Reading the results of me/accounts - asp.net

I'm using the Facebook API for .NET, and need the access token for a page I'm the admin for.
I'm making the following call:
FacebookClient client = new FacebookClient(tokens["access_token"]);
JsonObject jsonResponse = client.Get("me/accounts") as JsonObject;
Does anyone have a piece of script to read the values into a List or Dictionary for easy consumption?

I figured it out eventually, this is the sample code in case anyone is interested. In this example, I'm retrieving the access_token field from the Page name set in the web.config
FacebookClient client = new FacebookClient(AccessToken);
JsonObject jsonResponse = client.Get("me/accounts") as JsonObject;
foreach (var account in (JsonArray)jsonResponse["data"])
{
string accountName = (string)(((JsonObject)account)["name"]);
if (accountName == ConfigurationManager.AppSettings["FacebookPageName"])
{
HttpContext.Current.Session["PageAccessToken"] = (string)(((JsonObject)account)["access_token"]);
break;
}
}

Related

Trouble searching on Twitter in asp.net Core By TweetSharp

I try to search with a word on Twitter but every time I run it comes back empty.
I run two methods to execute. In the first method, I use the token given by Twitter, and in the second method, I take the token from online Twitter, but both methods return empty results.
TwitterService service= new TwitterService(_consumerKey, _consumerSecret);
twitterService.AuthenticateWith(_accessToken, _accessTokenSecret);
var options2 = new SearchOptions { Q = "VegaIt" };
var tweets = service.Search(options2);
foreach (var tweet in tweets.Statuses)
{
Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
}
AND method
TwitterService service = new TwitterService(_consumerKey, _consumerSecret);
// Step 1 - Retrieve an OAuth Request Token
OAuthRequestToken requestToken = service.GetRequestToken();
// Step 2 - Redirect to the OAuth Authorization URL
Uri uri = service.GetAuthorizationUri(requestToken);
service.AuthenticateWith(requestToken.Token, requestToken.TokenSecret);
var tweets = service.Search(options2);
foreach (var tweet in tweets.Statuses)
{
Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
}
In both methods the answer "tweet" is Null

PDF form submission to .Net Core Web API, return result

