Fans-only content in facebook with asp.net C# sdk - c#

Hi i'm developing an application in facebook with c# sdk and i want that the user whom liked my page can only use my application. (Like woobox)
I found some solutions in php in this link but there isn't any source about .net how can i get the liked info in ASP.NET
I find another examples in php in this link again but i can't find c# answer :\
Thanks

You get signed request when your web page is loaded within facebook canvas app; you should be able to parse signed request something similar to following:
if (Request.Params["signed_request"] != null)
{
string payload = Request.Params["signed_request"].Split('.')[1];
var encoding = new UTF8Encoding();
var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
var json = encoding.GetString(base64JsonArray);
var o = JObject.Parse(json);
var lPid = Convert.ToString(o.SelectToken("page.id")).Replace("\"", "");
var lLiked = Convert.ToString(o.SelectToken("page.liked")).Replace("\"", "");
var lUserId= Convert.ToString(o.SelectToken("user_id")).Replace("\"", "");
}
You need to add reference to json libraries in order to parse signed requestin C#, download from http://json.codeplex.com/
Also refere to How to decode OAuth 2.0 for Canvas signed_request in C#? if you are worndering about signed request.

This is only possible with the legacy APIs, or with the user_likes permission. As you want a solution without specific permissions I'll show you 2 methods. Use them in combination with AJAX to refresh the page when a user presses like.
Option 1) REST API
Using the legacy API, it's possible to use Pages.IsFan
https://api.facebook.com/method/pages.isFan?
page_id=...&
uid=...&
access_token=...
Do this in C# as follows.
var appID = "....";
var appSecret = "....";
var uid = "....";
var pageId = "....";
WebClient client = new WebClient();
var appAuthUri = string.Concat("https://graph.facebook.com/oauth/access_token?",
"client_id=", appID,
"&client_secret=", appSecret,
"&grant_type=", "client_credentials"
);
var response = client.DownloadString(appAuthUri);
var access_token = response.Split('=')[1];
var isFanUri = string.Concat("https://api.facebook.com/method/pages.isFan?",
"format=", "json",
"&page_id=", pageId,
"&uid=", uid,
"&access_token=", access_token
);
response = client.DownloadString(isFanUri);
bool isFan;
bool.TryParse(response, out isFan);
Option 2) Client side
The FBXML method. This is done with Javascript on the client, by subscribing to an event when the user clicks the like button. It's documented here.
How do I know when a user clicks a Like button?
If you are using the XFBML version of the button, you can subscribe to
the 'edge.create' event through FB.Event.subscribe.
Generate an FBXML like button here.
<div id="fb-root"></div>
<script>(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js#appId=132240610207590&xfbml=1";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));</script>
<div class="fb-like" data-href="http://www.thecodeking.co.uk" data-send="true" data-width="450" data-show-faces="false"></div>
Then subscribe to the edge.create event using the Javascript SDK. Place this code in the document BODY preferably just before the end.
<script type="text/javascript">
<!--
window.fbAsyncInit = function () {
FB.init({ appId: '245693305442004', status: true, cookie: true, xfbml: true });
FB.Event.subscribe('edge.create',
function (href, widget) {
// Do something here
alert('User just liked '+href);
});
(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>

this.canvasAuthorizer = new CanvasAuthorizer {
Permissions = new[] { "user_about_me", "publish_stream", "offline_access", "user_likes", "friends_about_me" }
};
this.canvasAuthorizer.Authorize();
if (FacebookWebContext.Current.IsAuthorized())
{
this.facebookWebClient = new FacebookWebClient(FacebookWebContext.Current);
string requested_Data = HttpContext.Current.Request.Form["signed_request"];
dynamic decodedSignedRequest = FacebookSignedRequest.Parse(this.facebookApplication, requested_Data);
if (decodedSignedRequest.Data.page != null)
{
// Funs Page
this.IsLike = decodedSignedRequest.Data.page.liked;
}
else
{
// Application Page
dynamic likes = this.facebookWebClient.Get("/me/likes");
foreach (dynamic like in likes.data)
{
if (like.id == this.FacebookFanPageID)
{
this.IsLike = true;
}
}
}
}

If your app is a canvas app, you could (should?) use the signed_request parameter to check if the user likes the page it's on:
# pseudocode
signed_request = decode_signed_request()
if signed_request['page']['liked']:
# user liked page, do something cool
else:
# user doesn't like page. redirect somewhere to tell them why they should
The signed_request is passed to your page as a POST variable; just as if there was a form field named signed_request and the form was submitted on the page previous to yours (in fact this is basically how facebook "runs" your app; the form is auto-submitted instead of waiting for a user to submit it). So in ASP.net you should be able to get it through the Request object:
Request["signed_request"]
This approach is useful if you're creating a "tab app" for a page; you can detect whether the user liked the page without them granting you extra permissions.

This can be done in PHP with the help of an SQL Query
`$result = $facebook->api(array( "method" => "fql.query",
"query" => "SELECT uid FROM page_fan WHERE uid=$uid AND page_id=$page_id"
));
Here $result variable can be used for segregating the Fan and non-Fan content

Related

ASP.Net Core 3.1 Identity - Generating Password Reset Token Issue

I am developing a site where the users will be able to click a "Forgot My Password" button to reset their passwords.
Currently, once the email has been validated, the following code should generate a token to be emailed to the user:
if(validUser != null)
{
var generationTime = DateTime.Now;
var pwToken = await _userManager.GeneratePasswordResetTokenAsync(validUser);
await _userManager.UpdateAsync(validUser);
var url = $"https://{Request.Host}/verify/{HttpUtility.UrlEncode(pwToken)}";
//EmailHelper.SendMagicLinkEmail(validUser, url, Request);
return new RedirectResult("/");
}
All information online regarding this seems to suggest that this is the way to do things. I have set up the Default token providers in the Startup.csfile too:
identityOptions: o => {
o.User.RequireUniqueEmail = true;
o.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultProvider;
o.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultProvider;
},
Yet when a token is generated it produces a large token such as this:
CfDJ8CnvAYtZf+1IjXpKUM7+umDYEaImg2SPFglPX3Y8RmYpEfg5zpK8xL54lvlbJUd54CaIzzYlff/GU+xKKS8mmG5UdC1zdk24nOsJNpIlmC3P5V72BchS4P9DGFTR77XiKbMAAYymnMomS2zCdTKh+E4bn9RI6FVinMecG1HR7nSHmOI2McbXHBFTanI/0uwxH5WI/Dj4AFTBP39ni7mfKkeWz2nJ5pTemELJJ6pYP50+
The problem here is obviously the forward slashes, which cause issues with routing so are encoded out here:
var url = $"https://{Request.Host}/verify/{HttpUtility.UrlEncode(pwToken)}";
The problem is that even with that, .Net Core seems to un-encode it and produce the following error when the generated link is accessed:
This error isn't necessarily the issue, and I do understand it's importance. Yet I can't seem to find any explanation as to why this token is behaving this way. All online examples seem to produce a fairly standard GUID style token, not something such as this.
Does anyone know why this might be happening?
Cheers
You may want to try the Url.Action() method:
Example:
var token = userManager.GeneratePasswordResetTokenAsync(user).Result;
var resetLink = Url.Action("ResetPassword","Account", new { token = token }, protocol: HttpContext.Request.Scheme);
var message = "Click here to reset your password";
//Then send your message to the user
Note in the example above the email must be HTML for the link to work
The token looks fairly normal to me.
I think the URL encoding method you'd want to use is Uri.EscapeDataString. What I've personally done is using a UriBuilder and escaped the query string values (in this case for email confirmation):
var uriBuilder = new UriBuilder
{
Scheme = "https",
Host = "my.website.com",
Path = "/confirmEmail",
Query = $"email={Uri.EscapeDataString(email)}&token={Uri.EscapeDataString(token)}"
};
var fullUrl = uriBuilder.Uri.AbsoluteUri;
For you that'd be:
var uriBuilder = new UriBuilder
{
Scheme = "https",
Host = Request.Host,
Path = $"/verify/{Uri.EscapeDataString(pwToken)}"
};
var fullUrl = uriBuilder.Uri.AbsoluteUri;

Bad Request: QUERY_ID_INVALID telegram bot api

I Want use telegram api bot . every thing is ok (in my idea) but i have stupid error that where ever is search i cant find any thing .
I am using Inline mode .
var awnser = new AnswerInlineQuery()
{
inline_query_id =model.inline_query.id,
results = new List<InlineQueryResultArticle>()
};
awnser.results.Add(new InlineQueryResultArticle() { id = Guid.NewGuid().ToString("N"), type = "article", url = "fidilio", input_message_content = new InputTextMessageContent() { message_text = "salam" }, title = "test" });
var send = SendInlineAwnser(awnser);
The send method is using restsharp
var ser = JsonConvert.SerializeObject(data);
var url = "https://api.telegram.org/bot" + telegramToken + "/answerInlineQuery";
var req = SimplePost<AnswerInlineQuery>(ser, url);
my serlization out put is this
{"inline_query_id":"302418856930797437","results":[{"type":"article","id":"fae56651b23244f8a3be94b1e6ebf6e7","title":"test","input_message_content":{"message_text":"salam"},"url":"fidilio"}]}
make sure that model.inline_query.id is correct and if so, keep in mind that you can send notify max 15 sec after inline keyboard pushed. Besides, I suggest using async method for sending inline query results.

C# Facebook app / post on site

im very new with Facebook apps and read several threads for creating them, but I have some problems with it.
First of all what I want to do: I want to create a web application that is able to post pictures, text and links on a facebook page that is managed by me.
I used the Facebook C# SDK: here!
What I have:
string facebookPageId = "<my page id>";
string app_id = "<my app id>";
string app_secret = "<my app secret>";
string scope = "publish_stream,manage_pages";
var fb = new FacebookClient();
dynamic res = fb.Get("oauth/access_token", new
{
client_id = app_id,
client_secret = app_secret,
grant_type = "client_credentials"
});
var access_token = res.access_token;
dynamic messagePost = new ExpandoObject();
messagePost.access_token = access_token;
messagePost.link = "http://www.test.at";
messagePost.name = "Testbot";
messagePost.caption = "{*actor*} " + "hello this is a test";
messagePost.description = "[SOME_DESCRIPTION]";
FacebookClient app = new FacebookClient(access_token);
app.AppId = app_id;
app.AppSecret = app_secret;
try
{
var result = app.Post("/hrechttest" + "/feed", messagePost);
}
catch (Exception e)
{
}
Well the code runs without any exceptions but in the output window I get the following:
Exception thrown: 'Facebook.FacebookOAuthException' in Facebook.dll
The next problem is:
As I understood it you must link your facebook app with your facebook page, but when I want to do that I cant select the page:
So what I did wrong or missed?
publish_stream is deprecated since many years, publish_pages is the correct permission to post to a Page (as Page).
API reference: https://developers.facebook.com/docs/graph-api/reference/page/feed#publish
Make sure you are using a Page Token, not a User Token:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
How to create Page Apps is explained in the docs too: https://developers.facebook.com/docs/pages/tabs

Facebook login winforms

Here is my generate URL:
private Uri GenerateLoginUrl(string appId, string extendedPermissions)
{
// for .net 3.5
// var parameters = new Dictionary<string,object>
// parameters["client_id"] = appId;
dynamic parameters = new ExpandoObject();
parameters.client_id = appId;
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
// The requested response: an access token (token), an authorization code (code), or both (code token).
parameters.response_type = "token";
// list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
parameters.display = "popup";
//scope
parameters.scope = "Email";
// add the 'scope' parameter only if we have extendedPermissions.
if (!string.IsNullOrWhiteSpace(extendedPermissions))
parameters.scope = extendedPermissions;
// when the Form is loaded navigate to the login url.
return _fb.GetLoginUrl(parameters);
//webBrowser.Navigate(new Uri("www.facebook.com"));
}
The problem is the return _fb.GetLoginUrl is NULL. I have a webBrowser control already on the WinForm.
Any ideas? or can i just hard code the URL?
Worked at this a few months ago. I had the same problem cause by the ajax in the response site. The problem is that the ajax load the site content after the url is loaded. I fixed it by wait for the webbrowseres load event. I think it was webrowser.DocumentCompleted
I hope this help you.

How can i get Equivalent method of HttpwebRequest in javascript

As we all know HttpwebRequest loads another page behind the scenes without redirecting the client to the other page.
How can I get this functionality using Javascript/Jquery?
$(document).ready(function () {
debugger;
var ip = '<%= Request.UserHostAddress%>';
var location = window.location.href;
var Browser = BrowserDetect.browser;
var Version = BrowserDetect.version;
var Os = BrowserDetect.OS;
var SendItems = 'Ip=' + ip + '&location=' + location + '&Browser=' + Browser + '&Version=' + Version + '&Os=' + Os;
var HttpWebReq = ?
I want to pass these values as a query string to the other page :S
A cross domain example by using yql,
var url = 'xyz.com'; // website you want to scrape
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + url + '"') + '&format=json&callback=?';
$.getJSON(yql,function(data){
if (data.results[0]){
console.log(data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')); // The scraped data (the whole webpage)
}
});
As Corbin commented - you are looking for AJAX tutorial.
Since you've tagged with JQuery starting from JQuery.ajax is a good idea.
Also check out other related questions like - How to get page content using Javascript or JQuery

Categories