implementing Invisible Google reCaptcha for asp.net application ? - c#

This is my ASP.NET form. I want to add invisible recaptcha to it with server side validation. Can someone please help?
I can do client side validation but it doesnt use secret key. My another questions is Do we need secret key for invisible recaptcha?
Please see serverside code that i used for google recaptcha but it is not working for Invisible recaptcha. I am getting this error : -
reCAPTCHA Error: missing-input-response: Not Valid Recaptcha
<div id="ContactFormDiv" runat="server">
<div class="form-row form-required">
<asp:Label ID="YourNameLabel" runat="server" AssociatedControlID="YourNameTextBox"> Your Name:</asp:Label>
<asp:TextBox ID="YourNameTextBox" runat="server" CssClass="form300" MaxLength="150"></asp:TextBox>
</div>
<div class="form-row form-required">
<div id='recaptcha' class="g-recaptcha"
data-sitekey="site key"
data-callback="onSubmit"
data-size="invisible">
</div>
</div>
<div class="form-row-buttons">
<asp:Button ID="SendMessageButton" ClientIDMode="Static" runat="server" Text="Send Message" CssClass="buttonPositive"
CausesValidation="True" OnClick="SendMessageButton_Click" />
</div>
</div>
Javascript Code
<script type="text/javascript" src="https://www.google.com/recaptcha/api.js" async defer></script>
Serverside Code
public class MyObject
{
public string success { get; set; }
}
public static string ReCaptcha_Key = "------------------Site Key-----------------";
public static string ReCaptcha_Secret = "--------------Secret Key ---------------";
public bool ValidateReCaptcha()
{
bool Valid = false;
//start building recaptch api call
var sb = new StringBuilder();
//Getting Response String Append to Post Method
string Response = Request["g-recaptcha-response"];
string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + ReCaptcha_Secret + "&response=" + Response;
sb.Append(url);
//make the api call and determine validity
using (var client = new WebClient())
{
var uri = sb.ToString();
var json = client.DownloadString(uri);
var serializer = new DataContractJsonSerializer(typeof(RecaptchaApiResponse));
var ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
var result = serializer.ReadObject(ms) as RecaptchaApiResponse;
//--- Check if we are able to call api or not.
if (result == null)
{
lblmsg.Text = "Captcha was unable to make the api call";
}
else // If Yes
{
//api call contains errors
if (result.ErrorCodes != null)
{
if (result.ErrorCodes.Count > 0)
{
foreach (var error in result.ErrorCodes)
{
lblmsg.Text = "reCAPTCHA Error: " + error;
}
}
}
else //api does not contain errors
{
if (!result.Success) //captcha was unsuccessful for some reason
{
lblmsg.Text = "Captcha did not pass, please try again.";
}
else //---- If successfully verified. Do your rest of logic.
{
lblmsg.Text = "Captcha cleared ";
Valid = true;
}
}
}
}
return Valid;
}
public bool temp = true;
protected void SendMessageButton_Click(object sender, EventArgs e)
{
temp = ValidateReCaptcha();
if (temp == false)
{
lblmsg.Text = "Not Valid Recaptcha";
lblmsg.ForeColor = System.Drawing.Color.Red;
}
else
{
lblmsg.Text = "Successful";
lblmsg.ForeColor = System.Drawing.Color.Green;
}
Page.Validate();
if (this.Page.IsValid == true && temp == true)
{ //Page and invisible recaptcha is valid }
}
I am getting this error : -
reCAPTCHA Error: missing-input-response: Not Valid Recaptcha

This is how I implemented the working sample:
-- Client Side (Refer to Google Documentation )
<head>
<!-- Google Invisible Captcha -->
<script src='https://www.google.com/recaptcha/api.js'/>
<script>
function onSubmit(token) {
document.getElementById("htmlForm").submit();
}
</script>
</head>
<body>
<form id="htmlForm" action="Default.aspx" method="post">
<input name="txtName" />
<input name="txtEmailAddress" />
<button class="g-recaptcha btn btn-default"
data-sitekey="-------------------Site key--------------"
data-callback="onSubmit">
Submit Request
</button>
</form>
</body>
-- Server Side (keeps secret Key)
public static bool IsValidCaptcha()
{
var secret = "--------------Secret Key ---------------";
var req =
(HttpWebRequest)
WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" + secret + "&response=" + HttpContext.Current.Request.Form["g-recaptcha-response"]);
using (var wResponse = req.GetResponse())
{
using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
{
string responseFromServer = readStream.ReadToEnd();
if (!responseFromServer.Contains("\"success\": false"))
return true;
}
}
return false;
}

I also have similar problem and it looks like it is harder to find any decent example. However, I saw that you have set
data-callback="onSubmit"
but I didn't see where you have defined that method. Is it there? Could that be what are you missing?

Related

How to read form data values shown on network tab of developer tools in controller?

Trying to read form data[Developer tools: Network -> Payload -> FormData], below is the flow of code and how I tried to read and failed. Kindly help me in reading form data values - bearer & status. End goal is to read the bearer token which is actually added to the form by the returnee application and decode and use the data. Apologies if am asking a silly question or made mistakes somewhere in my question.
cshtml:
<form asp-action="TestAction" asp-controller="Account" method="GET" id="sign_in_form" novalidate="novalidate">
<div id="signin">
<div class="form-group">
<input type="submit" value="Sign in" id="submit">
</div>
</div>
#Html.Hidden("ReturnUrl", ViewData["ReturnUrl"] ?? string.Empty, new { id = "returnURLID" })
</form>
TestActionController:
[HttpGet]
public async Task<IActionResult> TestAction()
{
return RedirectToLocal("https:someUrl.com/blah");
}
After redirecting to 'https:someUrl.com/blah', I fill up few details and submit, then I`ll be redirected back to 'https://testlogin.com/Account/Login?ReturnUrl=/?state=State123'.
Code where control comes back and the code I tried:
[HttpGet]
public IActionResult Login(string ReturnUrl = null)
{
if (HttpContext.User.Identity.IsAuthenticated)
{
return RedirectToLocal(ReturnUrl);
}
else if (!string.IsNullOrEmpty(ReturnUrl) && ReturnUrl.Contains("state=State123"))
{
//try 1
try
{
var dict = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString());
foreach (string key in HttpContext.Request.Form.Keys)
{
_errorService.InsertInformation($"dict[key]:{dict[key]}", "", 0, $"Login", Environment.MachineName);
}
}
catch(Exception ee) { _errorService.InsertInformation($"ee:{ee}", "", 0, $"Login", Environment.MachineName); }
//try 2
try
{
Request.Body.Position = 0;
var _body = new StreamReader(Request.Body).ReadToEnd();
//read _body - which is empty.
}
catch(Exception ex)
{
}
//try 3
using (var reader = new StreamReader(
Request.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false))
{
var bodyString = reader.ReadToEnd();
//bodyString is empty
try
{
foreach (var _key in Request.Form.Keys)
{
}
}catch{//It comes to catch block because Form is null}
}
return View();
}
else
{
// Some logic for session handling and others is done here.
return View();
}
}
Developer tool screenshot:

Connect Local AD with C# .Net Webform

Having trouble understanding this error below in vs.net.
I'm trying to grab a logged in user account on the domain and allow them to be able to edit their phone number.
Another guy setup the AD Access, but I can't event get a logged in user name.
Pasted the code VS.NET errors on every time with the exception that I found in an online article and worked for everyone else except me.
I've verified it works using powershell but I could use some help.
THANKS!!!
//parse the current user's logon name as search key
string sFilter = String.Format(
"(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))",
User.Identity.Name.Split(new char[] { '\\' })[1]
);
Exception User-Unhandled
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
<%# Import Namespace="System.DirectoryServices.ActiveDirectory" %>
<%# Import Namespace="System.DirectoryServices.AccountManagement" %>
<!DOCTYPE html>
<head>
<script language="c#" runat="server">
static string adsPath = "LDAP://dc=DOMAIN,dc=com";
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
SearchResult sr = FindCurrentUser(new string[] { "allowedAttributesEffective" });
if (sr == null)
{
msg.Text = "User not found...";
return;
}
int count = sr.Properties["allowedAttributesEffective"].Count;
if (count > 0)
{
int i = 0;
string[] effectiveAttributes = new string[count];
foreach (string attrib in sr.Properties["allowedAttributesEffective"])
{
effectiveAttributes[i++] = attrib;
}
sr = FindCurrentUser(effectiveAttributes);
foreach (string key in effectiveAttributes)
{
string val = String.Empty;
if (sr.Properties.Contains(key))
{
val = sr.Properties[key][0].ToString();
}
GenerateControls(key, val, parent);
}
}
}
else
{
UpdateControls();
}
}
private SearchResult FindCurrentUser(string[] attribsToLoad)
{
//parse the current user's logon name as search key
string sFilter = String.Format(
"(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))",
User.Identity.Name.Split(new char[] { '\\' })[1]
);
DirectoryEntry searchRoot = new DirectoryEntry(
adsPath,
null,
null,
AuthenticationTypes.Secure
);
using (searchRoot)
{
DirectorySearcher ds = new DirectorySearcher(
searchRoot,
sFilter,
attribsToLoad,
SearchScope.Subtree
);
ds.SizeLimit = 1;
return ds.FindOne();
}
}
private void GenerateControls(string attrib, string val, Control parent)
{
parent.Controls.Add(new LiteralControl("<div>"));
TextBox t = new TextBox();
t.ID = "c_" + attrib;
t.Text = val;
t.CssClass = "txt";
Label l = new Label();
l.Text = attrib;
l.AssociatedControlID = t.ID;
l.CssClass = "lbl";
parent.Controls.Add(l);
parent.Controls.Add(t);
parent.Controls.Add(new LiteralControl("</div>"));
}
private void UpdateControls()
{
SearchResult sr = FindCurrentUser(new string[] { "cn" });
if (sr != null)
{
using (DirectoryEntry user = sr.GetDirectoryEntry())
{
foreach (string key in Request.Form.AllKeys)
{
if (key.StartsWith("c_"))
{
string attrib = key.Split(new char[] { '_' })[1];
string val = Request.Form[key];
if (!String.IsNullOrEmpty(val))
{
Response.Output.Write("Updating {0} to {1}<br>", attrib, val);
user.Properties[attrib].Value = val;
}
}
}
user.CommitChanges();
}
}
btnSubmit.Visible = false;
Response.Output.Write("<br><br>< Back", Request.Url);
}
</script>
<style>
.lbl
{
margin-left: 25px;
clear: left;
width: 250px;
}
.txt
{
width: 250px;
}
</style>
</head>
<body>
<form id="main" runat="server">
Data for user:
<%=User.Identity.Name%>
<br>
<br>
<asp:Label ID="msg" runat="server" />
<asp:Panel ID="parent" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Update" />
</form>
</body>
</html>

Google Recaptcha not visible ASP.NET

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

why is HttpContext.Current.Request.Cookies[fullCookie] is always NULL when checking FB connectivity?

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>

Post to Facebook Page from ASP.NET Website

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

Categories

Resources