AS3 API: Deleting App Invites - facebook-graph-api

I'm using the ActionScript-Facebook API for my project. Facebook now leaves it up to us to delete app invites once they are used.
In their documentation, they have a JavaScript snippet to do what I need to do:
FB.api(requestId, 'delete', function(response) {console.log(response);});
Cool. The AS3 API call is like such:
Facebook.api(referID, callback, "POST");
For the life of me, I'm not sure how to work this. I've tried:
Facebook.api(referID, function(){trace("callback");}, "delete");
Facebook.api(referID, function(){trace("callback");});
Facebook.api(referID, {access_token:accessTokenString}, "delete");
Here's the documentation:
https://developers.facebook.com/docs/reference/dialogs/requests/#deleting

The following worked for removal of application requests:
var full_request_id : String = request_id + "_" + user_id;
var method : String = "/" + full_request_id;
Facebook.deleteObject(method, callback);
#see AbstractFacebook.as
The actionscript-api will then add the property 'method' with value 'delete' to the parameters of your call:
protected function deleteObject(method:String, callback:Function = null):void {
var params:Object = {method:'delete'};
api(method, callback, params, URLRequestMethod.POST);
}
if (params.access_token == null) { params.access_token = accessToken; }

Related

Can not pass a list of strings to a Web API endpoint. Why?

Can not pass a list of strings to a Web API endpoint. Why?
Here is my controller:
[Route("[controller]")]
[ApiController]
public class MyController
{
[HttpPost("foo")]
public string MyMethod(List<string> strs)
{
return "foo";
}
}
Here is how I am trying to call it:
var strs = new List<string> { "bar" };
var json = JsonConvert.SerializeObject(strs);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpCliet.PostAsync("/My/foo", content);
Before calling the endpoint I place a breakpoint on the return "foo"; line. Once the breakpoint is hit the strs list inside the MyController.MyMethod is empty. The strs is not null, but it contains no elements. While my intentions and expectations are to see the strs containing one element, i.e. the string "bar".
I am using the ASP.NET Core 2.2 in project where I create and use the HttpClient. And I am using the same ASP.NET Core 2.2 in project where I have the endpoint.
I am not sure what is wrong here. I have checked a few sources. E.g. the following:
C# HTTP post , how to post with List<XX> parameter?
https://carldesouza.com/httpclient-getasync-postasync-sendasync-c/
https://blog.jayway.com/2012/03/13/httpclient-makes-get-and-post-very-simple/
And I can not find what I am missing according to those resources.
UPDATE
The following call works for me as expected:
var json = JsonConvert.SerializeObject(string.Empty);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await server.CreateClient().PostAsync("/My/foo?strs=bar", content);
Maybe someone knows why the parameters in my case are read from the query string only, but not from body?
You can change your url to a full url in client.PostAsync.Here is a demo worked:
Api(localhost:44379):
WeatherForecastController:
[HttpPost("foo")]
public string MyMethod(List<string> strs)
{
return "foo";
}
Call(localhost:44326):
public async Task<IActionResult> CheckAsync() {
HttpClient client = new HttpClient();
var strs = new List<string> { "bar","bar1","bar2" };
var json = JsonConvert.SerializeObject(strs);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://localhost:44379/WeatherForecast/foo", content);
return Ok(response);
}
result:

Sharepoint: How to show AppendOnlyHistory on a display template in a cross-publishing scenario

