Facebook active token failure C# HttpWebRequest - c#

I obtain an access_token OK from Facebook, but whenever I try to use it, it fails (bad request).
It looks like the access_token is not being sent to the server correctly. I have used Server.UrlEncode to encode it.
Any ideas what I am doing wrong?
string ourAccessToken = "unknown";
//--------------------------------------
protected void Page_Load(object sender, EventArgs e)
{
getAccessToken();
getMe();
}
// -----------------------
private void getAccessToken()
{
string result = "unknown";
try
{
// get app access token
string thisURL = "https://graph.facebook.com/oauth/access_token";
thisURL += "?client_id=" + ourClientID;
thisURL += "&client_secret=" + ourClientSecret;
thisURL += "&grant_type=client_credentials";
thisURL += "&redirect_uri=" + Server.UrlEncode(ourSiteRedirectURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( thisURL);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode rc = response.StatusCode;
if( rc == HttpStatusCode.OK)
{
StreamReader Sreader = new StreamReader( response.GetResponseStream());
result = Sreader.ReadToEnd();
Sreader.Close();
}
response.Close();
}
catch (Exception exc)
{
result = "ERROR : " + exc.ToString();
}
Response.Write( "<br>result=[" + result + "]");
// extract accessToken
string accessToken = "";
int equalsAt = result.IndexOf( "=");
if( equalsAt >= 0 && result.Length > equalsAt) accessToken = (result.Substring( equalsAt + 1)).Trim();
Response.Write( "<br>accessToken=[" + accessToken + "]");
ourAccessToken = accessToken;
}
// -----------------------
private void getMe()
{
string result = "unknown";
try
{
string thisURL = "https://graph.facebook.com/me?access_token=" + Server.UrlEncode(ourAccessToken);
Response.Write("<br>thisURL=" + thisURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( thisURL);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode rc = response.StatusCode;
if( rc == HttpStatusCode.OK)
{
StreamReader Sreader = new StreamReader( response.GetResponseStream());
result = Sreader.ReadToEnd();
Sreader.Close();
}
response.Close();
}
catch (Exception ex)
{
Response.Write("<br>getMe Exc: " + ex.Message.ToString() + "<br>");
}
Response.Write("<br>getMe result = " + result + "<br><br>");
}
Thanks

Right settings in App-Dashboard? If you active "Native/Desktop" you can not send API-Calls with this method, see:
https://developers.facebook.com/docs/facebook-login/access-tokens?locale=en_US#apptokens

After a lot of trial and error, I conclude that an App Access Token is not relevant, and that the ClientID and ClientSecret should be used directly. I want my App to generate a set of photographs of registered users. Because the server is making the call, there is no meaning to "me". A set of data can be obtained by preparing a batch process:
string p1 = "access_token=" + Server.UrlEncode(ourClientID + "|" + ourClientSecret);
string p2 = "&batch=" +
Server.UrlEncode( " [ { \"method\": \"get\", \"relative_url\": \"" + chrisFBID + "?fields=name,picture.type(square)\" }, " +
" { \"method\": \"get\", \"relative_url\": \"" + johnFBID + "?fields=name,picture.type(large)\" }, " +
" { \"method\": \"get\", \"relative_url\": \"" + stephFBID + "?fields=name,picture.type(large)\" } ]");
string responseData = "";
try
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/");
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
byte[] bytedata = Encoding.UTF8.GetBytes(p1 + p2);
httpRequest.ContentLength = bytedata.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
responseData = reader.ReadToEnd();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString() + "<br>");
}
Response.Write("<br>" + responseData + "<br><br>");
I also conclude that the FB documentation suffers from the usual fatal flaw of documentation: it has been written by an expert and never tested on a novice user before release.

Related

How to fetch Json value and fill it on dataset in ASP.NET

