Use Request and Response variables in the static web method - c#

Here is my code,
[WebMethod]
public static bool FirstAccess()
{
string app_id = "139295982898884";
string app_secret = "b5d2a88b56898610d54da2af498e3220";
//string post_login_url = "http://dev.fitbook.com.asp1-23.ord1-1.websitetestlink.com/v4/FitbookContest.aspx";
string post_login_url = "http://localhost:4327/FitbookContest.aspx";
string scope = "publish_stream,manage_pages";
string code = HttpContext.Current.Request["code"] ?? "";
try
{
if (code == "")
{
string dialog_url = "http://www.facebook.com/dialog/oauth?" + "client_id=" + app_id + "&redirect_uri=" + HttpContext.Current.Server.UrlEncode(post_login_url) + "&scope=publish_stream";
// HttpContext.Current.Response.Write(dialog_url);
//HttpContext.Current.Response.Redirect(dialog_url, true);
return false;
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}", app_id, HttpContext.Current.Request.Url.AbsoluteUri, scope, HttpContext.Current.Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")), token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
access_token = tokens["access_token"];
TestFB.GetProfilePic(code);
return true;
}
}
catch (Exception ex)
{
return false;
}
}
Here the lines like
HttpContext.Current.Request["code"] ?? "";
and
HttpContext.Current.Response.Redirect(dialog_url, true);
are not working. So is there any alternative solution for it? Is there any way to use it?

Have you tried this,
string dialog_url = "~http://www.facebook.com/dialog/oauth?" + "client_id=" + app_id + "&redirect_uri=" + HttpContext.Current.Server.UrlEncode(post_login_url) + "&scope=publish_stream";
and, redirect as false indicate Whether execution of current page should terminate
HttpContext.Current.Response.Redirect(dialog_url,false);
Simply try this:
string code = HttpContext.Current.Request["code"];
if (code==null)
{
// code
}
and I think the problem is in the line. You didn't specify accesstoken
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}", app_id, HttpContext.Current.Request.Url.AbsoluteUri, scope, HttpContext.Current.Request["code"].ToString(), app_secret);

Related

How to do DIGEST with POST, PUT and PATCH