The overarching requirement I am trying to implement is to show comments (made on a list, item by item basis).
I added the feature on the authoring side by enabling versioning on the list and adding a text field with the option "Append Changes to Existing Text" set to true.
This indeed allows me to comment on items and displays them chronologically, but on the authoring side only.
The issue is that the UI part will be done on another site collection and I can't find a straightforward way to get all comments there.
So far, every resource I have found points to
<SharePoint:AppendOnlyHistory runat="server" FieldName="YourCommentsFieldName" ControlMode="Display"/>
The thing is, I can't (don't know how to) use this inside a display template.
So far, I am getting all my data using the REST API, via
var siteUrl=_spPageContextInfo.webAbsoluteUrl.replace("publishing","authoring");
$.ajax({
url: siteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
type: 'GET',
async:false,
headers: {"accept": "application/json;odata=verbose",},
dataType: 'JSON',
success: function(json) {
console.log(json);
//var obj = $.parseJSON(JSON.stringify(json.d.results));
//alert(obj);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error :"+XMLHttpRequest.responseText);
}
});
What this gives me is the latest comment only. I need a simple way to get a hold of the entire thread.
I ended up using javascript object model to get them like so:
function GetComments(listname, itemId) {
var siteUrl = _spPageContextInfo.webAbsoluteUrl.replace("publishing", "authoring");
if ($(".comments-history").length) {
$().SPServices({
operation: "GetVersionCollection",
async: false,
webURL: siteUrl,
strlistID: listname,
strlistItemID: itemId,
strFieldName: "Comments",
completefunc: function (xData, Status) {
$(xData.responseText).find("Version").each(function (data, i) {
var xmlComment = $(this)[0].outerHTML;
var arr = xmlComment.split(/comments|modified|editor/g);
var comment = arr[1].trim().substring(2, arr[1].length-2);
var dateSt = Date.parse((arr[2].substring(1, arr[2].length)).replace('/"', ''));
var user = getUsername(arr[3]);
var st = "<div class='comment-item'><div class='comment-user'>" + user + "(" + FormatDate(dateSt) + ")</div>";
st += "<div class='comment-text'>" + comment + "</div></div>";
$(".comments-history").append(st);
});
}
});
}
}
the parsing could be better, but this is just an initial working idea

In Sharepoint how to get list advanced settings for Opening Documents in the Browser using REST API

Using REST API i want to access this
Settings >> Advanced Settings >> Opening Documents in the Browser
Can anybody know about this?
Thanks
In SSOM this feature corresponds to SPList.DefaultItemOpen property:
Gets or sets a value that specifies whether to open list items in a
client application or in the browser.
In REST/CSOM this property is not exposed but it could be extracted and determined via List schema Xml. For more details about this approach follow this post.
Example
The following example demonstrates how to determine whether to open list items in a client application or in the browser using REST API:
function schemaXml2Json(schemaXml)
{
var jsonObject = {};
var schemaXmlDoc = $.parseXML(schemaXml);
$(schemaXmlDoc).find('List').each(function() {
$.each(this.attributes, function(i, attr){
jsonObject[attr.name] = attr.value;
});
});
return jsonObject;
}
function getDefaultItemOpen(webUrl,listTitle)
{
var endpointUrl = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')?$select=schemaXml";
return $.getJSON(endpointUrl).then(function(data){
var listProperties = schemaXml2Json(data.SchemaXml);
var flags = parseInt(listProperties.Flags);
var defaultItemOpen = (flags & 268435456) != 0 ? "Browser" : "PreferClient";
return defaultItemOpen;
});
}
Usage
getDefaultItemOpen(_spPageContextInfo.webAbsoluteUrl,'Documents')
.done(function(value){
console.log('DefaultItemOpen: ' + value);
});

How to embed latest tweets in Sitecore 6.5

