Get Posts (Wall Facebook) of me and my friends - c#

I use
https://developers.facebook.com/tools/access_token/
I create an App. I want get Posts of the wall of me and my friends.
I try me/feed and me/posts but I get nothing.
I have this unit test.
Any suggestions?
[TestMethod]
public void Basic_using_SDK()
{
// http://blog.prabir.me/posts/facebook-csharp-sdk-making-requests
var fb = new Facebook.FacebookClient();
var result = (IDictionary<string, object>)fb.Get("4");
var id = (string)result["id"];
var name = (string)result["name"];
var firstName = (string)result["first_name"];
var lastName = (string)result["last_name"];
var link = (string)result["link"];
var username = (string)result["username"];
var gender = (string)result["gender"];
var male = (string)result["locale"];
var parameters = new Dictionary<string, object>();
parameters["fields"] = "id,name";
result = (IDictionary<string, object>)fb.Get("4", parameters);
id = (string)result["id"];
name = (string)result["name"];
dynamic result2 = fb.Get("4");
id = result2.id;
name = result2.name;
firstName = result2.first_name;
lastName = result2.last_name;
link = result2.link;
username = result2.username;
gender = result2.gender;
male = result2.locale;
dynamic parameters2 = new ExpandoObject();
parameters2.fields = "id,name";
dynamic result3 = fb.Get("4", parameters);
id = result3.id;
name = result3.name;
dynamic me = fb.Get("zuck");
firstName = me.first_name;
lastName = me.last_name;
var client = new FacebookClient(AccessToken);
dynamic me2 = client.Get("me");
string aboutMe = me2.about;
dynamic result4 = client.Get("/me/feed");
foreach (dynamic post in result4.data)
{
var fromName = post.from.name;
Console.WriteLine(fromName);
}
dynamic result5 = client.Get("/me/posts");
for (int i = 0; i < result5.Count; i++)
{
}
// https://www.facebook.com/profile.php?id=xxxxxxx
// https://graph.facebook.com/xxxxxxx
var uidKiquenet = "xxxxx";
var query = string.Format(#"SELECT status_id,message,time,source,uid,place_id
FROM status WHERE uid IN (SELECT uid FROM status WHERE uid = '" + uidKiquenet + "') ORDER BY time DESC");
dynamic parameters6 = new ExpandoObject();
parameters6.q = query;
dynamic results6 = fb.Get("/xxxxx?fields=id,name,age_range,about,email,first_name,gender");
string myMessage = "Hello from Test";
fb.PostTaskAsync("me/feed", new { message = myMessage }).ContinueWith(t =>
{
if (!t.IsFaulted)
{
string message = "Great, your message has been posted to you wall!";
Console.WriteLine(message);
}
});
fb.GetTaskAsync("me").ContinueWith(t =>
{
if (!t.IsFaulted)
{
var result11 = (IDictionary<string, object>)t.Result;
string myDetails = string.Format("Your name is: {0} {1} and your Facebook profile Url is: {3}",
(string)result11["first_name"], (string)result11["last_name"],
(string)result11["link"]);
Console.WriteLine(myDetails);
}
});
// This uses Facebook Query Language
// See https://developers.facebook.com/docs/technical-guides/fql/ for more information.
query = string.Format("SELECT uid,name,pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1={0}) ORDER BY name ASC", "me()");
fb.GetTaskAsync("fql", new { q = query }).ContinueWith(t =>
{
if (!t.IsFaulted)
{
var result1 = (IDictionary<string, object>)t.Result;
var data = (IList<object>)result1["data"];
var count = data.Count;
var message = string.Format("You have {0} friends", count);
Console.WriteLine(message);
foreach (IDictionary<string, object> friend in data)
Console.WriteLine((string)friend["name"]);
}
});
}

You must authorize with the correct permission in order to get access to feed posts. Try authorizing with user_posts, as it is explained in the docs: https://developers.facebook.com/docs/graph-api/reference/v2.3/user/feed#read
Be aware that this does not get you access to posts of friends, unless they posted on the wall of the authorized user.
About review, you may want to read this: https://developers.facebook.com/docs/facebook-login/review/faqs#what_is_review
Btw, FQL is deprecated and will only work in v2.0 Apps - not in newer ones.

Same thing happened to me . Here is my Solution
I made my project registered on Facebook developer console. Then I did my code same as you but could not get posts / information . After some time i submitted my application for app review to facebook team (it was still in early development phase) and after their feedback I got my code working . So pending Application review can be your issue also . This option is available in application setting . Give it a shot
Update
Another code sample is here
if (Request["code"] == null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
FB_app_id, Request.Url.AbsoluteUri, FB_scope));
return false;
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}&perms=status_update"
, FB_app_id, Request.Url.AbsoluteUri, FB_scope, Request["code"].ToString(), FB_secret_id);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader rd = new StreamReader(response.GetResponseStream());
string vals = rd.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf('=')), token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf('=') - 1));
}
string access_token = tokens["access_token"];
Session["fb_access_token"] = access_token;
return true;
}
}