I am at a total loss here. Im currently having success doing a GET request against a web service that implements DIGEST MD5-sess authentication. This works fine. I get the expected result so I figure my 'BUILD DIGEST AUTH HEADER' method works as intended.
I then get the requirement to also support POST, PUT and PATCH but now I run into a whole heap of problems. First request obviously returns a 401 and I read the info in the WWW-Authenticate header and make a MD5-sess auth header taking into account that this is now a POST, PUT or PATCH request.
var methodString = urlResolverStrategy.ResolverDataModel.HttpMethod.ToString();
var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", methodString, dir));
I keep everything the same but do also obviously add the content to the request on POST, PUT and PATCH. But for some reason I cannot figure out Im locked out of the service. Second request return another 401 even.
Is there something special that needs to be done for DIGEST Auth when method is POST, PUT and PATCH that Im missing?
I have all my requests setup in Postman as well put Postman does not have the same problem. Second call in Postman gets the expected results. A 200 and the expected data on POST, PUT and PATCH.
Im using a slightly modified version DigestAuthFixer.cs that's also available on some other posts here in stackoverflow.
Code below is currently hardcoded to use the MD5-sess method.
public class DigestAuthFixer
{
private static readonly Random random = new Random(DateTime.Now.Millisecond);
private readonly AuthData authData;
readonly UrlResolverStrategyBase urlResolverStrategy;
public HttpStatusCode StatusCode { get; private set; }
public DigestAuthFixer(BasicAuth basicAuth, UrlResolverStrategyBase urlResolverStrategy)
{
// TODO: Complete member initialization
authData = new AuthData
{
Host = urlResolverStrategy.GetHostName(),
User = basicAuth.GetUsername(),
Password = basicAuth.GetPassword(),
};
this.urlResolverStrategy = urlResolverStrategy;
}
private string CalculateMd5Hash(string input)
{
var inputBytes = Encoding.ASCII.GetBytes(input);
var hash = MD5.Create().ComputeHash(inputBytes);
var sb = new StringBuilder();
foreach (var b in hash)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
private string GrabHeaderVar(string varName, string header)
{
var regHeader = new Regex(string.Format(#"{0}=""([^""]*)""", varName));
var matchHeader = regHeader.Match(header);
if (matchHeader.Success)
{
return matchHeader.Groups[1].Value;
}
throw new ApplicationException(string.Format("Header {0} not found", varName));
}
private string GetDigestHeader(string dir)
{
authData.NC++;
string ha1;
if (authData.Algorithm == "MD5-sess")
{
var ha0 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", authData.User, authData.Realm, authData.Password));
ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", ha0, authData.Nonce, authData.Cnonce));
}
else
{
ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", authData.User, authData.Realm, authData.Password));
}
var methodString = urlResolverStrategy.ResolverDataModel.HttpMethod.ToString();
var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", methodString, dir));
var digestResponse = CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, authData.Nonce, authData.NC, authData.Cnonce, authData.Qop, ha2));
var authString = string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", algorithm=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\", response=\"{8}\"", authData.User, authData.Realm, authData.Nonce, dir, authData.Algorithm, authData.Qop, authData.NC, authData.Cnonce, digestResponse);
return authString;
}
public string GrabResponse(string nUrl, string content)
{
var uri = new Uri(authData.Host + nUrl);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = urlResolverStrategy.ResolverDataModel.HttpMethod.ToString();
// If we've got a recent Auth header, re-use it!
if (!string.IsNullOrEmpty(authData.Cnonce) && DateTime.Now.Subtract(authData.CnonceDate).TotalHours < 1.0)
{
request.Headers.Add("Authorization", GetDigestHeader(nUrl));
}
if (!string.IsNullOrEmpty(urlResolverStrategy.ResolverDataModel.IfMatchHeaderValue))
{
request.Headers.Add(HttpHelper.IfMatchHeaderName, urlResolverStrategy.ResolverDataModel.IfMatchHeaderValue);
}
AddContentToBody(request, content);
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
StatusCode = response.StatusCode;
}
catch (WebException ex)
{
// Try to fix a 401 exception by adding a Authorization header
if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
throw;
var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
authData.Realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
authData.Nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
authData.Qop = GrabHeaderVar("qop", wwwAuthenticateHeader);
authData.Algorithm = "MD5-sess"; // GrabHeaderVar("algorithm", wwwAuthenticateHeader);
authData.NC = 0;
authData.Cnonce = RandomString(8);
authData.CnonceDate = DateTime.Now;
string debug = wwwAuthenticateHeader + Environment.NewLine + nUrl + Environment.NewLine + uri.ToString() + Environment.NewLine + authData.ToString();
var digestRequest = (HttpWebRequest)WebRequest.Create(uri);
digestRequest.Method = urlResolverStrategy.ResolverDataModel.HttpMethod.ToString();
AddContentToBody(digestRequest, content);
var authHeader = GetDigestHeader(nUrl);
debug += uri.ToString() + Environment.NewLine;
debug += nUrl + Environment.NewLine;
debug += authHeader + Environment.NewLine;
digestRequest.Headers.Add("Authorization", authHeader);
if (!string.IsNullOrEmpty(urlResolverStrategy.ResolverDataModel.IfMatchHeaderValue))
{
request.Headers.Add(HttpHelper.IfMatchHeaderName, urlResolverStrategy.ResolverDataModel.IfMatchHeaderValue);
}
HttpWebResponse digestResponse = null;
try
{
//return authHeader;
digestResponse = (HttpWebResponse)digestRequest.GetResponse();
StatusCode = digestResponse.StatusCode;
response = digestResponse;
}
catch (Exception digestRequestEx)
{
if (digestResponse != null)
{
StatusCode = response.StatusCode;
}
else
{
StatusCode = HttpStatusCode.InternalServerError;
}
//return "It broke" + Environment.NewLine + debug;
return "There was a problem with url, username or password (" + digestRequestEx.Message + ")";
}
}
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
public string RandomString(int length)
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[length];
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
return new string(stringChars);
}
private void AddContentToBody(HttpWebRequest request, string content)
{
if (string.IsNullOrEmpty(content))
return;
var data = Encoding.Default.GetBytes(content); // note: choose appropriate encoding
request.ContentLength = data.Length;
request.ContentType = HttpHelper.MediaTypes.Json;
request.Accept = "*/*";
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
//request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(content);
}
}
}
internal class AuthData
{
public string Host;
public string User;
public string Password;
public string Realm;
public string Nonce;
public string Qop;
public string Cnonce;
public DateTime CnonceDate;
public int NC;
public string Algorithm;
public override string ToString()
{
string newLine = Environment.NewLine;
string result = Host + newLine;
result += User + newLine;
result += Realm + newLine;
result += Nonce + newLine;
result += Qop + newLine;
result += Cnonce + newLine;
result += CnonceDate + newLine;
result += NC + newLine;
result += Algorithm + newLine;
return result;
}
}
So apparently it matters in which order you add all the headers to the request. With hookbin I was able to detect that even though I have put an Authorization header on my digestRequest object it did not follow through to hookbin.
My placing the Authorization header addition to just below the setting the method line it all works...
I had no idea that that could pose a problem. The reason my GET method work is because is because 'content' is empty so no headers are added.
var digestRequest = (HttpWebRequest)WebRequest.Create(uri);
digestRequest.Method = urlResolverStrategy.ResolverDataModel.HttpMethod.ToString();
digestRequest.Headers.Add("Authorization", GetDigestHeader(nUrl));

