hi i am trying to upload images from my wp8.1 app to facebook but one of the issues is that pictures posted are visible to only me unless i amnually change it from facebook . i want to post them automatically for public to view . here is my code :
var postParams = new
{
access_token = ObjFBHelper.AccessToken,
message = "My message",
source = pic,
};
try
{
dynamic fbPostTaskResult = await fbclient.PostTaskAsync("me/photos",postParams);
var responseresult = (IDictionary<string, object>)fbPostTaskResult;
}
catch (Exception ex)
{
//MessageDialog ErrMsg = new MessageDialog("Error Ocuured!");
}
var parameters = new Dictionary<string, object>
{
{ "message", FacebookMessage },
{ "privacy", new Dictionary<string, object>
{
{ "value", "ALL_FRIENDS" }
}
}
};
I found this on stackoverflow. Maybe it helps you too?
From: SO question
Related
Because of a limitation in message size in the Office API, I am trying to build a service that:
Office client gets identity token (getCallbackTokenAsync)
Posts message including identity token to service
Service creates new new Exchange Service, with new Token Credential
Limitations:
The EWS server is on premise, and it is currently not possible to use OAuth
I'm currently using this as a RESTful service
I have tried getUserIdentityToken, but that is not useful for credentials.
Office JS call
var _appName;
var _mailbox;
var _emailAddress;
var _itemId;
var _identityToken;
var _ewsUrl;
app.initialize();
_mailbox = Office.context.mailbox;
var item = _mailbox.item;
_itemId = item.itemId;
_ewsUrl = _mailbox.ewsUrl;
_emailAddress = _mailbox.userProfile.emailAddress;
function MakeRequest(serviceUrl, callType, format) {
_mailbox.getCallbackTokenAsync(function (asyncResult) {
if (asyncResult.error) {
app.showNotification(_appName, "Error getting Use Identity Token: " + asyncResult.error.message);
}
else {
_identityToken = asyncResult.value;
var correctedItemId = _itemId.replace("+", "_");
var request = { ItemId: correctedItemId, UserEmailAddress: _emailAddress, UserIdentityToken: _identityToken, EwsUrl: _ewsUrl, AudienceUrl: _audUrl, ReturndNewId: false };
$.ajax({
crossDomain: true,
url: serviceUrl,
type: callType,
data: JSON.stringify(request),
contentType: 'application/json; charset=utf-8',
dataType: format,
success: function (asyncResultSuccess) {
LogResult(asyncResultSuccess.statusText);
//app.showNotification(_appName, asyncResultSuccess.statusText);
},
error: function (asyncResultError) {
LogResult(asyncResultError.statusText);
//app.showNotification(_appName, asyncResultError.statusText);
}
});
}
});
}
Server Side Credential:
void LoadSimple()
{
try
{
service = new ExchangeService(ExchangeVersion.Exchange2013_SP1)
{
Credentials = new TokenCredentials(RequestProperties.UserIdentityToekn),
Url = new Uri(RequestProperties.EwsUrl)
};
ReturnProps = new EwsReturnItem();
}
catch (Exception ex)
{
log.Error(string.Format("{0}: {1}", MethodBase.GetCurrentMethod().Name, ex.Message));
}
}
Server Side Forward Message:
public EwsReturnItem Forward(string toRecipient, string ccRecipient, string subjectPrepend, string bodyText)
{
try
{
var correctedId = CorrectItemId(RequestProperties.ItemId);
EmailMessage email = EmailMessage.Bind(service, correctedId, new PropertySet(ItemSchema.MimeContent, ItemSchema.Subject));
ResponseMessage forwardMessage = email.CreateForward();
forwardMessage.Subject = String.Format("{0}{1}", subjectPrepend, email.Subject);
forwardMessage.ToRecipients.Add(toRecipient);
forwardMessage.CcRecipients.Add(ccRecipient);
forwardMessage.BodyPrefix = bodyText;
...snip
}
catch (Exception ex)
{
log.Error(string.Format("{0}: {1}", MethodBase.GetCurrentMethod().Name, ex.Message));
return new EwsReturnItem() { StatusText = ex.Message };
}
}
It fails as unauthorized on this line:
EmailMessage email = EmailMessage.Bind(service, correctedId, new PropertySet(ItemSchema.MimeContent, ItemSchema.Subject));
I'm developing a Facebook with the Microsoft.Bot.Builder Framework (4.2.2)
The Bot Works on emulator and on Azure with the "Test in Web Chat" Really fine. But on the Facebook Channel I get an "There was an error sending this message to your bot: HTTP status code InternalServerError"
My log stream says:
019-04-12 13:23:22.154 +00:00 [Information]
Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting
HTTP/1.1 POST
http://thomasreigltestbot1995.azurewebsites.net/api/messages
application/json; charset=utf-8 688
2019-04-12 13:23:22.155 +00:00 [Information]
Microsoft.Bot.Builder.Integration.IAdapterIntegration: Received an
incoming activity. ActivityId: Vg2USjaJGCZ1Ib_-
LTftnL9F6qg_DCJaV3XbIqGzSpisuO10eYLezkjHJxSVcYAAUWQvynDJbUyfvyBgN30B3w
2019-04-12 13:23:22.155 +00:00 [Information]
Microsoft.Bot.Builder.Integration.IAdapterIntegration: Sending
activity. ReplyToId: Vg2USjaJGCZ1Ib_-
LTftnL9F6qg_DCJaV3XbIqGzSpisuO10eYLezkjHJxSVcYAAUWQvynDJbUyfvyBgN30B3w
2019-04-12 13:23:22.388 +00:00 [Error]
Facebook_Events_Bot.FacebookEventsBot: Exception caught :
Microsoft.Bot.Schema.ErrorResponseException: Operation returned an
invalid status code 'Unauthorized'at
Microsoft.Bot.Connector.Conversations.
This is my simple Bot from this repo:
https://github.com/Microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/23.facebook-events
public class FacebookEventsBot : IBot
{
private const string DialogId = "question";
/// </summary>
private readonly DialogSet _dialogs;
private Tuple<int, string> tuple;
public FacebookEventsBot(BotAccessors accessors)
{
if (accessors == null)
{
throw new ArgumentNullException(nameof(accessors));
}
_dialogs = new DialogSet(accessors.ConversationDialogState);
_dialogs.Add(new AttachmentPrompt(DialogId));
}
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
const string facebookPageNameOption = "Facebook Page Name";
const string quickRepliesOption = "Quick Replies";
const string postBackOption = "PostBack";
if (turnContext == null)
{
throw new ArgumentNullException(nameof(turnContext));
}
// Check if we are on the Facebook channel.
if (turnContext.Activity.ChannelId == Channel.Channels.Facebook)
{
// Analyze Facebook payload from channel data.
ProcessFacebookPayload(turnContext.Activity.ChannelData);
// Initially the bot offers to showcase 3 Facebook features: Quick replies, PostBack and getting the Facebook Page Name.
// Below we also show how to get the messaging_optin payload separately as well.
switch (turnContext.Activity.Text)
{
// Here we showcase how to obtain the Facebook page name.
// This can be useful for the Facebook multi-page support provided by the Bot Framework.
// The Facebook page name from which the message comes from is in turnContext.Activity.Recipient.Name.
case facebookPageNameOption:
{
var reply = turnContext.Activity.CreateReply($"This message comes from the following Facebook Page: {turnContext.Activity.Recipient.Name}");
await turnContext.SendActivityAsync(reply);
break;
}
// Here we send a HeroCard with 2 options that will trigger a Facebook PostBack.
case postBackOption:
{
var dialogContext = await _dialogs.CreateContextAsync(turnContext, cancellationToken);
var results = await dialogContext.ContinueDialogAsync(cancellationToken);
var card = new HeroCard
{
Text = "Is 42 the answer to the ultimate question of Life, the Universe, and Everything?",
Buttons = new List<CardAction>
{
new CardAction() { Title = "Yes", Type = ActionTypes.PostBack, Value = "Yes" },
new CardAction() { Title = "No", Type = ActionTypes.PostBack, Value = "No" },
},
};
var reply = turnContext.Activity.CreateReply();
reply.Attachments = new List<Attachment> { card.ToAttachment() };
await turnContext.SendActivityAsync(reply);
break;
}
// By default we offer the users different actions that the bot supports, through quick replies.
case quickRepliesOption:
default:
{
var reply = turnContext.Activity.CreateReply("What Facebook feature would you like to try? Here are some quick replies to choose from!");
reply.SuggestedActions = new SuggestedActions()
{
Actions = new List<CardAction>()
{
new CardAction() { Title = quickRepliesOption, Type = ActionTypes.PostBack, Value = quickRepliesOption },
new CardAction() { Title = facebookPageNameOption, Type = ActionTypes.PostBack, Value = facebookPageNameOption },
new CardAction() { Title = postBackOption, Type = ActionTypes.PostBack, Value = postBackOption },
},
};
await turnContext.SendActivityAsync(reply);
break;
}
}
}
else
{
// Check if we are on the Facebook channel.
if (turnContext.Activity.ChannelId == Channel.Channels.Facebook)
{
// Here we can check for messaging_optin webhook event.
// Facebook Documentation for Message optin:
// https://developers.facebook.com/docs/messenger-platform/reference/webhook-events/messaging_optins/
}
await turnContext.SendActivityAsync($"Received activity of type {turnContext.Activity.Type}.");
}
}
private void ProcessFacebookPayload(object channelData)
{
// At this point we know we are on Facebook channel, and can consume the Facebook custom payload
// present in channelData.
var facebookPayload = (channelData as JObject)?.ToObject<FacebookPayload>();
if (facebookPayload != null)
{
// PostBack
if (facebookPayload.PostBack != null)
{
OnFacebookPostBack(facebookPayload.PostBack);
}
// Optin
else if (facebookPayload.Optin != null)
{
OnFacebookOptin(facebookPayload.Optin);
}
// Quick reply
else if (facebookPayload.Message?.QuickReply != null)
{
OnFacebookQuickReply(facebookPayload.Message.QuickReply);
}
// TODO: Handle other events that you're interested in...
}
}
private void OnFacebookOptin(FacebookOptin optin)
{
// TODO: Your optin event handling logic here...
}
private void OnFacebookPostBack(FacebookPostback postBack)
{
// TODO: Your PostBack handling logic here...
}
private void OnFacebookQuickReply(FacebookQuickReply quickReply)
{
// TODO: Your quick reply event handling logic here...
}
}
}
I'm trying to implement the Facebook share functionality in my little xamarin iOS app. I've already downloaded the latest version of Facebook iOS SDK from nuget, but I don't know how to use it. Is there anyone who has done that already , so he can send me some normal info on that ?
Much appreciated before hands :)
I have implemented share for twitter and fb .
iOS version
you can share using native social services from ios and if not available use
OAuth2Authenticator to get access token then post using FB graph
public void ShareViaSocial(string serviceType, string urlToShare)
{
socialKind = serviceType == "Twitter" ? SLServiceKind.Twitter : SLServiceKind.Facebook;
if (SLComposeViewController.IsAvailable(socialKind))
{
_socialComposer = serviceType == "Twitter" ? SLComposeViewController.FromService(SLServiceType.Twitter) : SLComposeViewController.FromService(SLServiceType.Facebook);
_socialComposer.AddUrl(new Uri(urlToShare));
viewController.PresentViewController(_socialComposer, true, () =>
{
_socialComposer.CompletionHandler += (result) =>
{
Device.BeginInvokeOnMainThread(() =>
{
viewController.DismissViewController(true, null);
if (result == SLComposeViewControllerResult.Done)
{ OnShare(this, ShareStatus.Successful); }
else
{ OnShare(this, ShareStatus.NotSuccessful); }
});
};
});
}
//If user doest have fb app and no credential for social services we use fb graph
else if (socialKind == SLServiceKind.Facebook)
{
var auth = new OAuth2Authenticator(
clientId: SharedConstants.FacebookLiveClientId,
scope: SharedConstants.FacebookScopes,
authorizeUrl: new Uri(SharedConstants.FacebookAuthorizeUrl),
redirectUrl: new Uri(SharedConstants.FacebookRedirectUrl));
viewController.PresentViewController((UIViewController)auth.GetUI(), true, null);
auth.AllowCancel = true;
auth.Completed += (s, e) =>
{
//hide the webpage after completed login
viewController.DismissViewController(true, null);
// We presented the UI, so it's up to us to dimiss it on iOS.
if (e.IsAuthenticated)
{
Account fbAccount = e.Account;
Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "link", urlToShare } };
var requestUrl = new Uri("https://graph.facebook.com/me/feed");
var request = new OAuth2Request(SharedConstants.requestMethodPOST, requestUrl, dictionaryParameters, fbAccount);
request.GetResponseAsync().ContinueWith(this.requestResult);
}
else { OnShare(this, ShareStatus.NotSuccessful); }
};
auth.Error += Auth_Error;
}
//If user doest have twitter app and no credential for social services we use xanarub auth for token and call twitter api for sending tweets
else
{
var auth = new OAuth1Authenticator(
SharedConstants.TwitterConsumerKey,
SharedConstants.TwitterConsumerSecret,
new Uri(SharedConstants.TwitterRequestUrl),
new Uri(SharedConstants.TwitterAuth),
new Uri(SharedConstants.TwitterAccessToken),
new Uri(SharedConstants.TwitterCallBackUrl));
auth.AllowCancel = true;
// auth.ShowUIErrors = false;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += (s, e) =>
{
// We presented the UI, so it's up to us to dismiss it.
viewController.DismissViewController(true, null);
if (e.IsAuthenticated)
{
Account twitterAccount = e.Account;
Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "status", urlToShare } };
var request = new OAuth1Request(SharedConstants.requestMethodPOST, new Uri("https://api.twitter.com/1.1/statuses/update.json"), dictionaryParameters, twitterAccount);
//for testing var request = new OAuth1Request("GET",new Uri("https://api.twitter.com/1.1/account/verify_credentials.json "),null, twitterAccount);
request.GetResponseAsync().ContinueWith(this.requestResult);
}
else { OnShare(this, ShareStatus.NotSuccessful); }
};
auth.Error += Auth_Error;
//auth.IsUsingNativeUI = true;
viewController.PresentViewController((UIViewController)auth.GetUI(), true, null);
}
}
Hi I am creating an application where I used ajax request to populate the List of Items.
It works in PC-Browser but not works in iPhone safari.
What could be the issue in safari? Please Help.
createXMLHTTPHandle:function(url,onSuccess,onError){
var xhttp;
try {
if(window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", url, false);
xhttp.setRequestHeader("Content-Type",
"text/xml;charset=utf-8");
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4) {
if(xhttp.status == 200)//clear db and parse
and store new data
{
onSuccess(xhttp.responseText);
}
}
};
xhttp.send();
}
catch(err) {//
if(err=="Error: NETWORK_ERR: XMLHttpRequest Exception 101")
alert("Please check your network connection!");
onError(err);
}
}
I've looked around on SO to see if this has been asked before and couldn't find anything (so if it has indeed been asked before then I apologize.
Here's what I'm trying to do, a user can select from a list of skills for their profile, if a skill they want isn't in the list then they can add it to the database, I have that accomplished with WCF & jQuery AJAX. Here's the code for that:
$("#AddNewSkill").click(function () {
$("#AddNewSkill").attr("disabled", true);
$("#newSkill").attr("disabled", true);
var newSkill = $("#newSkill").val();
var data = { name: $("#newSkill").val(), description: "", type: "Skill" };
data = JSON.stringify(data)
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../WeddingPhotographerService.svc/AddNew",
data: data,
dataType: "json",
success: function () {
successCall('#newSkill', '#AddNewSkill');
//$('#SkillListViewContainer').load('../Account/GetSkillControl');
},
error: function (msg) {
$("#AddSkillError").text(msg.d);
$("#AddSkill").attr("disabled", false);
$("#NewSkill").attr("disabled", false);
}
});
});
Here's the method in the AJAX-Enabled WCF service:
[OperationContract]
public bool AddNew(string name, string description, string type)
{
switch (type)
{
case "":
goto default;
case "skill":
IRepository<Skill> skillRepo = ObjectFactory.GetInstance<IRepository<Skill>>();
var skill = new Skill { Name = name, Description = (string.IsNullOrEmpty(description)) ? string.Empty : description };
skillRepo.Save(skill);
return true;
case "equipment":
IRepository<Equipment> eqRep = ObjectFactory.GetInstance<IRepository<Equipment>>();
var eq = new Equipment { Name = name, Description = (string.IsNullOrEmpty(description)) ? string.Empty : description };
eqRep.Save(eq);
return true;
case "occasion":
IRepository<Occassion> occRepo = ObjectFactory.GetInstance<IRepository<Occassion>>();
var oc = new Occassion { Name = name, Description = (string.IsNullOrEmpty(description)) ? string.Empty : description };
occRepo.Save(oc);
return true;
default:
IRepository<Skill> repo = ObjectFactory.GetInstance<IRepository<Skill>>();
var s = new Skill { Name = name, Description = (string.IsNullOrEmpty(description)) ? string.Empty : description };
repo.Save(s);
return true;
}
}
It's kind of ugly but I'll optimize it once I have this 2nd part working. Here's how the ListBox is being loaded in the view:
<%: Html.ListBox("Skills", Model.SkillList, new { #style = "width:157px; height:90px;background:#e2f0f1;", #size = "3", #class = "inputbox" })%>
Which comes from RegistrationModelView.cs, here's SkillList in my model view:
private MultiSelectList GetSkills(string[] selectedValues)
{
List<Skill> list = new List<Skill>();
IRepository<Skill> skills = ObjectFactory.GetInstance<IRepository<Skill>>();
foreach (Skill skill in skills.GetAll())
{
list.Add(new Skill()
{
Key = skill.Key,
Name = skill.Name,
Description = ""
});
}
return new MultiSelectList(list, "Key", "Name", selectedValues);
}
And the action in AccountController.cs that loads the view
[MoveFormsScript]
public ActionResult Index()
{
return View(new RegistrationModelView());
}
I'm pretty sure all the code I posted (other than how the new item is added with the WCF service and the jQuery for consuming said service is irrelevant but I thought I'd offer as much information as possible).
Like I said the new value is added to the database no problem, my issue is updating the ListBox to reflect the new values. Anyone got any ideas and can help with this?
Well I mucked around until I found something that does what I need it to do. It may not be the most efficient or elegant way to accomplish the task but it at least works (Maybe someone will come along with a different solution some day).
What I ended up doing was make another $,ajax() call in the success of the first call like this
$("#AddNewSkill").click(function () {
$("#AddNewSkill").attr("disabled", true);
$("#newSkill").attr("disabled", true);
var data = { name: $("#newSkill").val(), description: "", type: "skill" };
data = JSON.stringify(data)
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../WeddingPhotographerService.svc/AddNew",
data: data,
dataType: "json",
success: function () {
$.ajax({
type:"POST",
datatype:"json",
url: "../Account/GetSkills",
success:updateSkillsListBox
});
},
error: function (msg) {
alert(msg.d);
}
});
});
function updateSkillsListBox(data, status) {
$("#Skills").html("");
for(var d in data) {
$("<option value=\"" + data[d].Value + "\">" + data[d].Name + "</option>").appendTo("#Skills");
}