I am trying to fetch JSON value but failed to retrieve value and fill on DataSet and bind them on GridView and I am getting null value.
Here I have tried code please seen below:
var outputValue = cpmu.getCPMUdata(AgreementNo, AgreementedBy, YearOfAgreement);
var serializer = new JavaScriptSerializer();
dynamic obj = serializer.Deserialize<dynamic>(outputValue);
var data = obj["data"];
StringReader theReader = new StringReader(data);
DataSet theDataSet = new DataSet();
theDataSet.ReadXml(theReader);
var result = theDataSet.Tables[0];
Label3.Text = theDataSet.Tables[0].Rows[0].Field<string>("AgreementNo");
Label2.Text = theDataSet.Tables[0].Rows[0].Field<string>("Agreementby");
Label4.Text = theDataSet.Tables[0].Rows[0].Field<string>("YearofAgreement");
GridView2.DataSource = theDataSet;
GridView2.DataMember = theDataSet.Tables["Bill"].ToString();
GridView2.DataBind();
JSON code:
public string getCPMUdata(string AgreementNo, string Agreementby, string YearofAgreement)
{
//Code to accept the SSL server certificate
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
//Configuration Values
string strbaseUrl = System.Configuration.ConfigurationManager.AppSettings["baseUrl"];
string strLoginBaseUrl = System.Configuration.ConfigurationManager.AppSettings["LoginBaseUrl"];
String username = System.Configuration.ConfigurationManager.AppSettings["UserName"];
string password = System.Configuration.ConfigurationManager.AppSettings["Password"];
//***************
/* Input Values */
string strAgreementNo = AgreementNo;
string strAgreementby = Agreementby;
string strYearofAgreement = YearofAgreement;
/****************/
// Initialize the response
string returnvalue = string.Empty;
HttpWebResponse response = null;
HttpWebRequest request = null;
String responseText = null;
String authorization;
try
{
//Create the Request Url
String requestUrl = strLoginBaseUrl + "?service=" + HttpUtility.UrlEncodeUnicode(strbaseUrl + "/3DSpace/resources/CHiPSCPMSBillDetailsModeler/CHiPSCPMSBillDetails?AgreementNo=" + HttpUtility.UrlEncode(strAgreementNo) + "&Agreementby=" + HttpUtility.UrlEncode(strAgreementby) + "&YearofAgreement=" + HttpUtility.UrlEncode(strYearofAgreement));
request = WebRequest.Create(requestUrl) as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/json";
authorization = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + authorization);
response = request.GetResponse() as HttpWebResponse;
if (request.HaveResponse == true && response == null)
{
String msg = "response was not returned or is null";
throw new WebException(msg);
}
if (response.StatusCode != HttpStatusCode.OK)
{
String msg = "response with status: " + response.StatusCode + " " + response.StatusDescription;
throw new WebException(msg);
}
// get the first HTTP response content
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseText = reader.ReadToEnd();
//extract the LT code from the response string
String lt = "";
lt = responseText.Substring(responseText.LastIndexOf("\"lt\""));
lt = lt.Substring(0, lt.IndexOf(","));
lt = lt.Replace("\"lt\":", ",");
lt = lt.Replace("\"", "");
lt = lt.Replace("\"", "");
lt = lt.Replace(",", "");
//Extract Session ID from the response header
String strJsonId = "";
strJsonId = response.Headers["Set-Cookie"];
strJsonId = response.Headers["Set-Cookie"].Substring(strJsonId.LastIndexOf("JSESSIONID"));
strJsonId = strJsonId.Substring(0, strJsonId.IndexOf(";"));
strJsonId = strJsonId.Replace("JSESSIONID", "");
strJsonId = strJsonId.Replace("=", "");
strJsonId = strJsonId.Trim();
//throw exception if access token or sessionid is not available
if (lt == "" && strJsonId == "")
{
String msg = "Unable to retrieve Access Token and session Key";
throw new WebException(msg);
}
//Second HTTP Request to get the Data based on the 'lt' token, 'SessionID' and Query String parameters
WebRequest requestLast = WebRequest.Create(requestUrl);
requestLast.Headers.Add("Cookie", "JSESSIONID=" + strJsonId);
requestLast.Method = "POST";
string postData = "lt=" + lt + "&username=" + username + "&password=" + password;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
requestLast.ContentType = "application/x-www-form-urlencoded";
requestLast.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream1 = requestLast.GetRequestStream();
dataStream1.Write(byteArray, 0, byteArray.Length);
dataStream1.Close();
// Get the response.
WebResponse responseLast = requestLast.GetResponse();
dataStream1 = responseLast.GetResponseStream();
StreamReader reader1 = new StreamReader(dataStream1);
returnvalue = reader1.ReadToEnd();
// Clean up the streams.
reader.Close();
reader1.Close();
dataStream1.Close();
response.Close();
responseLast.Close();
}
catch (WebException e)
{
if (e.Response != null)
{
response = (HttpWebResponse)e.Response;
returnvalue = response.StatusCode + " " + response.StatusDescription;
}
else
{
returnvalue = e.Message;
}
}
finally
{
if (response != null)
{
response.Close();
}
}
return returnvalue;
}
public static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
Here in variable returnvalue, I get such type of error:
{"msg":"error","data":" NA
</AgreementNo> NA </Agreementby> NA
</YearofAgreement> \t\t No Data Found\t\t
</Bill>\t\t </xml>"}

Problems with PayPal API Http call

I've integrated an option for users to pay via PayPal their online shopping on the web shop that I'm creating. The problem came up suddenly when I started to get this error:
You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.
And the code for the Http call is as following:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost.ToString());
}
}
catch (Exception e)
{
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); // this is the line where the exception occurs...
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
Can someone help me out with this? It worked fine a day ago, now its giving me this error?
Okay so if anyone is interested, I was able to fix the error by adding the following line before creating the web request (I was able to fix it by going down to Tls12 like this):
`ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12`;
Cheers :-)
Edit try this:
public string HttpCall(string NvpRequest)
{
string url = pEndPointURL;
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode(BNCode);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
// Try using Tls11 if it doesnt works for you with Tls
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = WebRequestMethods.Http.Post;
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost.ToString());
}
}
catch (Exception e)
{
}
//Retrieve the Response returned from the NVP API call to PayPal.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
return result;
}
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;
//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + HttpUtility.UrlEncode( BNCode );
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost);
}
}
catch (Exception e)
{
/*
if (log.IsFatalEnabled)
{
log.Fatal(e.Message, this);
}*/
}
//Retrieve the Response returned from the NVP API call to PayPal
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}
//Logging the response of the transaction
/* if (log.IsInfoEnabled)
{
log.Info("Result :" +
" Elapsed Time : " + (DateTime.Now - startDate).Milliseconds + " ms" +
result);
}
*/
return result;
}
After a number of hours wasted, it turned out to be the Tls protocol version.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Authorize.NET test account working fine on local host but not on live site