Related

C# Solr query - how to only get future dates?

I have a search method that queries Solr for event items. I need to modify it to only get events where the date has not already passed (i.e. Where(x => x.EventDate.Date >= DateTime.Now.Date), but I'm not sure how to add this because I'm not very familiar with Solr. Here's my search function:
public SearchQueryResults Search(string keywords, int page,int perPage, List<Guid> contentTypeFilters, List<Guid> otherFilters, ISortBuilder<SearchResultItem> sortBuilder)
{
var searchFilters = new List<IPredicateBuilder<SearchResultItem>>()
{
new IsSearchablePredicateBuilder()
};
if (contentTypeFilters.Any())
{
var contentTypePredicateBuilder = new ContentTypePredicateBuilder();
contentTypePredicateBuilder.ContentTypes = contentTypeFilters;
searchFilters.Add(contentTypePredicateBuilder);
}
if (otherFilters.Any())
{
var tagFilterBuilder = new TagsAndPredicateBuilder(otherFilters,_sitecoreContext);
searchFilters.Add(tagFilterBuilder);
}
if (string.IsNullOrWhiteSpace(keywords))
{
keywords = "";
}
SearchRequest searchRequest = new SearchRequest();
var queryParams = new Dictionary<string, string>() { };
queryParams.Add("q", keywords);
searchRequest.QueryParameters = queryParams;
searchRequest.SortBy = "";
searchRequest.SortOrder = "";
SearchQuery<SearchResultItem> queryArguments = new SearchQuery<SearchResultItem>();
queryArguments.FilterBuilders = searchFilters;
queryArguments.Page = page;
queryArguments.PerPage = perPage;
queryArguments.FacetsBuilder = new SearchFacetBuilder<SearchResultItem>();
queryArguments.SearchRequest = searchRequest;
queryArguments.IndexName = _indexName;
if (string.IsNullOrWhiteSpace(keywords))
{
queryArguments.QueryBuilders =new List<IPredicateBuilder<SearchResultItem>>();
}
else
{
queryArguments.QueryBuilders = new[] { new KeywordPredicateBuilder<SearchResultItem>(new[] { keywords }) };
}
queryArguments.SortBuilder = sortBuilder;
try
{
var results = _searchManager.GetResults<SearchResultItem>(queryArguments);
SearchQueryResults queryResults = new SearchQueryResults();
queryResults.ResultItems = results.Results;
queryResults.CurrentPage = page;
queryResults.TotalResults = Int32.Parse(results.TotalResults.ToString());
queryResults.TotalPages = (queryResults.TotalResults + perPage - 1) / perPage; ;
return queryResults;
}
catch (Exception exc)
{
Sitecore.Diagnostics.Log.Error("Error with FilteredSearch, could be a loss of connection to the SOLR server: " + exc.Message, this);
return null;
}
}
and here is how it's being called:
Results = _searchService.Search(searchTerm, CurrentPage - 1, 10, contentTypes, searchFilters,
new GenericSortBuilder<SearchResultItem>(q => q.OrderByDescending(r => r.SearchDate)));
How do I add in date filtering so that it only returns items where the date is in the future?
I would add filter query to the list of existing ones filtering the date field. On the documentation page, I was able to find information about fluent API, which could help here
Query.Field("date").From(DateTime.Now)
I'm not C# developer, that this code could have some mistakes, but I think the main idea is clear what needs to be done.

Can Update a photo tags in existing One

My question is can able to add a tag from existing one (means existing phtos).Now iam able to tag a friends in fresh upload using this code
private const string ExtendedPermissions = "user_about_me,user_photos,publish_stream";
[HttpPost]
[FacebookAuthorize(Permissions = ExtendedPermissions, LoginUrl = "/Home/LogOn?ReturnUrl=~/Home")]
public ActionResult MensagemPost(string message)
{
var fb = new FacebookWebClient();
dynamic me = fb.Get("me");
string friendId_1 = // get the first one friend id
string friendId_2 = // get the second one friend id
var tags = new[]
{
new { tag_uid = friendId_1, x = 20, y = 20 },
new { tag_uid = friendId_2, x = 40, y = 40 },
new { tag_uid = (string)me.id, x = 60, y = 60 }
};
dynamic parameters = new ExpandoObject();
parameters.message = message;
parameters.tags = tags;
parameters.url = "http://1.bp.blogspot.com/-evheT51sfeM/TlO_wZ8YDqI/AAAAAAAAA8I/fjlg0G8AgMY/s1600/The-best-top-hd-desktop-naruto-shippuden-wallpaper-naruto-shippuden-wallpapers-hd-11.jpg";
dynamic result = fb.Post("me/photos", parameters);
return RedirectToAction("Index", new { success = true });
}
but cannot i update the tags in existing one.
My try IS
var res = FbClient.Post("/4333418373210452/tags", PostInfo);
AccessToken = Properties.Settings.Default.FBAccessToken;
FacebookClient FbClient = new FacebookClient(AccessToken);
var PostInfo = new Dictionary<string, object>();
var tags = new[] { new { tag_uid = "870415313026255", tag_text = "Tag updated", x = 90, y = 110 } };
PostInfo.Add("tags", tags);
var result = FbClient.Post("/4333418373210452/tags", PostInfo);
This code is getting error from facebook.The error says
(GraphMethodException - #100) Unsupported post request. Please read
the Graph API documentation at
https://developers.facebook.com/docs/graph-api
i try to googling but cannot get the solution till now ..anyone help me out..your comments also welcome
Jagadeesh Govindaraj
Found the solution...previously i'm try to POST REQUEST Against my friend ID, But now i changed to phtoID..Its Worked.
AccessToken = Properties.Settings.Default.FBAccessToken;
FacebookClient FbClient = new FacebookClient(AccessToken);
var PostInfo = new Dictionary<string, object>();
var tags = new[] { new { tag_uid = "870415313026255", tag_text = "Tag updated", x = 90, y = 110 } };
PostInfo.Add("tags", tags);
var result = FbClient.Post("/"Existing PhotoID"/tags", PostInfo);

Why doesn't StartWorkflow() start my workflow in C#?

I am attempting to programatically start a SharePoint 2013 workflow. The workflow takes five parameters, puts them in an email body and e-mails them to me. When I go to the SharePoint website I can start this workflow manually, so I know the workflow is correct. When I try to use the SharePoint API's to start the workflow, I get no errors, I get an empty Guid back, and the workflow does not run.
public Guid Add(Project project)
{
var result = Guid.Empty;
var siteUri = new Uri(ConfigurationManager.AppSettings["SharePoint.Site"]);
var workflowName = ConfigurationManager.AppSettings["SharePoint.WorkflowName"];
using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(siteUri, null))
{
var workflowServiceManager = new WorkflowServicesManager(clientContext, clientContext.Web);
var workflowSubscriptionService = workflowServiceManager.GetWorkflowSubscriptionService();
var subscriptions = workflowSubscriptionService.EnumerateSubscriptions();
clientContext.Load(subscriptions, subs => subs.Where(sub => sub.Name == workflowName));
clientContext.ExecuteQuery();
foreach (var subscription in subscriptions)
{
var instanceService = workflowServiceManager.GetWorkflowInstanceService();
var initiationData = new Dictionary<string, object>
{
{"pProjectName", project.Name},
{"pDivision", _divisionData.GetDivisionName(project.DivisionId ?? Guid.Empty) },
{"pOperatingGroup", "****TODO: Operating Group****"},
{"pClientName", _clientData.GetClientName(project.ClientId ?? Guid.Empty) },
{"pSiteUrl", "****TODO: Site URL****" }
};
var startResult = instanceService.StartWorkflow(subscription, initiationData);
result = startResult.Value;
}
}
return result;
}
string subscriptionID = "WFListSubscriptionID of your wf";//it is a guid
int itemID = "Item.ID, Id of a item that you start wf for";
Guid workflowSubscriptionIdGuid = new Guid(subscriptionID);
var workflowServiceManager = new WorkflowServicesManager(item.Web);
var workflowSubscriptionService = workflowServiceManager.GetWorkflowSubscriptionService();
var workflowSubscription = workflowSubscriptionService.GetSubscription(workflowSubscriptionIdGuid);
var inputParameters = new Dictionary<string, object>();
workflowServiceManager.GetWorkflowInstanceService().StartWorkflowOnListItem(workflowSubscription, itemID, inputParameters);

How to Create a campaign in MailChimp using ASP.Net

I need to create and send immediately campaigns in MailChimp.com. I used C# wrapper Percepective MCAPI.dll for this purpose.
from the MailChimp API, Its clear that we cannot lists but can create campaigns. I tried code but the campaignID is retured null; no exception thrown atleast. I did set the campaigntype to Auto.
here is my code snippet:
try
{
string apiKey = "api-us2"; // API KEY is valid
string emailAddress = "ravinderpal.singh#abc.net";
listsForEmailInput lstForEmailInput = new listsForEmailInput(apiKey, emailAddress);
listsForEmail cmd = new listsForEmail(lstForEmailInput);
listsForEmailOutput lstEmailOutPut = cmd.Execute();
List lstResults = lstEmailOutPut.result;
string listID = lstResults[0]; // Got Precraeted List ID( Valid Confirmed )
Console.WriteLine("\n" + listID);
// compaign Create
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = " New Campaign from dev_Anil";
campaignCreateOpt.from_email = "anil.k#abc.net";
campaignCreateOpt.from_name = "anil";
Dictionary content = new Dictionary();
content.Add("html", "Helloaasdsa");
content.Add("text", "Hi all !! this is dev_anil");
content.Add("url", "");
content.Add("archive", "");
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "any"; // Could not set Condition -- need help for this
// Need to set a Dictionary typeOptions because null is not supported
Dictionary typeOptions = new Dictionary();
campaignCreateParms campaignCreateParms = new campaignCreateParms(apiKey, EnumValues.campaign_type.auto, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campaignCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campaignCreateInput);
campaignCreateOutput ccOutput = campaignCreate.Execute(campaignCreateInput);
string abc = ccOutput.result; // This comes out to null
}
catch(Exception ee)
{
Console.WriteLine("\n\n Exception :" + ee.Message); // no exception
}
can anybody show me the right direction and what is wrong with the code.
any help would be much appreciated.
thanks.
I solved this problem and here is code as solution. here listID is precreated List ID in your account in Mailchimp.
private void CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 100;
string campaignID =string.Empty;
// compaign Create Options
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = "subject";
campaignCreateOpt.from_email = "abc#xyz.com";
campaignCreateOpt.from_name = "abc";
campaignCreateOpt.template_id = TemplateID;
// Content
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("html_ArticleTitle1", "ArticleTitle1");
content.Add("html_ArticleTitle2","ArticleTitle2");
content.Add("html_ArticleTitle3", "ArticleTitle3");
content.Add("html_Article1", "Article1");
content.Add("html_Article2", "Article2");
// Conditions
List<campaignSegmentCondition> csCondition = new List<campaignSegmentCondition>();
campaignSegmentCondition csC = new campaignSegmentCondition();
csC.field = "interests-" + 123; // where 123 is the Grouping Id from listInterestGroupings()
csC.op = "all";
csC.value = "";
csCondition.Add(csC);
// Options
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "all";
// Type Options
Dictionary<string, string> typeOptions = new Dictionary<string, string>();
typeOptions.Add("offset-units", "days");
typeOptions.Add("offset-time", "0");
typeOptions.Add("offset-dir", "after");
// Create Campaigns
campaignCreate campaignCreate = new campaignCreate(new campaignCreateInput(apiKey, EnumValues.campaign_type.plaintext, campaignCreateOpt, content, csOptions, typeOptions));
campaignCreateOutput ccOutput = campaignCreate.Execute();
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
if (error.Count <= 0)
{
campaignID = ccOutput.result;
}
else
{
foreach (Api_Error ae in error)
{
Console.WriteLine("\n ERROR Creating Campaign : ERRORCODE\t:" + ae.code + "\t ERROR\t:" + ae.error);
}
}
}
I removed the url and archive from the content. Then the campaign was created just fine:
// campaign Create
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listId;
campaignCreateOpt.subject = " New Campaign from Someemone";
campaignCreateOpt.from_email = "someone#home.com";
campaignCreateOpt.from_name = "someone";
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("html", "Lots of cool stuff here.");
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "any"; // Could not set Condition -- need help for this
// Need to set a Dictionary typeOptions because null is not supported
Dictionary<string,string> typeOptions = new Dictionary<string, string>();
campaignCreateParms campaignCreateParms = new campaignCreateParms(apiKey, EnumValues.campaign_type.trans, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campaignCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campaignCreateInput);
campaignCreateOutput ccOutput = campaignCreate.Execute(campaignCreateInput);
string newCampaignId = ccOutput.result; // Not null anymore