I have to embed latest tweets in a Sitecore 6.5 project as given below image
How can I implement this functionality.
Thanks
Hello You can do this See below code. I am pasting code here for a single sublayout. Please update some tokens as per your requirement. This code will return you a Json you can get that json in JQuery.
Code - ----------------
public partial class LatestTweets : BaseSublayout
{
SiteItem objSiteItem = SiteItem.GetSiteRoot();
protected void Page_Load(object sender, EventArgs e)
{
if (objSiteItem != null)
{
hdJsonData.Value = GetTweets();
frLatestTweets.Item = objSiteItem;
frLatestTweets.Item = objSiteItem;
frFollowUsLink.Item = objSiteItem;
ltFollowUs.Text = Sitecore.Globalization.Translate.Text(Constants.FOLLOW_US);
ltTweetUs.Text = Sitecore.Globalization.Translate.Text(Constants.TWEET_US);
}
}
public string GetTweets()
{
// oauth application keys
var oauth_token = objSiteItem.AccessToken.Rendered;
var oauth_token_secret = objSiteItem.AccessTokenSecret.Rendered;
var oauth_consumer_key = objSiteItem.ConsumerKey.Rendered;
var oauth_consumer_secret = objSiteItem.ConsumerSecret.Rendered;
var screen_name = objSiteItem.TwitterUser.Rendered;
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// unique request details
var oauth_nonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
// message api details
var status = "Updating status via REST API if this works";
var resource_url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
// create oauth signature
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version,
Uri.EscapeDataString(screen_name)
);
baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
// make the request
ServicePointManager.Expect100Continue = false;
var postBody = "screen_name=" + Uri.EscapeDataString(screen_name);//
resource_url += "?" + postBody;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseData;
}
}
Just as you would add it into any website... create a component for it and use the twitter API like this for example: http://jsfiddle.net/abenlumley/xRwam/4/
/*********************************************************************
#### Twitter Post Fetcher! ####
Coded by Jason Mayes 2013.
www.jasonmayes.com
Please keep this disclaimer with my code if you use it. Thanks. :-)
Got feedback or questions, ask here: http://goo.gl/JinwJ
Ammended by Ben Lumley and djb31st 2013
www.dijitul.com
Ammended to display latest tweet only with links
********************************************************************/
var twitterFetcher=function(){var d=null;return{fetch:function(a,b){d=b;var c=document.createElement("script");c.type="text/javascript";c.src="http://cdn.syndication.twimg.com/widgets/timelines/"+a+"?&lang=en&callback=twitterFetcher.callback&suppress_response_codes=true&rnd="+Math.random();document.getElementsByTagName("head")[0].appendChild(c)},callback:function(a){var b=document.createElement("div");b.innerHTML=a.body;a=b.getElementsByClassName("e-entry-title");d(a)}}}();
/*
* ### HOW TO USE: ###
* Create an ID:
* Go to www.twitter.com and sign in as normal, go to your settings page.
* Go to "Widgets" on the left hand side.
* Create a new widget for "user timeline". Feel free to check "exclude replies"
* if you dont want replies in results.
* Now go back to settings page, and then go back to widgets page, you should
* see the widget you just created. Click edit.
* Now look at the URL in your web browser, you will see a long number like this:
* 345735908357048478
* Use this as your ID below instead!
*/
twitterFetcher.fetch('345190342812909568', function(tweets){
// Do what you want with your tweets here! For example:
var x = tweets.length;
var n = 0;
var element = document.getElementById('tweets');
var html = '<ul>';
if (tweets[n].innerHTML) {
html += '<li>' + tweets[n].innerHTML + '</li>';
} else {
html += '<li>' + tweets[n].textContent + '</li>';
}
n++;
html += '</ul>';
element.innerHTML = html;
});
As #IvanL said, you will simply want to create a sublayout and add the markup/JS/etc as you normally would. Below, I describe an easy-to-use library that will help you to get your Tweets via Twitter's API and also a jQuery plugin that will help simplify the way you render them. All you would need to do is wire up the library, make the necessary C# call, and then use the jQuery plugin to help you render the Tweets, using the markup style that you specify.
As mentioned below, note that I originally wrote both the library and the jQuery plugin for integration with a Sitecore 6.5 environment, and made them flexible enough to use with any solution.
Getting and Rendering Tweets
I created a C# library for the Twitter API about a year ago, named TweetNET. It has MSDN style documentation, and I built it in such a way as it could be integrated into .NET applications, and the first production site that I used it on was a Sitecore 6.5 site. The documentation and examples are pretty comprehensive, but if you have any questions, feel free to let me know.
As for the actual displaying of the Tweets after getting them from Twitter, I also have another repo, Twitter Feed, which is a jQuery plugin designed to simplify rendering Tweets. Both projects include examples of the TweetNET's use, and the Twitter Feed project also includes examples of its call, so this would be a one-stop-shop for you.
TweetNET - Latest Tweets Call
TweetNET reduces the code that you need in order to get the latest Tweets for a given handle to the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TweetNET.OAuth;
using TweetNET.Requests.Timelines.Statuses;
using System.Net;
using System.IO;
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
var consumerKey = "your consumerKey";
var consumerSecret = "your consumerSecret";
var oAuthToken = "your oAuthToken";
var oAuthTokenSecret = "your oAuthTokenSecret";
var twitterHandle = "your twitter handle";
var tokens = new SecurityTokens(consumerKey, consumerSecret, oAuthToken, oAuthTokenSecret);
var utGETRequest = new UserTimelineRequest(tokens);
utGETRequest.Screen_Name = twitterHandle;
var request = utGETRequest.BuildRequest();
WebResponse response = utGETRequest.SendRequest(request);
string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
}
Twitter Feed - Rendering Tweets
$(document).ready(function () {
$("#feedTarget").twitterFeed({
count: 4,
rawData: yourRawJSONData,
prepend: "<div class='tweetWrapper'>",
append: "</div>",
tweetBodyClass: "tweetBody tweetText",
date: { prepend: "<div>", append: " - ", order: 3, cssClass: "tweetDate" },
retweet: { show: false },
favorite: { prepend: " - ", order: 0, append: "</div>" },
callbackOnEach: true,
callback: function() {
$(this).find(".tweetBody").myCallbackOnEachTweet();
}
});
});
});
To get latest tweet read following url
https://umerpasha.wordpress.com/2013/06/13/c-code-to-get-latest-tweets-using-twitter-api-1-1/