i m testing authorize.net payments and it is working fine on local host payment processing is all good. but when i upload it to my live site with test accounts i get error with
**Object reference not set to an instance of an object. at Billing.readHtmlPage(String url)**
string[] authorizeServer = readHtmlPage("https://test.authorize.net/gateway/transact.dll").Split('|');
//Error is Here
if (authorizeServer[0].ToLower() == "approved" || authorizeServer[0].ToLower() == "1")
{
//Process Payment
}
private String readHtmlPage(string url)
{
String result = "";
//Test Account ID
String strPost =
"x_login=xxxxx"&x_type=AUTH_CAPTURE&x_method=CC&x_tran_key=xxxxx&x_relay_response=&FALSE&" + "x_card_num=" + ccNum.Text + "&x_exp_date=" + ddl_CCM.SelectedValue + "/" +
ddl_CCY.SelectedValue +
"&x_amount=" + lbl_Gtotal.Text +
"&x_first_name=" + ccFName.Text + "&x_last_name=" + ccLName.Text +
"&x_address=" + Server.UrlEncode(hf_street.Value) + "&x_city=" +
hf_city.Value +
"&x_state=" + hf_state.Value + "&x_zip=" + hf_zip.Value;
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
sr.Close();
}
return result;
}
Any Help would be nice and much helpful thanks

WebDAV Exchange 2003 failing when specifying a date

I am using the following code to retrieve emails from an Exchange 2003 server. All was working on Friday and now it fails.
From some investigation I have narrowed it to the targetDate variable. Seems if the date is in April it fails with a 400 back from the server. I have commented this line out and tried various dates 2012-3-29, 2012-4-1, 2012-4-10 (today) and the ones in April seem to fail.
Some kind of sick April fools joke?
The code itself is derived from this article: http://www.codeproject.com/Articles/42458/Using-Exchange-2003-with-Webdav-Send-Retrieve-Atta
public XmlDocument GetMailAll()
{
HttpWebRequest request = default(HttpWebRequest);
HttpWebResponse response = default(HttpWebResponse);
string rootUri = null;
string query = null;
byte[] bytes = null;
Stream requestStream = default(Stream);
Stream responseStream = default(Stream);
XmlDocument xmlDoc = default(XmlDocument);
xmlDoc = new XmlDocument();
try
{
DateTime targetDateTime = DateTime.Today.AddDays(-5);
String targetDate = ""+targetDateTime.Year + "-" + targetDateTime.Month + "-" + targetDateTime.Day;
rootUri = server + "/Exchange/" + alias + "/" + inbox;
query = "<?xml version=\"1.0\"?>"
+ "<D:searchrequest xmlns:D = \"DAV:\" xmlns:m=\"urn:schemas:httpmail:\">"
+ "<D:sql>SELECT \"urn:schemas:httpmail:hasattachment\", \"DAV:displayname\", "
+ "\"urn:schemas:httpmail:from\", \"urn:schemas:httpmail:subject\", "
//+ "\"urn:schemas:httpmail:htmldescription\"," //Return full body (not necessary right now)
+ "\"urn:schemas:httpmail:datereceived\", \"urn:schemas:httpmail:read\" FROM \"" + rootUri
+ "\" WHERE \"DAV:ishidden\" = false "
+ "AND \"DAV:isfolder\" = false "
//+ "AND \"urn:schemas:httpmail:read\" = false"
+ "AND \"urn:schemas:httpmail:datereceived\" >= CAST(\"" + targetDate + "T00:00:000Z\" AS 'dateTime.tz')"
+ "</D:sql></D:searchrequest>";
request = (HttpWebRequest)WebRequest.Create(rootUri);
request.Timeout = 5000;
request.Credentials = new NetworkCredential(alias, password, domain);
request.Method = "SEARCH";
request.ContentType = "text/xml";
request.Headers.Add("Translate", "F");
bytes = System.Text.Encoding.UTF8.GetBytes(query);
request.ContentLength = bytes.Length;
requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
response = (HttpWebResponse)request.GetResponse();
authCookies = new List<Cookie>();
foreach(Cookie cookie in response.Cookies)
{
authCookies.Add(cookie);
}
responseStream = response.GetResponseStream();
xmlDoc.Load(responseStream);
responseStream.Close();
}
catch (WebException ex)
{
if (ex.Response == null)
{
throw new Exception();
}
else if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized)
{
throw new ExchangeCatastrophicException();
}
else
{
throw new ExchangeFailedException();
}
}
catch (Exception ex)
{
throw;
}
return xmlDoc;
}
Finally got it working. The exact targetDate to cast including the T00:00:..Z part must match the specification on http://msdn.microsoft.com/en-us/library/aa123600%28v=exchg.65%29.aspx
I now have:
DateTime targetDateTime = DateTime.Today;
string targetDate = targetDateTime.ToString("yyyy-MM-dd");
snip
+ "AND \"urn:schemas:httpmail:datereceived\" >= CAST(\"" + targetDate + "T00:00:00Z" + "\" AS 'dateTime.tz')"
Note that the seconds part is two zero's instead of three.

