C#-Facebook-SDK WP7, the principles of how Facebook works? - c#

Apologies if this is somewhere, but I'm struggling to find the details I need for wp7.
I have created the application on Facebook as required, and am retrieving an access token. The following code posts to Facebook but I cannot get a response, nor can I work out how to monitor the response?
public bool fbUpload(string accessToken, Picture pic)
{
try
{
Stream s = null;
s = PicturesLoader.LoadFileFromStorage(pic.Url);
//Sets the byte array to the correct number of bytes
byte[] imageData = new byte[s.Length];
s.Read(imageData, 0, System.Convert.ToInt32(s.Length));
FacebookApp app = new FacebookApp();
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("access_token", accessToken);
parameters.Add("message", "TEST - WP7 application [upload pic and comment on wall...]");
var mediaObject = new FacebookMediaObject { FileName = pic.Name, ContentType = "image/jpeg" };
mediaObject.SetValue(imageData);
parameters["source"] = mediaObject;
FacebookAsyncResult postResult;
FacebookAsyncCallback fbCB = new FacebookAsyncCallback();
app.PostAsync(parameters, fbCB);
return true;
}
catch (InvalidCastException ex)
{
return false;
}
}
The other question I have, is how do you allow users to allow access based upon their own Facebook account. I want to store a user's account details so they only have to set up the account details once, and then they can use my phone app with having to sign in?

You can handle the post result something like this:
FacebookAsyncCallback callBack = new FacebookAsyncCallback(postResult);
fbApp.PostAsync(parameters, args, callBack);
private void postResult(FacebookAsyncResult asyncResult)
{
// Do something with asyncResult here;
}
Regarding the second question, you must ask for permissions to access this data.
You usually do that in the FacebookOAuthClient.GetLoginUrl(<appId>, null, <permissions>) method call.
Once that's done, you can store the files you have permissions to locally in your app.

Related

creating a github issue in octokit.net

I am trying to write a script that will open an issue typed in the console.
For some reason the issue variable comes back empty in the debugger.
class Program
{
public async static Task Main()
{
var client = new GitHubClient(new ProductHeaderValue("test-app"));
var user = await client.User.Get("medic17");
var tokenAuth = new Credentials(APIKeys.GithubPersinalAccessToken);
client.Credentials = tokenAuth;
var exampleIssue = new NewIssue("test body");
var issue = await client.Issue.Create("owner","name", exampleIssue);
}
}
APIKeys holds my token.
Thanks
I found a solution hope this helps someone else as well.
class Program
{
public async static Task Main()
{
// client initialization and authentication
var client = new GitHubClient(new ProductHeaderValue("<anything>"));
var user = await client.User.Get("<user>");
var tokenAuth = new Credentials(APIKeys.GithubPersinalAccessToken);
client.Credentials = tokenAuth;
// user input
Console.WriteLine("Give a title for your issue: ");
string userIssueTitle = Console.ReadLine().Trim();
Console.WriteLine("Describe your issue:", Environment.NewLine);
string userIssue = Console.ReadLine().Trim();
// input validation
while (string.IsNullOrEmpty(userIssue) || string.IsNullOrEmpty(userIssueTitle))
{
Console.WriteLine("ERROR: Both fields must contain text");
Console.ReadLine();
break;
}
var newIssue = new NewIssue(userIssueTitle) { Body = userIssue };
var issue = await client.Issue.Create(<owner>, <repo> newIssue);
var issueId = issue.Id;
Console.WriteLine($"SUCCESS: your issue id is {issueId} ");
Console.ReadLine();
}
}
Note
You need to store your keys in a separate file and write a class for it so your authentication flow might be different.
Note 2
You must replace all text with real values.
Still a little confused the app is OpenSource for transport since it deals with HIPPA data, users who want to use it need GitHub account if they want to do any error reporting. I assume I don’t share the authToken in the source of the project but the desktop Binary needs it plus the users GitHub login and password. Any pointers? I have tried just using username password that gets entered when creating issue but that fails with “not found”. It seems like any secret that gets deployed with binary app is potentially an issue.

Using TLSharp How to get UserProfilePhoto's photo?

