C# (Windows Phone) Facebook get info - c#

How do I get other info from the user like location, birthday, or gender? I'm using this code as a guide for the project that I'm doing. http://windowsphoneaalto.org/2012/01/facebook-get-information-about-the-user/
I was able to get the user's id and name but I can't get the other information. I tried getting the user's location by adding, string location = result["location"].ToString();
I ended up getting a null value and a keynotfoundexception. This is the piece of code that I'm having issues with.
void _fbClient_GetCompleted(object sender, FacebookApiEventArgs e)
{
//Turn the data into Dictionary.
//If you want to see what the Facebook is returning you can check it
//with this tool provided by Facebook
//http://developers.facebook.com/tools/explorer/?method=GET&path=me
var result = (IDictionary<string, object>)e.GetResultData();
//Get the ID value
string id = result["id"].ToString();
//Get the name value
string name = result["name"].ToString();
//Currently the thread running this code
//is not the UI thread and only UI thread can update
//UI. So we are calling the UI thread here.
_page.Dispatcher.BeginInvoke(() => {
MessageBox.Show(name + " (" + id + ")");
});

As far as i remember you'll need to add that to the facebook apps extended permission and then ask the user to give you the rights to share those details.
Look more for extended permission on facebook will solve your problem

Related

How to add value to a custom column while uploading document into a SharePoint document library as an item using C#?

I have a console application which tries to upload a document into a share point document library list.
I am successfully able to do it and also I am able to fill one of the custom Column(Column name is : "Category") value while uploading the file using C#.
I have tried to fill another custom column(Column name is : "Related Assets") value using the same procedure but i get the error stating the provided column name does not exist but when i see in actual share point portal it does exist.
So not able to solve this issue. Even i tried couple of methods as given below and i get same error message in terms of the column does not exist or it has been deleted or not able to recognize it.
Please find the screenshot of SharePoint showing the list of columns:
Please find the code i have till now which upload the document into SharePoint portal.
public static async Task<string> UploadReleaseNoteDocumentintoSpPortal(string releasenotefilepath, string releasenotefilename, string clientid, string clientsecret)
{
string status = string.Empty;
try
{
Console.WriteLine("Trying to Upload Release note file into Share Point Portal...");
string siteUrl = "<<Sp site URL>>";
Console.WriteLine("Connecting to Share Point Portal...");
var ClientContext = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, clientid, clientsecret);
ClientContext.Load(ClientContext.Web, p => p.Title);
await ClientContext.ExecuteQueryAsync();
Console.WriteLine(ClientContext.Web.Title);
var web = ClientContext.Web;
Console.WriteLine("Connected successfully to Share Point Portal...");
List DocumentsList = web.Lists.GetByTitle("Accelerators Documents");
ClientContext.Load(DocumentsList.RootFolder);
await ClientContext.ExecuteQueryAsync();
Console.WriteLine("Reading and loading the list named : Accelerators Documents from SP");
Console.WriteLine("Converting the release note document into byte array");
byte[] bytes = System.IO.File.ReadAllBytes(releasenotefilepath);
MemoryStream stream = new MemoryStream(bytes);
Console.WriteLine("Storing the release note Data into File Create information object of SharePoint");
FileCreationInformation FileCreateInfo = new FileCreationInformation();
FileCreateInfo.Content = bytes;
FileCreateInfo.ContentStream = stream;
FileCreateInfo.Overwrite = true;
FileCreateInfo.Url = DocumentsList.RootFolder.ServerRelativeUrl + #"\" + releasenotefilename;
Console.WriteLine("Adding file to SharePoint");
var ReleaseNoteFiledata = DocumentsList.RootFolder.Files.Add(FileCreateInfo);
ReleaseNoteFiledata.Update();
ReleaseNoteFiledata.ListItemAllFields["Category"] = "Release Notes";
//ReleaseNoteFiledata.ListItemAllFields["Related Assets"] = "<<Desired Value>>";
//IN Above commented line i get the error stating Microsoft.SharePoint.Client.ServerException:
//'Column 'Related Assets' does not exist. It may have been deleted by another user.
//But in actual site if we see it exists as you can see in above screenshot
ReleaseNoteFiledata.ListItemAllFields.Update();
ClientContext.Load(ReleaseNoteFiledata);
await ClientContext.ExecuteQueryAsync();
Console.WriteLine("Adding file to SharePoint Completed Successfully...");
return status = "Successful";
}
catch (Exception ex)
{
Console.WriteLine("Exception occured while trying to upload Release note file into CoP Portal :" + ex.Message);
return status = "Error/Exception";
}
}
Please find the error message i get while trying to add value to another custom column present in SharePoint:
Microsoft.SharePoint.Client.ServerException: 'Column 'Related Assets' does not exist. It may have been deleted by another user.
Even if i use the ReleaseNoteFiledata.SetFileProperties() and pass the values as a dictionary key value pair containing the column name and its value then also i get the same error for the second custom column. If i keep only the category custom column then it works perfectly without any issue as you can see in the screenshot above.
If i select the record and see the details or properties in the SharePoint the Related assets column symbol is some like in below screenshot:
Please let me know if the supporting documents are fine or still if my issue is not understandable so that i can re frame it or provide more screenshots.
Please help me in solving the above issue or how to make this column recognizable or readable or identifiable in the code.
Thanks in Advance
Regards
ChaitanyaNG
You need to use the internal name of the column 'Related Assets' in your code. It should be Related_x0020_Assets.
You could check the internal name of the column by go to list settings-> click the column, you would see the internal name in the url.