Codemetric optimized httpwebrequest in C#

the problem is the httpwebrequest method in my c# program. visual studio gives it a metric of 60, thats pretty lame.. so how can i program it more efficient? (:
my actual code:
public string httpRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Proxy = WebRequest.DefaultWebProxy;
request.MediaType = "HTTP/1.1";
request.ContentType = "text/xml";
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(StreamReader streamr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
String sresp = streamr.ReadToEnd();
return sresp;
}
thanks for helping. ;)
Well, firstly I wouldnt let a number rule my code :)
However, using WebClient may simplify things quite a bit - less code to be counted. I'm not at a PC but that looks like a single DownloadString call, plus a few request headers.
http://msdn.microsoft.com/en-us/library/fhd1f0sw(v=VS.100).aspx
Oh, and add some using statements around all the IDisposable objects you create.
Here's the code I use in a social networking class I built which interacts with Twitter, Facebook, Tumblr, etc. Modify as you see fit. Also, I don't know what "metric" it would be given by VS, but if you're referring to the "Calculate Code Metrics" a 60 is still good. 20 to 100 is considered to be well maintainable, so I wouldn't worry too much.
protected string Request(
string Method,
Uri Endpoint,
string[][] Headers,
string Params) {
try {
ServicePointManager.Expect100Continue = false;
HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(Endpoint);
Request.Method = Method;
if (Method == "POST") {
Request.ContentLength = Params.Length;
Request.ContentType = "application/x-www-form-urlencoded";
};
for (byte a = 0, b = (byte)Headers.Length; a < b; a++) {
Request.Headers.Add(Headers[a][0], Headers[a][1]);
};
if (!String.IsNullOrWhiteSpace(Params)) {
using (StreamWriter Writer = new StreamWriter(Request.GetRequestStream())) {
Writer.Write(Params);
};
};
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
Request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointDelegate);
using (StreamReader Reader = new StreamReader(Response.GetResponseStream())) {
string R = Reader.ReadToEnd();
try {
Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Headers[0][1] + "</p><p>" + Params + "</p><p>" + R + "</p>");
} catch (Exception) {
Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Params + "</p><p>" + R + "</p>");
};
return (R);
};
} catch (WebException Ex) {
try {
if (Ex.Status != WebExceptionStatus.Success) {
using (StreamReader Reader = new StreamReader(Ex.Response.GetResponseStream())) {
string R = Reader.ReadToEnd();
try {
Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Headers[0][1] + "</p><p>" + Params + "</p><p>" + R + "</p>");
} catch (Exception) {
Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Params + "</p><p>" + R + "</p>");
};
return (R);
};
};
} catch (Exception) {
// Ignore
};
return (string.Empty);
} catch (Exception) {
return (string.Empty);
};
}
private IPEndPoint BindIPEndPointDelegate(
ServicePoint ServicePoint,
IPEndPoint RemoteEndPoint,
int Retries) {
if (String.IsNullOrWhiteSpace(this.IPEndpoint)) {
return new IPEndPoint(IPAddress.Any, 5000);
} else {
return new IPEndPoint(IPAddress.Parse(this.IPEndpoint), 5000);
};
}

Categories

Resources