I'm using TLSharp for dealing with really complicated Telegram API.
it's hard to understand how xxxAbswww types can be converted to xxxwww types which contains the real usable information!
I have the code below:
TLUser user = client.MakeAuthAsync("<user_number>", hash, code).Result;
how can I get the photo of authenticated user?
Agha Hamed,
Users' photo is accessible using 'userProfilePhoto' Telegram method and TLSharp didn't implemented this method.
But TLSharp provided some fascilities to implement other Telegram API methods. They says:
You can call any method with help of SendRequestAsync function. For
example, send user typing method:
//Create request
var req = new TLRequestSetTyping()
{
action = new TLSendMessageTypingAction(),
peer = peer
};
//run request, and deserialize response to Boolean
return await SendRequestAsync<Boolean>(req);
Unfortunately I don't know how to use SendRequestAsync function to do this.
try this:
var photo = ((TLUserProfilePhoto)user.Photo);
var photoLocation = (TLFileLocation)photo.PhotoBig;
TLFile file = await client.GetFile(new TLInputFileLocation()
{
LocalId = photoLocation.LocalId,
Secret = photoLocation.Secret,
VolumeId = photoLocation.VolumeId
}, 1024 * 256);
//address to save pic
string fileName = "D:\\Project\\user_profile.jpg";
using (var m = new MemoryStream(file.Bytes))
{
var img = Image.FromStream(m);
//pictureBox1.Image = img; //make a preview
img.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
I dotn know why there is no example for TLSharp!
i am a newbe like you if you found the solution please post it here
i just discovered that TLUser has a method named "photo"

Facebook upload multiple photos to album at once

I am working on developing WinService which uploads photos from specific folder on file system to Facebook page (to have upload, I have made Facebook application and connected it to Facebook page), where folder name is name which will be used for Facebook album.
So, first I create album, which is going fine and I have album id.
I have tried several ways to upload photos to Facebook album, but each time one popup notification is generated per each uploaded photo.
Way1:
FacebookClient fb = new FacebookClient(token.Trim());
//Perform upload
var imageStream = File.OpenRead(photo.Location);
fb.PostCompleted += (o, e) =>
{
imageStream.Dispose();
if (e.Cancelled || e.Error != null)
{
error = e.Error == null ? "canceled" : e.Error.Message;
}
};
dynamic res = fb.PostTaskAsync("/" + fbAlbumID + "/photos", new
{
message = String.Empty,
file = new FacebookMediaStream
{
ContentType = "image/jpg",
FileName = Path.GetFileName(photo.Location)
}.SetValue(imageStream)
});
res.Wait();
var dictionary = (IDictionary<string, object>)res.Result;
way2:
dynamic result = fb.Batch(
new FacebookBatchParameter(HttpMethod.Post, "/" + albumId + "/photos",
new Dictionary<string, object>
{
{"message", "picture 1 msg"},
{
"pic1",
new FacebookMediaObject {ContentType = "image/jpeg", FileName = "p4.jpg"}.SetValue(
File.ReadAllBytes(
file1path))
}
}),
new FacebookBatchParameter(HttpMethod.Post, "/" + albumId + "/photos",
new Dictionary<string, object>
{
{"message", "picture 1 msg"},
{
"pic2",
new FacebookMediaObject {ContentType = "image/jpeg", FileName = "p4.jpg"}.SetValue(
File.ReadAllBytes(
file2path))
}
}
)
);
but for each way, each uploaded photo has generated popup notification for people who have liked the page.
They, "likers", see this as spam.
How to achieve to upload 10 photos in one album and to have single notification?
Please advice, thanks.
The only way I've seen anyone accomplish this (a single feed item, or a single notification) is by using the Open Graph functionality. It really stinks that the base graph API doesn't have an easy way to do this. Whether you try a batched request (way 2), attaching a photo url, or attaching raw image data, you'll get multiple feed items and multiple notifications. Twitter's API achieves what you want by forcing you to upload multiple photos and getting back media_ids, which you can then attach to a Tweet.
See https://developers.facebook.com/docs/opengraph/using-actions/v2.2#photos. I know that setting up Open Graph may not be what you want to do, but it seems to truly be the only way at the time of this posting. Open Graph requires you to use user-level access tokens anyway, and you're using page-level tokens. So, given you're requirements, it doesn't seem to be possible yet.

How to get the facebook signed request in c#

I'm new to Facebook apps. I'm trying to create an MVC 4 application with Facebook Application as my Project Template.
I'm trying to catch the page id on which the page tab is created and I've got it somehow.
My problem here is when someone visits my app, I want to know the page id through which they are viewing the page tab. I've searched a lot where I got to know that I've to use FacebookSignedRequest for this. But this class is not available to me.
Thanks in advance for any help.
If you are simply trying to parse the signed_request parameter from Facebook, you can do so using the following C# code.
This code also verifies the hash using your own app_secret param, to ensure the signed_request originated from Facebook.
public static string DecodeSignedRequest(string signed_request)
{
try
{
if (signed_request.Contains("."))
{
string[] split = signed_request.Split('.');
string signatureRaw = FixBase64String(split[0]);
string dataRaw = FixBase64String(split[1]);
// the decoded signature
byte[] signature = Convert.FromBase64String(signatureRaw);
byte[] dataBuffer = Convert.FromBase64String(dataRaw);
// JSON object
string data = Encoding.UTF8.GetString(dataBuffer);
byte[] appSecretBytes = Encoding.UTF8.GetBytes(app_secret);
System.Security.Cryptography.HMAC hmac = new System.Security.Cryptography.HMACSHA256(appSecretBytes);
byte[] expectedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(split[1]));
if (expectedHash.SequenceEqual(signature))
{
return data;
}
}
}
catch
{
// error
}
return "";
}
private static string FixBase64String(string str)
{
while (str.Length % 4 != 0)
{
str = str.PadRight(str.Length + 1, '=');
}
return str.Replace("-", "+").Replace("_", "/");
}
All I had to do was create a Facebook Client object and call the ParseSignedRequest method with the app secret.
var fb = new FacebookClient();
dynamic signedRequest = fb.ParseSignedRequest(appSecret, Request.Form["signed_request"]);
This returns a Json object which we have to parse using JObject.Parse