Multiple complexFilter in Magento's api v2

Currently I’m having some difficulties with using new Magento's soap v2 from c# interface.
With php i was able to do something like this:
$params["created_at"]["from"] = date("Y-m-d H:i:s",Functions::convert_time($dataDa));
$params["created_at"]["to"] = date("Y-m-d H:i:s",Functions::convert_time($dataA));
MageInterface::getSingleton()->shipmentList($params);
In this mode i was able to find list of orders which were created from $dataDa to $dataA without problems. With c# however it seems that only the last one of the selectors work.
My code:
var cpf = new complexFilter[2];
cpf[0] = new complexFilter
{
key = "created_at",
value = new associativeEntity
{
key = "to",
value = uxDataA.DateTime.ToString("yy-MM-dd HH:mm:ss")
}
});
cpf[1] = new complexFilter
{
key = "created_at",
value = new associativeEntity
{
key = "from",
value = uxDataDa.DateTime.ToString("yy-MM-dd HH:mm:ss")
}
});
var filters = new filters();
filters.complex_filter = cpf;
var risultato = mage.salesOrderList(sessionKey, filters);
In this mode only created_at->from criteria is taken in consideration (it's like second complex filter override previous one with the same key). Ideas?
Thanks in advance.
This works for me :
private filters addFilter(filters filtresIn, string key, string op, string value)
{
filters filtres = filtresIn;
if (filtres == null)
filtres = new filters();
complexFilter compfiltres = new complexFilter();
compfiltres.key = key;
associativeEntity ass = new associativeEntity();
ass.key = op;
ass.value = value;
compfiltres.value = ass;
List<complexFilter> tmpLst;
if (filtres.complex_filter!=null)
tmpLst = filtres.complex_filter.ToList();
else tmpLst = new List<complexFilter>();
tmpLst.Add(compfiltres);
filtres.complex_filter = tmpLst.ToArray();
return filtres;
}
and call
{
Mage_Api_Model_Server_V2_HandlerPortTypeClient clientSoap = new Mage_Api_Model_Server_V2_HandlerPortTypeClient();
string sessionId = clientSoap.login(LOG, PASS);
filters filtres = new filters();
filtres = addFilter(filtres, "status", "eq", "processing");
filtres = addFilter(filtres, "created_at", "from", "2014-09-07 08:00:00");
filtres = addFilter(filtres, "created_at", "to", "2014-09-07 00:00:00");
salesOrderEntity[] lst = clientSoap.salesOrderList(sessionId, filtres);
}
Solved, there was a bug (or the feature?) in mage\sales\order\api\v2.php
See more info in this thread: http://www.magentocommerce.com/boards/viewthread/70368/

Categories

Resources