how to block a process in a web application only if the execution parameters are the same?

I have a web form with 4 dropdownlists and a search button that obtains a list from the database using the values ​​of the selected dropdownlist as filters, what I need is that if user A and B select the same values ​​of the dropdownlist, only 1 of them can work with the list obtained from the database. What would be the best way to work this?
//Get employee list
List<Entity.Employee> lstEmployees = new List<Entity.Employee>();
lstEmployees = Logic.Employee.getEmployees(DropDownList1.SelectedValue, DropDownList2.SelectedValue, DropDownList3.SelectedValue, DropDownList4.SelectedValue);
foreach(Employee emp in lstEmployees)
{
//single process per user required
}
//release single process
Here are two options depending on the environment you are using
1) If you are hosting it on a single server
You can use the application pool Application[Key1 + Key2 + Key3] as a way to track if someone is already working on that combination if not, let them continue.
2) If you are hosting it on a web farm
Use a database (or a shared storage somewhere ex: network share) to track the locking of those parameter combination similar to #1
Obviously #1 is easier/faster
2 is scalable
//Get employee list
List<Entity.Employee> lstEmployees = new List<Entity.Employee>();
lstEmployees = Logic.Employee.getEmployees(DropDownList1.SelectedValue, DropDownList2.SelectedValue, DropDownList3.SelectedValue, DropDownList4.SelectedValue);
foreach(Employee emp in lstEmployees)
{
String MyKey = DropDownList1.SelectedValue + DropDownList2.SelectedValue + DropDownList3.SelectedValue + DropDownList4.SelectedValue;
if(Application[MyKey]==null || Application[MyKey]=""){
//single process per user required
}
}
//release single process
I'm assuming that Employee is a class that you have access to?
The simplest solution I can picture here would be to incorporate a boolean field titled something like "isCheckedOut" and simply check for this value before allowing any data modification.
This solution doesn't really mechanically "lock-down" the code, but depending on how you're accessing it, this sort of quick check could be a very simple fix.
I write the code like this
string sProcesoUnico = ddlCompania.SelectedValue + ddlNomina.SelectedValue + ddlPeriodo.SelectedValue + ddlClaveMovi.SelectedValue;
if (Application[sProcesoUnico].ToString() == "" || Application[sProcesoUnico] == null)
{
try
{
// Process
}
catch (Exception)
{
throw;
}
finally
{
Application[sProcesoUnico] = ""; //release process
}
}
It´s ok the way that I release the Application State?

How to get whole Facebook friends list from api