Firefox Add-On to redirect urls based on wildcards

I am looking at writing a firefox extension which will take a url, apply a regex to it to produce a second url.
I then need to have firefox redirect to this new URL without the user having to do anyything.
Does anyone have any examples I could use to learn how to do this. I've used the firefox tutorials to get as far as this..
// Import the page-mod API
var pageMod = require("sdk/page-mod");
// Import the self API
var self = require("sdk/self");
// Create a page mod
// It will run a script whenever a ".org" URL is loaded
// The script replaces the page contents with a message
pageMod.PageMod({
include: "*",
contentScript: 'window.alert("Matched Page");'
})
So my question is, how would I do this.
For instance, if a user types in http://www.mywebsite/data/7287232/wherever, I'd like them to be redirected to http://www.anotherwebsite/folder/7287232
Well.. answering to the initial head line:
https://addons.mozilla.org/en-US/firefox/addon/redirector
Or is that actually you? #ScaryAardvark ?
that example is very complex, the main purpose of that traceable channel example is to get a COPY of the sourcecode that gets loaded at that uri.
const { Ci, Cu, Cc, Cr } = require('chrome'); //const {interfaces: Ci, utils: Cu, classes: Cc, results: Cr } = Components;
Cu.import('resource://gre/modules/Services.jsm');
Cu.import('resource://gre/modules/devtools/Console.jsm');
var observers = {
'http-on-modify-request': {
observe: function (aSubject, aTopic, aData) {
console.info('http-on-modify-request: aSubject = ' + aSubject + ' | aTopic = ' + aTopic + ' | aData = ' + aData);
var httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
var requestUrl = httpChannel.URI.spec
if (/\.org/.test(requestUrl) || /http\:\/\/www\.mywebsite\/data\/7287232\/.+/.test(requestUrl)) {
httpChannel.redirectTo(Services.io.newURI('http://www.anotherwebsite/folder/7287232', null, null));
}
},
reg: function () {
Services.obs.addObserver(observers['http-on-modify-request'], 'http-on-modify-request', false);
},
unreg: function () {
Services.obs.removeObserver(observers['http-on-modify-request'], 'http-on-modify-request');
}
}
};
to register the observer on startup of addon run this:
//register all observers
for (var o in observers) {
observers[o].reg();
}
and on shutdown of addon unregister all observers like this:
//unregister all observers
for (var o in observers) {
observers[o].unreg();
}