Desktop app to create event through a facebook page

I have a facebook fanpage and I am trying to make a desktop application which can create events through this fanpage, however I'm having trouble understanding how the story goes with acces tokens, id, user permissions... If I am not mistaken once I have the accesstoken I can create an event using the facebookSDK from codeplex and the following function:
public string CreateEvent(string accessToken)
{
FacebookClient facebookClient = new FacebookClient(accessToken);
Dictionary<string, object> createEventParameters = new Dictionary<string, object>();
createEventParameters.Add("name", "My birthday party )");
createEventParameters.Add("start_time", DateTime.Now.AddDays(2).ToUniversalTime().ToString());
createEventParameters.Add("end_time", DateTime.Now.AddDays(2).AddHours(4).ToUniversalTime().ToString());
createEventParameters.Add("owner", "Balaji Birajdar");
createEventParameters.Add("description", " ( a long description can be used here..)");
//Add the "venue" details
JsonObject venueParameters = new JsonObject();
venueParameters.Add("street", "dggdfgg");
venueParameters.Add("city", "gdfgf");
venueParameters.Add("state", "gfgdfgfg");
venueParameters.Add("zip", "gfdgdfg");
venueParameters.Add("country", "gfdgfg");
venueParameters.Add("latitude", "100.0");
venueParameters.Add("longitude", "100.0");
createEventParameters.Add("venue", venueParameters);
createEventParameters.Add("privacy", "OPEN");
createEventParameters.Add("location", "fhdhdfghgh");
Add the event logo image
FacebookMediaObject logo = new FacebookMediaObject()
{
ContentType = "image/jpeg",
FileName = #"C:\logo.jpg"
};
logo.SetValue(File.ReadAllBytes(logo.FileName));
createEventParameters["#file.jpg"] = logo;
JsonObject resul = facebookClient.Post("/me/events", createEventParameters) as JsonObject;
return resul["id"].ToString();
}
Do I always need an application to do this?
I have a test application and I can get an access token from it using:
public string getToken(string strURL)
{
string strURL = "https://graph.facebook.com/oauth/access_token?client_id=149585851811979&client_secret=blablablablabalalbal&grant_type=client_credentials";
Uri Uri = new Uri(strURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri);
HttpWebResponse HWResponse = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(HWResponse.GetResponseStream());
string token = sr.ReadToEnd();
sr.Close();
token = token.Replace("access_token=", "");
return token;
}
I tried it like this but it obviously didn't work.
So my questions:
Do I always need an application? If yes, how do i connect it to my existing fan page?
Where do I set my user permissions? And how do I then login with the user?
I just think the documentation is a bit vague :s Sorry if my questions are stupid.
Any help/pseudocode is appreciated!
I am using BatchFB to create events in an App Engine app, it works for me, here is the code
// Some Date math that is from my App, but I am using Joda DateTime for output
// formatting.. I have found that if the start_time is malformed by FB standards it will
// to create an event, and give you an eventid, but the event never really gets created.
long hour = { your data }
DateTime start_time = new DateTime(d).plusHours((int)hour);
String stime = start_time.toString(ISODateTimeFormat.dateTime());
Batcher batcher = new FacebookBatcher(token);
Later<NewFeedItem> event = batcher.post(
"/events", NewFeedItem.class,
new Param("name", edata.getStringProperty(EventData.Schema.Name)),
new Param("start_time", stime )
);
long eventid = event.get().id;
I generate token on the client side with FBJS, and pass it to the server.
NewFeedItem is just a class defining an long variable, see batchFB's site..
With that said, I am thinking of switching to RestFB because I can't get BatchFB to support binary parameters with trying to post images. Also RestFB is documented better.. They seem to be related projects and refer to each other often.
I am not adding in Venue data yet, but I have read that for the GraphAPI to work, they need to be top level parameters. i.e. add in street, city, state at the same level as location and privacy..
When you try to read the event it will come in the venue parameter, but it needs to be top level when creating.. Also fallback to just using name and start_time, the only required parameters and add to that once it's working.
-John Gentilin

Categories