Is there a way to get the whole Facebook friends list using an api!
I've tried a lot of thing and here's my shot:
FacebookClient f = new FacebookClient(access_token);
f.IsSecureConnection = true;
dynamic friendlist = await f.GetTaskAsync(#"https://graph.facebook.com/me/friendlists?access_token="+access_token);
t.Text = JsonConvert.SerializeObject(friendlist);
But all I got is an empty data!
Can anyone help me?
The friendlists endpoint is deprecated, as you can see in the breaking changes log: https://developers.facebook.com/docs/graph-api/changelog/breaking-changes#tagged-users-4-4
It would not have been what you expected anyway, it was only for lists, not friends directly. Access to all friends is not possible since a very long time. You can only get data of users/friends who authorized your App. You can use the /me/friends endpoint for that.
Another thread about getting all friends: Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application
There is another way can give you an access to your all friend list names by downloading a copy of your facebook information data by selecting friends and following checkbox and wait till your file is ready then download it.
This is not the API way but for starters who want one time download list of friends
Go to the friend list page: https://www.facebook.com/friends/list
Scroll all the way down so that all friend list loads
Press F12 to open developer tools, click on console tab
A. Show in console
copy paste following script in console and hit enter.
var accumulated = "";
for (var el of document.querySelectorAll('[data-visualcompletion="ignore-dynamic"]')) {
var name = el.getAttribute("aria-label");
if(name!= null && name != "null"){
accumulated = "Name:"+name +", "+ accumulated;
console.log(accumulated);
accumulated = "";
}else{
var a = el.getElementsByTagName("a")[0];
if(a){
accumulated += "Profile URL: "+ a.getAttribute("href");
//console.log(a);
}
}
}
B. Download a .json file
copy paste following script in console and hit enter.
var exportObj = [];
var accumulated = "";
for (var el of document.querySelectorAll('[data-visualcompletion="ignore-dynamic"]')) {
var name = el.getAttribute("aria-label");
if(name!= null && name != "null"){
exportObj.push({name: name, profileURL: accumulated});
accumulated = "";
}else{
var a = el.getElementsByTagName("a")[0];
if(a){
accumulated += a.getAttribute("href");
}
}
}
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", "friendsList.json");
document.body.appendChild(downloadAnchorNode);
downloadAnchorNode.click();
downloadAnchorNode.remove();
Note: pseudo code tested in firefox

Assistance with Oauth2 authentication to use with DropBox

I am building a Windows c# app that needs to upload files to DropBox. Basically I have everything I need for my app(app secret and app key), but I need to have the client tokens saved to my sql DB for future use. According to Dropbox I am unable to save user login info which is good, but finding a good lib is getting tough.I have tried many different DropBox based libraries but run across the following issues:
SharpBox: seems easy enough to use, but need some kind of deserializer to save the client key and client secret anywhere.
OAuth2 Authorizer: Not enough documentation that I can find, in order for me to actually implement this.
DropNet: This is one that looked promising. It's async and looked good, but again I can't find an example of how to perform the auth function and save the variables to a file/DB/Reg/ or anything.
DropBox.API: This is the method that I currently use and it's working. Problem is it's not Async and requires .NET 4.5. I was ok with all the downs but lately found that's it's very touchy about different versions of JSON and other libraries.
I was hoping someone could give me some assistance in getting any of the above OAUTH libs actually working, Just to get the 3 legged auth process working.
UPDATE::
ok so i am going to include some of the code that I am using at the moment, that uses dropbox.api:
// Get Oauth Token
private static OAuthToken GetAccessToken()
{
string consumerKey = "mykey";
string consumerSecret = "myseceret";
var oauth = new OAuth();
var requestToken = oauth.GetRequestToken(new Uri(DropboxRestApi.BaseUri), consumerKey, consumerSecret);
var authorizeUri = oauth.GetAuthorizeUri(new Uri(DropboxRestApi.AuthorizeBaseUri), requestToken);
Process.Start(authorizeUri.AbsoluteUri);
MessageBox.Show("Once Registration is completed Click OK", "Confirmation");
return oauth.GetAccessToken(new Uri(DropboxRestApi.BaseUri), consumerKey, consumerSecret, requestToken);
}
// Complete Oauth function and write to file
private void button5_Click(object sender, EventArgs e)
{
DialogResult result1 = MessageBox.Show("Please register for dropbox before continuing with authentication. The authorization process will take 1 minute to complete. During that time the backup utility window will be unresponsive. Click yes if you are ready to begin the authorization. HAVE YOU REGISTERED FOR DROPBOX YET?", "DO YOU HAVE A DROPBOX ACCOUNT?", MessageBoxButtons.YesNo);
if (result1 == DialogResult.Yes)
{
try
{
u_w.Enabled = false;
var accesstoken = GetAccessToken();
StringBuilder newFile = new StringBuilder();
string temptoken = "";
string tempsecret = "";
string tempprovider = "";
string tempstatus = "";
string[] file = System.IO.File.ReadAllLines(#"C:\cfg\andro_backup.ini");
foreach (string line in file)
{
if (line.Contains("dbkey:"))
{
temptoken = line.Replace("dbkey:", "dbkey:" + accesstoken.Token);
newFile.Append(temptoken + "\r\n");
continue;
}
if (line.Contains("dbsecret:"))
{
tempsecret = line.Replace("dbsecret:", "dbsecret:" + accesstoken.Secret);
newFile.Append(tempsecret + "\r\n");
continue;
}
if (line.Contains("Provider:"))
{
tempprovider = line.Replace("Provider:", "Provider:DropBox");
newFile.Append(tempprovider + "\r\n");
continue;
}
if (line.Contains("Status:"))
{
tempstatus = line.Replace("Status:", "Status:Connected");
newFile.Append(tempstatus + "\r\n");
continue;
}
newFile.Append(line + "\r\n");
}
System.IO.File.WriteAllText(#"C:\cfg\andro_backup.ini", newFile.ToString());
MessageBox.Show("Completed Backup Provider Setup", "Provider Setup Complete");
Configuration.Reload();
The Above works at the moment and I can upload, download files. The issue is it's not Async and I would like to attempt to stay within the .NET 4.0 if possible, this code requires 4.5
Trying to do the same thing with dropnet, I am unable to get it to work at all even using the examples he has given on the page located here https://github.com/dkarzon/DropNet.
I attempted to look at the demos he has on there as well , but they explaing having the user login everytime to perform any functions, where I need the app to be authorized so it can do it's deeds when it needs to. As far as the code I am using for drop net, I literally just copied and pasted what he had there, just to even see if I can get it to connect and still no go.
If you are using DropNet similar to the examples all you need to do is save the return object from the GetAccessToken method. That returns an instance of a UserLogin object which has the Token and secret on it. Or if you are using the async methods for it then the callback parameter.
Checkout the sample here:
https://github.com/dkarzon/DropNet/blob/master/DropNet.Samples/DropNet.Samples.WP7/MainPage.xaml.cs#L69
Post the code you are using for it so I can give you a better explanation for it.

Facebook / Offline Permission - Trying to perform an action on a set of offline users

We're building an app which in part of its functionality tries to capture the number of likes associated to a particular video owned by a user.
Users of the app are asked for extended off-line access and we capture the key for each user:
The format is like this: 2.hg2QQuYeftuHx1R84J1oGg__.XXXX.1272394800-nnnnnn
Each user has their offline / infinite key stored in a table in a DB. The object_id which we're interested in is also stored in the DB.
At a later stage (offline) we try to run a batch job which reads the number of likes for each user's video. (See attached code)
For some reason however, after the first iteration of the loop - which yields the likes correctly, we get a failure with the oh so familiar message:
"Session key is invalid or no longer valid"
Any insight would be most appreciated.
Thanks,
B
List<DVideo> videoList = db.SelectVideos();
foreach (DVideo video in videoList)
{
long userId = 0;
ConnectSession fbSession = new ConnectSession(APPLICATION_KEY, SECRET_KEY);
//session key is attached to the video object for now.
fbSession.SessionKey = video.UserSessionKey;
fbSession.SessionExpires = false;
string fbuid =video.FBUID;
long.TryParse(fbuid, out userId);
if (userId > 0)
{
fbSession.UserId = userId;
fbSession.Login();
Api fbApi = new Facebook.Rest.Api(fbSession);
string xmlQueryResult = fbApi.Fql.Query("SELECT user_id FROM like WHERE object_id = " + video.FBVID);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(new StringReader(xmlQueryResult));
int likesCount = xmlDoc.GetElementsByTagName("user_id").Count;
//Write entry in VideoWallLikes
if (likesCount > 0)
{
db.CountWallLikes(video.ID, likesCount);
}
fbSession.Logout();
}
fbSession = null;
}
You said you have asked user for extended offline access, but by looking at your access token, it is not long-lived. your token is 2.hg2QQuYeftuHx1R84J1oGg__.XXXX.1272394800-nnnnnn, within it, the "1272394800" is expiration epoch time.

Categories

Resources