I have created a .net core web api controller in C#, that accepts PDF form data in FDF format, from a submit button on the form.
Because my controller tries to store the data in a database, I would like to return a success/fail status to the form, which should be displayed to the user.
The form is a regular Acrobat form (so not a web form) and is filled from the browser.
I have read about returning FDF data with a /Status, but have not found how to translate that info to web api, which is quite new to me.
You can Return a PdfResult that Adobe will accept. The return value must be based on where the document was submitted from. Here's my mvc controller
[AllowAnonymous]
[HttpPost]
public PdfResult SubmitForm(string Browser)
{
using (var sr = new StreamReader(Request.InputStream))
{
var fdfStream = sr.ReadToEnd();
var fieldsDict = _pdfFormService.ExtractFieldsText(fdfStream);
var formJson = JsonConvert.SerializeObject(fieldsDict);
var clientId = fieldsDict["client-id"];
var agencyId = fieldsDict["agency-id"];
var username = fieldsDict["username"];
var formId = fieldsDict["form-id"];
_pdfFormService.SubmitForm(int.Parse(agencyId), username, int.Parse(clientId), int.Parse(formId), formJson);
var document = PdfHelper.BuildSuccessPdf();
if (Browser == "Browser")
return document.ExportAsActionResult("success.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open);
else
return document.ExportAsActionResult("success.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save);
}
}
I found the definitions for PDF results and the document.ExportAsActionResult extension methods here.

How to consume a secure Rest MVC web api

I'm just a beginner on the .NET world and I've created a web api (.NET 4.5.2) and I'm using the annotation [Authorize] above my controllers like shown below:
[Authorize]
public class PhasesController : ApiController
{
private TestReportEntities db = new TestReportEntities();
// GET: api/Phases
public IQueryable<Phase> GetPhase()
{
return db.Phase;
}
}
I've already created my DB and I'm using the default tables that the web.api uses to manage the access, as you can see on this image:
My tables
I've already done a method to request to my web api, in another project/solution, it's working fine when I remove the annotation [Authorize] from my web api controllers.
this is an example about how I'm requesting my api:
public int GetCurrentIdPhase(int idProject)
{
int phaseId = -1;
WebRequest request = WebRequest.Create(string.Concat(URL, string.Format("api/phases/?idProject={0}", idProject)));
using (var resp = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(resp.GetResponseStream()))
{
string objText = reader.ReadToEnd();
var phase = JsonConvert.DeserializeObject<List<Phase>>(objText);
phaseId = phase[0].id;
}
}
if (phaseId != -1)
{
return phaseId;
}
else
{
throw new Exception("Phase not found");
}
}
At the end of the day my questions are:
How can I request a token to my api (POST - www.myApi/token) using the example above?
How can I use the token, once I've got it, on every request to my API?
if you can help me I would really appreciate it.
Thanks.
I've created a method to get the Token from my Web API, this is the method:
var request = (HttpWebRequest)WebRequest.Create(string.Concat(URL, "token"));
var postData = "grant_type=password";
postData += string.Format("&userName={0}", user);
postData += string.Format("&password={0}", pass);
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
string objText = new StreamReader(response.GetResponseStream()).ReadToEnd();
var requestedToken = (JObject)JsonConvert.DeserializeObject(objText);
token = string.Concat(token, requestedToken["access_token"].Value<string>());
And to request something to my API all I need to do is just add the token on the header of all requests like shown on the line below:
request.Headers.Add(HttpRequestHeader.Authorization, getToke());
Hope it can help someone else who is beginning to work with .NET web API like me.
Regards.
Im assuming the "GetCurrentIdPhase" call is from an unrelated app with unrealted auth - if any auth.
The difficulty here is in using Authorize and the traidtional browser authentication flow. Here's an example of changing the pipeline a bit to use a different auth form for using console/desktop apps. You don't say where you are calling GetCurrentIdPhase from so I'll have to assume either a separate app. If its a web app and you are authenticated using the same tables, then you will have to share the token between them using for ex. the url blackice provided above.
If the app is a desktop/console/etc (not another app that the user had to auth against the same tables) then you can try this approach to change how auth is done to make it easier to access.
MVC WebAPI authentication from Windows Forms

Dotnetopenauth, retrieve email from facebook scope

Have a question I surpsisingly couldnt find an answer to when searching around.
If I request a users email from facebook like:
var scope = new List<string>();
scope.Add("email");
FbClient.RequestUserAuthorization(scope);
How do I retrieve it? I couldnt find a clear option for this in the FacebookGraph.
Near as I can tell, the FacebookGraph object that is in the examples from DotNetOpenAuth does not support changing the fields that you are receiving. However, since WebRequest that it is prompting is returning a JSON string, you can parse it yourself (or use another JSON parser). That's exactly what I did, using the NewtonSoft.Json.dll:
//as part of the uri for the webrequest, include all the fields you want to use
var request = WebRequest.Create("https://graph.facebook.com/me?fields=email,name&access_token=" + Uri.EscapeDataString(authorization.AccessToken));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
System.IO.StreamReader streamReader = new System.IO.StreamReader(responseStream, true);
string MyStr = streamReader.ReadToEnd();
JObject userInfo = JObject.Parse(MyStr);
//now you can access elements via:
// (string)userInfo["name"], userInfo["email"], userInfo["id"], etc.
}
}
Note that you specify what fields you want sent back as part of the WebRequest URI. The fields that are available can be found at https://developers.facebook.com/docs/reference/api/user/
Using DNOA This answer did it for me.
Just added the following:
var scope = new List<string>();
scope.Add("email");
client.RequestUserAuthorization(scope);
and the following to the facebook graph.
[DataMember(Name = "email")]
public string EMail { get; set; }
What you wrote above appears to be requsting authorization from the user to allow your app to get email back when you query the user's object. To query the user's object you do an HTTP Get on https://graph.facebook.com/me. Try it out in the Graph API explorer tool at https://developers.facebook.com/tools/explorer

How can i verify if my google web store application is licensed using asp.net?

I'm using DotNetOpenAuth.dll in order to obtain userid, but i don't know how to send the signed OAuth request google needs:
http://code.google.com/intl/it-IT/chrome/webstore/docs/check_for_payment.html
the example shows only java code
thanks for any help
Go to http://www.dotnetopenauth.net/ and read the documentations, you should find everything you need there.
EDIT:
I'm not sure if this is the right way or not but here is some sample code in c#
var serviceProvider = new ServiceProviderDescription();
var tokenManager = new TokenManager(); //make an implementation of IConsumerTokenManager
var oauth = new WebConsumer(serviceProvider, tokenManager); //instanciate an consumer
var user = new User(); //User class contains an implementation of getFederatedIdentity()
var url = new Uri(string.Format(SERVER_URL,APP_ID,HttpUtility.HtmlEncode(user.getFederatedIdentity())));//create the url
var response = oauth.PrepareAuthorizedRequestAndSend(
new MessageReceivingEndpoint(url, HttpDeliveryMethods.AuthorizationHeaderRequest), TOKEN); //Send the request
//do what you want with the response

Resources