c# URL POST Web API

I'm trying to do a function which work with WECHAT API,
Here is my code:
I use the code below to get a connection Token
internal static string Token(string CorpID, string Secret)
{
CorpID = CorpID ?? "wwe1f80304633";
Secret = Secret ?? "Ev7_oVN7RqD9k4yUy5pzkfcZ_QhX9l0VjZnAQ";
string token;
using (var wc = new WebClient())
{
token = wc.DownloadString($"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CorpID}&corpsecret={Secret}");
}
if (token.Contains("access_token"))
{
return token.Split(',')[2].Split(':')[1].Replace("\"", "");
}
return "";
}
It's successful to get a valid token from WECHAT Server,
And the code below is I want to POST a request to WECHAT API and ask WECHAT to Send Message to selected Department Person.
internal static string SendMsg(string sendtext)
{
string ACTOKEN = "" + PDC.MSGTOKEN + "";
string CONTENT = "" + PDC.CONTENT + "";
string PostUrl;
using (var wc2 = new WebClient())
{
PostUrl = wc2.UploadString($"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}{1}", ACTOKEN, CONTENT);
}
return "";
}
public static void SendMsg2()
{
PDC.CONTENT = "Test Message";
string MsgContent = "{\"toparty\": \"" + PDC.DEPTID + "\",\"msgtype\": \"text\",\"agentid\": \"" + PDC.AGENTID + "\",\"text\": {\"content\": \"" + PDC.CONTENT + "\"},\"safe\":0}";
SendMsg(MsgContent);
MessageBox.Show("" + MsgContent + "");
}
And I Added a button on my WinForm and trying to make it work
private void BtnSendMsg_Click(object sender, EventArgs e)
{
string token = MSG.Token(null, null);
if (!string.IsNullOrEmpty(token))
{
PDC.MSGTOKEN = token;
MessageBox.Show("" + PDC.MSGTOKEN + "");
}
else
{
MessageBox.Show(" Invalid Token ");
}
MSG.SendMsg2();
}
However seems it doesn't work, and if I'm not wrong the problem on this part
internal static string SendMsg(string sendtext)
{
string ACTOKEN = "" + PDC.MSGTOKEN + "";
string CONTENT = "" + PDC.CONTENT + "";
string PostUrl;
using (var wc2 = new WebClient())
{
PostUrl = wc2.UploadString($"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}{1}", ACTOKEN, CONTENT);
}
return "";
}
May anyone can give me some ideas how I can solve this problem ? Many Many Many Thanks ~
I has been done my Code without Problem, this is the code below for everyone who need.
The code to get Token from Https API
internal static string Token(string CorpID, string Secret)
{
CorpID = CorpID ?? "" + PDC.CorpID + "";
Secret = Secret ?? "" + PDC.Secret + "";
string token;
using (var wc = new WebClient())
{
token = wc.DownloadString($"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CorpID}&corpsecret={Secret}");
}
if (token.Contains("access_token"))
{
return token.Split(',')[2].Split(':')[1].Replace("\"", "");
}
return "";
}
The Method of POST
internal static string PostWebRequest(string PostUrl, string ParamData, Encoding DataEncode)
{
string ret = string.Empty;
try
{
byte[] byteArray = DataEncode.GetBytes(ParamData);
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(PostUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close();
}
catch (Exception ex)
{
return ex.Message;
}
return ret;
}
The code to using WECHAT WORK for sending Message
internal static string SendMsg(string CorpID, string Secret, string ParamData, Encoding DataEncode)
{
string AccessToken = Token(CorpID, Secret);
string PostUrl = string.Format("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}", AccessToken);
return PostWebRequest(PostUrl, ParamData, DataEncode);
}
public static void SendMsg2()
{
string sCorpID = "" + PDC.CorpID + "";
string sSecret = "" + PDC.Secret + "";
PDC.CONTENT = "Test Message";
string Message = "Test";
string MsgContent = "{";
MsgContent += "\"totag\": \"" + PDC.DEPTID + "\",";
MsgContent += "\"msgtype\": \"text\",";
MsgContent += "\"agentid\": \"" + PDC.AGENTID + "\",";
MsgContent += "\"text\": {";
MsgContent += " \"content\": \"" + Message + "\"";
MsgContent += "},";
MsgContent += "\"safe\":\"0\"";
MsgContent += "}";
SendMsg(sCorpID, sSecret, MsgContent, Encoding.UTF8);
}
The Button Event for active Send Message Function
private void BtnSendMsg_Click(object sender, EventArgs e)
{
string token = MSG.Token(null, null);
if (!string.IsNullOrEmpty(token))
{
PDC.MSGTOKEN = token;
}
MSG.SendMsg2();
}

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>"}

Facebook active token failure C# HttpWebRequest

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.

Why Yammer Post Message Error 500?

While posting messages, Yammer is throwing the following error (and not posting the message):
The remote server returned an error: (500) Internal Server Error.
I'm using Yammer .NET wrapper and it's working fine with REST call "https://www.yammer.com/api/v1/messages.json", but posting message gives the above error.
Below is the code giving us the error message,
String consumerkey = "consumerkey";
String clientsecret = "clientsecret";
WebProxy webpro = new WebProxy("ourproxyserver",8080)
webpro.BypassProxyOnLocal = true;
webpro.Credentials = CredentialCache.DefaultCredentials;
String access_token = "https://www.yammer.com/oauth2/access_token.json"+
"?client_id=clientid&"+
"client_secret=cli_secret&code=code_id";
Yammer.Session session = new Yammer.Session(
new OAuth.OAuthKey(
consumerkey, clientsecret, access_token,"token"
),
webpro);
NameValueCollection parameters = new NameValueCollection();
parameters.Add("body", body);
response = Yammer.HttpUtility.Post(Resources.YAMMER_MESSAGES_CREATE, parameters, session);
Any ideas what could be wrong?
You can try following wrapper method to post message on yammer (Please note that this code uses Auth and Authbase class:
public static string PostMessage(string body)
{
NameValueCollection parameters = new NameValueCollection();
parameters.Add("body", body);
string response = string.Empty;
response = Post("https://www.yammer.com/api/v1/messages/", parameters);
return response;
}
public static string Post(string url, NameValueCollection parameters)
{
string nonce, timestamp;
string fullUrl = EncodeUrl(url, parameters);
string signature = GetSignature(WebMethod.POST, fullUrl, out timestamp, out nonce);
HttpWebRequest request = CreateWebRequest(url, WebMethod.POST, nonce, timestamp, signature);
int count = 0;
string queryString = string.Empty;
foreach (string key in parameters.Keys)
{
if (count == 0)
queryString = key + "=" + Rfc3986.Encode(parameters[key]);
else
queryString += "&" + key + "=" + Rfc3986.Encode(parameters[key]);
count++;
}
byte[] postDataBytes = Encoding.ASCII.GetBytes(queryString);
request.ContentLength = postDataBytes.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(postDataBytes, 0, postDataBytes.Length);
reqStream.Close();
WebResponse response = null;
string data = string.Empty;
try
{
response = request.GetResponse();
data = response.Headers["Location"];
}
catch (Exception ex)
{
//System.Windows.Forms.MessageBox.Show("Error retrieving web response " + ex.Message);
throw ex;
}
finally
{
if (response != null)
response.Close();
}
return data;
}
private static string EncodeUrl(string url, NameValueCollection parameters)
{
string fullUrl = string.Empty;
int count = 0;
foreach (string key in parameters.Keys)
{
if (count == 0)
fullUrl = url + "?" + key + "=" + Rfc3986.Encode(parameters[key].ToLower());
else
fullUrl += "&" + key + "=" + Rfc3986.Encode(parameters[key].ToLower());
count++;
}
return fullUrl;
}
public static string GetSignature(WebMethod method, string url, out string timestamp, out string nonce)
{
OAuthBase oAuth = new OAuthBase();
nonce = oAuth.GenerateNonce();
timestamp = oAuth.GenerateTimeStamp();
string nurl, nrp;
Uri uri = new Uri(url);
string sig = oAuth.GenerateSignature(
uri,
YOURCONSUMERKEY,
YOURCONSUMER_SECRET,
AuthToken,
AuthTokenSecret,
method.ToString(),
timestamp,
nonce,
OAuthBase.SignatureTypes.PLAINTEXT, out nurl, out nrp);
return System.Web.HttpUtility.UrlEncode(sig);
}
private static HttpWebRequest CreateWebRequest(string fullUrl, WebMethod method, string nonce, string timeStamp, string sig)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUrl);
request.Method = method.ToString();
request.Proxy = Yammer.Session.WebProxy;
string authHeader = CreateAuthHeader(method, nonce, timeStamp, sig);
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Authorization", authHeader);
return request;
}
private static string CreateAuthHeader(WebMethod method, string nonce, string timeStamp, string sig)
{
var sb = new StringBuilder();
sb.Append("OAuth ");
if (method == WebMethod.POST)
sb.Append("realm=\"" + "\",");
else
sb.Append("realm=\"\",");
string authHeader = "oauth_consumer_key=\"" + YOURCONSUMERKEY + "\"," +
"oauth_token=\"" + YOURAUTHTOKEN + "\"," +
"oauth_nonce=\"" + nonce + "\"," +
"oauth_timestamp=\"" + timeStamp + "\"," +
"oauth_signature_method=\"" + "HMAC-SHA1" + "\"," +
"oauth_version=\"" + "1.0" + "\"," +
"oauth_signature=\"" + sig + "\"";
sb.Append(authHeader);
return sb.ToString();
}

Categories

Resources