I am trying to set up Google reCaptcha on ASP.NET web forms but it is not visible.
So far I took the following approach:
At the beginning of the .ascx page:
<%# Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>
And the following in the form I want it to show:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
<recaptcha:RecaptchaControl
ID="recaptcha"
runat="server"
PublicKey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
PrivateKey="_My private key taken from the reCaptcha API_"
/>
However, when I run the page, the reCaptcha is not visible.
Any help is appreciated. Thanks
Looks like you're using the old reCaptcha.
Google deprecated it, and encourages you to switch to NoCaptcha re Captcha 2.
Here's how you do it:
page.aspx
<html>
<head>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<form>
page.aspx.cs
public partial class page : System.Web.UI.Page
{
private string CAPTCHA_SECRET_KEY = #"6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe"; // WARNING: FAKE SECRET KEY
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
String username = unameInput.Text;
String password = pwordInput.Text;
if (validate())
{
// ...
}
}
}
// Thanks to http://www.thatsoftwaredude.com/content/6235/implementing-googles-no-captcha-recaptcha-in-aspnet
private bool validate()
{
string url = #"https://www.google.com/recaptcha/api/siteverify";
WebRequest request = WebRequest.Create(url);
string postData = string.Format("secret={0}&response={1}&remoteip={2}", CAPTCHA_SECRET_KEY, Request["g-recaptcha-response"], Request.UserHostAddress);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(postData);
writer.Close();
StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream());
string responseData = reader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
CaptchaResponse cResponse = jss.Deserialize<CaptchaResponse>(responseData);
return cResponse.success;
}
catch(WebException)
{
return true; // TODO: Change to false when releasing
}
}
class CaptchaResponse
{
public bool success { get; set; }
}
use this. create a external class
public class Recaptcha
{
public bool ValidateCaptcha(string sitekey, string responseRecaptcha)
{
//var response = Request["g-recaptcha-response"]; //part of the parameter << you need to pass this as your responseRecaptcha
//secret that was generated in key value pair
//part of the parameter
var client = new WebClient();
var reply =
client.DownloadString(
string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",sitekey,responseRecaptcha));
var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);
string status = "";
//when response is false check for the error message
if (!captchaResponse.Success)
{
if (captchaResponse.ErrorCodes.Count <= 0) return true;
var error = captchaResponse.ErrorCodes[0].ToLower();
switch (error)
{
case ("missing-input-secret"):
status = "The secret parameter is missing.";
return false;
break;
case ("invalid-input-secret"):
status = "The secret parameter is invalid or malformed.";
return false;
break;
case ("missing-input-response"):
status = "The response parameter is missing.";
return false;
break;
case ("invalid-input-response"):
status = "The response parameter is invalid or malformed.";
return false;
break;
default:
status = "Error occured. Please try again";
return false;
break;
}
}
else
{
status = "Valid";
}
return true;
}
}
internal class CaptchaResponse
{
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("error-codes")]
public List<string> ErrorCodes { get; set; }
}
Related
I have created a Windows Form Application Function to validate an Api. But the code is breaking ar Deserialize Line. I need to check for Status . If Status=1 is stored in StatusCode string. I can proceed ahead. Please assist.
Function Code :
private void Validate_CW_Account(string Company_Code , string Username , string Password)
{
try
{
string sURL = "";
string baseURL = "https://www.compelapps.in/efacilito_UAT_Api/api/CocktailWorld/Validate_CW_Account_Migration?";
sURL = baseURL+ "StrCompanyCode=" + Company_Code + "&StrUsername=" + Username + "&StrPassword=" + Password;
var client = new RestClient(sURL);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", sURL, ParameterType.QueryString);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
string json_response = response.Content.ToString();
CW_API_Response cw = JsonConvert.DeserializeObject<CW_API_Response>(json_response);
string StatusCode = cw.Status;
if (StatusCode == "1")
{
lbl_AccountConn_Status.Text = "SUCCESSFUL";
lbl_AccountConn_Status.BackColor = System.Drawing.Color.GreenYellow;
lbl_AccountConn_Status.ForeColor = System.Drawing.Color.Black;
}
else
{
lbl_AccountConn_Status.Text = "AUTHENTICATION FAILED";
lbl_AccountConn_Status.BackColor = System.Drawing.Color.Red;
lbl_AccountConn_Status.ForeColor = System.Drawing.Color.White;
}
}
catch (Exception ex)
{
throw ex;
}
}
Class File Code :
public class CW_API_Response
{
public string Status { get; set; }
public string Company_ID { get; set; }
}
If the JSON returned by API is [ { "Company_ID": 11, "Status": 1 } ] then you need to read JSON List. You are not reading list. You are assuming single value.
Try this:
List<CW_API_Response> cw = JsonConvert.DeserializeObject<List<CW_API_Response>>(json_response);
string StatusCode = cw[0].Status.ToString();
Few days back i learnt making reports in power BI and it was great experience learning power BI. As i am creating a dashboard for my MVC based web application, i wanted to make look and fill of my dashboard attractive. I am thinking of embedding power BI report with that for that i have used following code inside view :-
<body>
<script type="text/javascript" src="~/Scripts/PowerBI/powerbi.js"></script>
<script type="text/javascript">
window.onload = function () {
var iframe = document.getElementById("iFrameEmbedReport");
iframe.src = "https://app.powerbi.com/reportEmbed?reportId=" + embedReportId;
iframe.onload = postActionLoadReport;
}
function postActionLoadReport() {
var m = {
action: "loadReport",
accessToken: accessToken
};
message = JSON.stringify(m);
iframe = document.getElementById("iFrameEmbedReport");
iframe.contentWindow.postMessage(message, "*");;
}
</script>
<style>
#iFrameEmbedReport {
width: 95%;
height: 95%;
}
</style>
<iframe ID="iFrameEmbedReport"></iframe>
</body>
And code for controller is given below :-
public class DashBoardController : Controller
{
string baseUri = WebConfigurationManager.AppSettings["PowerBiDataset"];
string AccessToken = string.Empty;
// GET: DashBoard
public ActionResult DashBoard()
{
if (Request.Params.Get("code") != null)
{
Session["AccessToken"] = GetAccessToken(
Request.Params.GetValues("code")[0],
WebConfigurationManager.AppSettings["ClientID"],
WebConfigurationManager.AppSettings["ClientSecret"],
WebConfigurationManager.AppSettings["RedirectUrl"]);
Response.Redirect("~/DashBoard/DashBoard");
}
if (Session["AccessToken"] != null)
{
AccessToken = Session["AccessToken"].ToString();
GetReport(0);
}
return View();
}
protected void GetReport(int index)
{
System.Net.WebRequest request = System.Net.WebRequest.Create(
String.Format("{0}/Reports",
baseUri)) as System.Net.HttpWebRequest;
request.Method = "GET";
request.ContentLength = 0;
request.Headers.Add("Authorization", String.Format("Bearer {0}", AccessToken));
using (var response = request.GetResponse() as System.Net.HttpWebResponse)
{
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
{
PBIReports Reports = JsonConvert.DeserializeObject<PBIReports>(reader.ReadToEnd());
if (Reports.value.Length > 0)
{
var report = Reports.value[index];
ViewData["AccessToken"] = Session["AccessToken"].ToString();
ViewData["EmbedURL"] = report.embedUrl;
ViewData["ReportID"] = report.id;
}
}
}
}
public void GetAuthorizationCode()
{
var #params = new NameValueCollection
{
{"response_type", "code"},
{"client_id", WebConfigurationManager.AppSettings["ClientID"]},
{"resource", WebConfigurationManager.AppSettings["PowerBiAPI"]},
{ "redirect_uri", WebConfigurationManager.AppSettings["RedirectUrl"]}
};
var queryString = HttpUtility.ParseQueryString(string.Empty);
queryString.Add(#params);
Response.Redirect(String.Format(WebConfigurationManager.AppSettings["AADAuthorityUri"] + "?{0}", queryString));
}
public string GetAccessToken(string authorizationCode, string clientID, string clientSecret, string redirectUri)
{
TokenCache TC = new TokenCache();
string authority = WebConfigurationManager.AppSettings["AADAuthorityUri"];
AuthenticationContext AC = new AuthenticationContext(authority, TC);
ClientCredential cc = new ClientCredential(clientID, clientSecret);
return AC.AcquireTokenByAuthorizationCode(
authorizationCode,
new Uri(redirectUri), cc).AccessToken;
}
}
public class PBIReports
{
public PBIReport[] value { get; set; }
}
public class PBIReport
{
public string id { get; set; }
public string name { get; set; }
public string webUrl { get; set; }
public string embedUrl { get; set; }
}
As i think, I am doing everything right but i don't know why it's not able to display report. Please suggest me if i did any mistake in the above given code.
It's not clear where the error is, as you provided lots of code and no specfics on the error itself. Here are few things to note:
To embed Power BI content in your HTML you just need an empty div element
Too much code overall.
You need to perform following steps:
Acquire authentication token by using AuthenticationContext.AcquireTokenAsync with credentials provisioned on Power BI side
Instantiate PowerBIClient with the token you just obtained. That's the token for your application. Never pass it to users. Don't store in Session as it'll expire. PowerBIClient(new Uri(_Context.ApiUrl), new TokenCredentials(authResult.AccessToken, "Bearer"))
Obtain ID(s) of content that's available in Power BI. There are different APIs for different types (dashboards, reports, tiles) as well as for content that's in Groups(workspaces) or not, e.g. client.Dashboards.GetDashboardsInGroupAsync(GroupId). This step could be skipped if you already know what type of content you're getting and its ID. Keep in mind that if EmbedUrl property is empty on returned object(s) you won't be able to render, even if you manually construct such url.
Obtain Embed Token for particular content. There are different methods available, e.g. client.Reports.GenerateTokenInGroupAsync(GroupId, Id-of-content, new GenerateTokenRequest(accessLevel: "view"))
The final step is to apply Embed Token and EmbedUrl on the client-side. Something among following lines:
.
var embedToken = $('#embedToken').val();
var txtEmbedUrl = $('#txtReportEmbed').val();
var txtEmbedReportId = $('#txtEmbedReportId').val();
var models = window['powerbi-client'].models;
var permissions = models.Permissions.All;
var config= {
type: 'report',
tokenType: models.TokenType.Embed,
accessToken: embedToken,
embedUrl: txtEmbedUrl,
id: txtEmbedReportId,
permissions: permissions,
settings: {
filterPaneEnabled: true,
navContentPaneEnabled: true
}
};
var embedContainer = $('#embedContainer')[0];
var report = powerbi.embed(embedContainer, config);
You should be able to test your stuff here. Just plugin your values.
You can also observe sample app here]2. Flow provided above is for "app owns data" case.
Can anyone help me with the correct notation of receiving a JSON POST request in PHP and a working (and aligned) C Sharp script for sending the POST request. I want a decentral login on my PC (with C Sharp software) which uses a JSON POST request to connect to my MySQL database (through a PHP 7.1.1 plugin) on my webspace. I can see the Exceptions (so the JSON feedback is received properly) which the script returns but the PHP POST superglobal keeps coming up empty (on the request side).
My C Sharp script:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Windows.Forms;
namespace HBI_Statistics_UI
{
public partial class Login : Form
{
public class API_Response
{
public bool IsError { get; set; }
public string ErrorMessage { get; set; }
public string ResponseData { get; set; }
}
public Login()
{
InitializeComponent();
}
private void buttonLogin_Click(object sender, EventArgs e)
{
try
{
// request params
var apiUrl = "http://www.home-business-intelligence.net/plugin/HBI-Statistics/login.php";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "json=" + "{\"Email\":\"" + textBox1.Text + "\"," +
"\"Pwd\":\"" + textBox2.Text + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
API_Response r = JsonConvert.DeserializeObject<API_Response>(result);
// check response
if (r.ResponseData == "Success")
{
this.Hide();
ProgramMainUI pr = new ProgramMainUI();
pr.Show();
}
else
{
MessageBox.Show(r.ErrorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (System.Net.WebException ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Newtonsoft.Json.JsonReaderException ne)
{
MessageBox.Show(ne.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
My PHP Script:
include ("library.php");
try
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// Post Request
$api_data = strip_tags(isset($_POST['json']) ? $_POST['json'] : '');
// Validate Request
if (empty($api_data))
{
throw new Exception('Invalid request!! Please provide login details.' . print_r($api_data));
}
if (!empty($api_data))
{
// Decode json
$data = json_decode($api_data, true);
// Set connection
$conn = Connection::Conn_2();
// Sanitize data for query
$pwd = mysqli_real_escape_string($conn, $data->json->Pwd);
$email = mysqli_real_escape_string($conn, $data->json->Email);
$pwd2 = VanillaSpecial::Hash($pwd); // Hashed Password
// Insert Query of SQL
$result = mysqli_query($conn, $sql = "SELECT * FROM `Management-employees` WHERE email='$email' AND password = '$pwd2'") or die(json_encode(array(
'IsError' => 'true',
'ErrorMessage' => 'Invalid Request!! Oops, something went wrong. Please try again!!'
)));
if (mysqli_num_rows($result) == 1)
{
// output data of each row
while ($row = mysqli_fetch_assoc($result))
{
$functionCategory = $row[functionCategoryID];
}
switch ($functionCategory)
{
case "Management":
// echo "You have got clearance for this page!";
exit(json_encode(array(
'IsError' => 'false',
'ResponseData' => 'Success'
)));
break;
default:
throw new Exception('Invalid clearance!!');
}
}
else
{
throw new Exception('ERROR: Could not be able to execute ' . $sql . ' - ' . mysqli_error($conn));
}
}
}
else
{
throw new Exception('Invalid access method!!');
}
}
catch(Exception $e)
{
exit(json_encode(array(
'IsError' => 'true',
'ErrorMessage' => $e->getMessage()
)));
}
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
}
I am totally new in using FB API and i am trying to post to facebook wall from my Asp.net application.
I have got the Appkey and secret key from FB and just trying to follow
the code to post in FB wall.
LINK : http://kennetham.com/2010/07/21/facebook-api-asp-net/
The problem i am facing now is, in my ConnectAuthentication Class, HttpContext.Current.Request.Cookies[fullCookie] is always NULL. Due to that, when i check for the FB connectivity by "if (ConnectAuthentication.isConnected())" in my pageload, it always returns false and it does not run the code inside condition.
Why is that? Am i missing something ?
ConnectAuthentication Class
public class ConnectAuthentication
{
public ConnectAuthentication()
{
}
public static bool isConnected()
{
return (SessionKey != null && UserID != -1);
}
public static string ApiKey
{
get
{
return ConfigurationManager.AppSettings["APIKey"];
}
}
public static string SecretKey
{
get
{
return ConfigurationManager.AppSettings["Secret"];
}
}
public static string SessionKey
{
get
{
return GetFacebookCookie("session_key");
}
}
public static long UserID
{
get
{
long userID = -1;
long.TryParse(GetFacebookCookie("user"), out userID);
return userID;
}
}
private static string GetFacebookCookie(string cookieName)
{
string retString = null;
string fullCookie = ApiKey + "_" + cookieName;
if (HttpContext.Current.Request.Cookies[fullCookie] != null)
retString = HttpContext.Current.Request.Cookies[fullCookie].Value;
return retString;
}
}
Here is how the ConnectAuthentication Class is used in my page load :
if (ConnectAuthentication.isConnected())
{
Facebook.Session.ConnectSession session = new Facebook.Session.ConnectSession(ConnectAuthentication.ApiKey, ConnectAuthentication.SecretKey);
_connectSession = new ConnectSession(ConnectAuthentication.ApiKey, ConnectAuthentication.SecretKey);
Api _facebookAPI = new Api(_connectSession);
_connectSession.UserId = ConnectAuthentication.UserID;
Facebook.Rest.Api api = new Facebook.Rest.Api(_connectSession);
//Display user data captured from the Facebook API.
Facebook.Schema.user user = api.Users.GetInfo();
string fullName = user.first_name + " " + user.last_name;
Panel1.Visible = true;
Label1.Text = fullName;
}
else
{
//Facebook Connect not authenticated, proceed as usual.
}
}
This code worked perfectly...
<input type="button" id="fblogin" value="Login to Facebook" disabled="disabled" style="display:none"/>
<fb:login-button v="2" length="long" onlogin="window.location = 'Default.aspx'">Login to Facebook</fb:login-button>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '<%: Facebook.FacebookApplication.Current.AppId %>',
cookie: true,
xfbml: true,
oauth: true
});
function facebooklogin() {
FB.login(function (response) {
if (response.authResponse) {
// user authorized
// make sure to set the top.location instead of using window.location.reload()
top.location = '<%= this.ResolveCanvasPageUrl("~/") %>';
} else {
// user cancelled
}
}, { scope: '<%: string.Join(",", ExtendedPermissions) %>' });
};
$(function () {
// make the button is only enabled after the facebook js sdk has been loaded.
$('#fblogin').attr('disabled', false).click(facebooklogin);
});
};
(function () {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
</script>
How to post something on a facebook page's wall from a asp.net website.
Google search says that I have to create an app to do this. Is it possible to post to facebook wall without creating an app?
not sure where to start. I tried developers.facebook.com and csharpsdk.org. Not much luck. Is there an example? or a tutorial using the graph api?
Creating an APP on facebook is a minimum requirement for FB to accept your posts. What you are asking doesnt make much sense. Imagine if anyone can post stuff to FB, we probably wouldnt be discussing about this here (it would have been dead by now and I am glad it is how it is) I suggest you read these links for a quick start
FB API in general:
http://developers.facebook.com/docs/reference/javascript/FB.api/
C# SDK: http://developers.facebook.com/blog/post/395/
Graph Api: http://developers.facebook.com/docs/reference/api/
Hope this gives some starting points. Good luck
After you create the application stuff in facebook and get your unique application id and secret code use the following (code behind)
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Web.Security;
using System.Xml;
using System.Collections.Specialized;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
readonly static string myurl = "your url";
readonly static string App_ID = "Your application id";
readonly static string App_Secret = "your secret code";
readonly static string scope = "email";
FacebookUser me;
readonly static DataContractJsonSerializer userSerializer = new DataContractJsonSerializer(typeof(FacebookUser));
protected void Page_Load(object sender, EventArgs e)
{
if (Session["code"] == null)
{
fbLogin.Visible = true;
}
else
{
fbLogin.Visible = false;
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if ((!IsPostBack) || Session["code"] == null)
{
string code = Request.QueryString["code"];
if (code == null)
{
Session["code"] = null;
}
else
{
Session["code"] = code;
// oAuth = new oAuthFacebook();
//// oAuthFacebook oFB = new oAuthFacebook();
// //Response.Redirect(oFB.AuthorizationLinkGet());
// oAuth.AccessTokenGet(Request["code"]);
// if (oAuth.Token.Length > 0)
// {
// //We now have the credentials, so we can start making API calls
// string url = "https://graph.facebook.com/me/likes?access_token=" + oAuth.Token;
// string json = oAuth.WebRequest(oAuthFacebook.Method.GET, url, String.Empty);
// }
}
string error_description = Request.QueryString["error_description"];
string originalReturnUrl = Request.QueryString["ReturnUrl"]; // asp.net logon param
Uri backHereUri = Request.Url; // modify for dev server
if (!string.IsNullOrEmpty(code)) // user is authenticated
{
me = GetUserDetails(code, backHereUri);
FormsAuthentication.SetAuthCookie(me.email, false); // authorize!
if (!string.IsNullOrEmpty(originalReturnUrl))
Response.Redirect(originalReturnUrl);
}
if (!string.IsNullOrEmpty(error_description)) // user propably disallowed
{
OnError(error_description);
}
fbLogin.Visible = !User.Identity.IsAuthenticated;
if (string.IsNullOrEmpty(code))
{
fbLogin.Visible = true;
LoginName1.Visible = false;
}
else
{
fbLogin.Visible = false;
LoginName1.Visible = true;
LoginName1.Text = "User Email: " + me.email.ToString() + " Name: " + me.first_name.ToString() + " Sname: " + me.last_name.ToString() + " Verified: " + me.verified.ToString();
}
fbLogin.NavigateUrl = string.Format(
CultureInfo.InvariantCulture,
"https://www.facebook.com/dialog/oauth?"
+ "client_id={0}&scope={1}&redirect_uri={2}",
App_ID,
scope,
Uri.EscapeDataString(backHereUri.OriginalString));
}
}
FacebookUser GetUserDetails(string code, Uri backHereUri)
{
Uri getTokenUri = new Uri(
string.Format(
CultureInfo.InvariantCulture,
"https://graph.facebook.com/oauth/access_token?"
+ "client_id={0}&client_secret={1}&code={2}&redirect_uri={3}",
App_ID,
App_Secret,
Uri.EscapeDataString(code),
Uri.EscapeDataString(backHereUri.OriginalString))
);
using (var wc = new WebClient())
{
string token = wc.DownloadString(getTokenUri);
Session["token"] = token;
Uri getMeUri = new Uri(
string.Format(
CultureInfo.InvariantCulture,
"https://graph.facebook.com/me?{0}",
token)
);
using (var ms = new MemoryStream(wc.DownloadData(getMeUri)))
{
var me = (FacebookUser)userSerializer.ReadObject(ms);
return me;
}
}
}
void OnError(string error_description)
{
Controls.Add(new Label()
{
CssClass = "oauth-error",
Text = error_description
}
);
}
[Serializable]
class FacebookUser
{
public long id;
public string name;
public string first_name;
public string last_name;
public string link;
public string email;
public string timezone;
public string locale;
public bool verified;
public string updated_time;
}
protected void Button1_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
WebRequest req = WebRequest.Create("https://api.facebook.com/restserver.php?method=links.getStats&urls=http://localhost:5064/default.aspx,http://www.facebook.com");
WebResponse resp = req.GetResponse();
StreamReader reader = new StreamReader(resp.GetResponseStream());
string xml = reader.ReadToEnd();
xml = xml.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").Replace("links_getStats_response xmlns=\"http://api.facebook.com/1.0/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd\" list=\"true\"", "links_getStats_response");
doc.LoadXml(xml);
XmlNodeList xnList = doc.SelectNodes("links_getStats_response/link_stat");
foreach (XmlNode xn in xnList)
{
string fullurls = xn["url"].InnerText;
string likes = xn["like_count"].InnerText;
string comment = xn["comment_count"].InnerText;
string normalisedurls = xn["normalized_url"].InnerText;
}
}
public string WebRequests(string method, string url, string postData)
{
HttpWebRequest webRequest = null;
StreamWriter requestWriter = null;
string responseData = "";
webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = method.ToString();
webRequest.ServicePoint.Expect100Continue = false;
webRequest.UserAgent = HttpContext.Current.Request.UserAgent;
webRequest.Timeout = 20000;
if (method == "POST")
{
webRequest.ContentType = "application/x-www-form-urlencoded";
//POST the data.
requestWriter = new StreamWriter(webRequest.GetRequestStream());
try
{
requestWriter.Write(postData);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
}
responseData = WebResponseGet(webRequest);
webRequest = null;
return responseData;
}
public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}
return responseData;
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Session["code"] != null)
{
string urls = "https://graph.facebook.com/me/feed?" + Session["token"];
var json = WebRequests("POST", urls, "message=" + HttpUtility.UrlEncode("" + TextBox1.Text));
}
}
}
}
AND for default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HyperLink runat="server" Text="Log in with Facebook" id="fbLogin"/><br /><br />
<asp:Label ID="LoginName1" runat="server" Text="" Font-Bold="true"></asp:Label>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Get Likes And Comments" onclick="Button1_Click" />
<br />
<asp:TextBox ID="TextBox1" runat="server" Width="407px" Text="Testing Api by c# code"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Post To me"
onclick="Button2_Click" />
</div>
</form>
</body>
</html>
Hope that helps