How to use LinqToTwitter in UAP? - linq-to-twitter

I started to try using Linq to Twitter library to query some twitter data. I have a following function:
public static async Task<List<Status>> GetTweets(TwitterContext context, string searchQuery, int count = 15)
{
var searchResult = await
(from search in context.Search
where search.Type == SearchType.Search &&
search.Query == searchQuery &&
search.IncludeEntities == true &&
search.Count == count
select search)
.SingleOrDefaultAsync();
return searchResult.Statuses;
}
And the function in a console application I created to call this function looks like this:
IAuthorizer authorizer = new ApplicationOnlyAuthorizer
{
CredentialStore = new InMemoryCredentialStore
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
}
};
authorizer.AuthorizeAsync().Wait();
TwitterContext context = new TwitterContext(authorizer);
List<Status> statuses = GetTweets(context, "#hashtag", 50).Result;
This works perfectly. However, if I migrate this into a universal windows app, then it hangs at List<Status> statuses = GetTweets(context, "#hashtag", 50).Result; forever. No exception occurs, nothing shows up, nothing returns. Am I using it wrong?

Versions of LINQ to Twitter v3.x and earlier won't work with UAP apps. They'll produce the same behavior that you're experiencing now. You must upgrade to the latest version, which is in pre-release.
Here's the pre-release version of LINQ to Twitter, v4.0. It's main purpose is to include support for UAP, in addition to other technologies:
http://www.nuget.org/packages/linqtotwitter/4.0.0-beta2

Related

Having trouble returning Javascript Object Selenium C#

So basically what I am trying to do is setup a proxy to intercept my call to a website and put a script tag in the header to catch javascript bugs using fiddler's proxy library. Which looks like this:
<script>
window.__webdriver_javascript_errors = [];
window.onerror = function(errorMsg, url, line)
{ window.__webdriver_javascript_errors.push(errorMsg + ' (found at ' + url + ', line ' + line + ')'); };
</script>
That all works great and it is catching bugs before the page loads. My issue is when I go to the page I can't actually return the javascript object from the page.
public static IList<string> GetJavaScriptErrors(IWebDriver driver, TimeSpan timeout)
{
string errorRetrievalScript = "var errorList = window.__webdriver_javascript_errors; window.__webdriver_javascript_errors = []; return errorList;";
DateTime endTime = DateTime.Now.Add(timeout);
List<string> errorList = new List<string>();
IJavaScriptExecutor executor = driver as IJavaScriptExecutor;
List<object> returnedList = executor.ExecuteScript(errorRetrievalScript) as List<object>;
while (returnedList == null && DateTime.Now < endTime)
{
System.Threading.Thread.Sleep(250);
returnedList = executor.ExecuteScript(errorRetrievalScript) as List<object>;
}
if (returnedList == null)
{
return null;
}
else
{
foreach (object returnedError in returnedList)
{
errorList.Add(returnedError.ToString());
}
}
return errorList;
}
Now when I run this, my returnedList never ever gets the errorRetrievalScript returned to it. I cannot seem to figure out why I always get null returned.
The weirdness is, before I run the executor for javascript if I go to Firefox and type in
window.__webdriver_javascript_errors
All the errors show up just fine, but the second I hit that executor the errors vanish, which is what I want to happen, and that works! But the return never returns anything.
What am i doing wrong?
EDIT:
The selenium, and browsers versions I am using are:
Firefox: 47.0.1
Chrome: 51.0.2704.103
IE: 11.420.10586.0
Selenium: 2.53.1

Oauth 2 popup with Angular 2

I'm upgrading/rewriting an existing angular app to use angular2. My problem is that I want to open a OAuth flow in a new pop up window and once the OAuth flow is completed use window.postMessage to communicate back to the angular 2 app that the OAuth flow was successful.
Currently what I have is in the angular 2 service is
export class ApiService {
constructor(private _loggedInService: LoggedInService) {
window.addEventListener('message', this.onPostMessage, false);
}
startOAuthFlow() {
var options = 'left=100,top=10,width=400,height=500';
window.open('http://site/connect-auth', , options);
}
onPostMessage(event) {
if(event.data.status === "200") {
// Use an EventEmitter to notify the other components that user logged in
this._loggedInService.Stream.emit(null);
}
}
}
This template that is loaded at the end of the OAuth flow
<html>
<head>
<title>OAuth callback</title>
<script>
var POST_ORIGIN_URI = 'localhost:8000';
var message = {"status": "200", "jwt":"2"};
window.opener.postMessage(message, POST_ORIGIN_URI);
window.close();
</script>
</head>
</html>
Using window.addEventListener like this seems to completely break the angular 2 app, dereferencing this.
So my question is can I use window.addEventListener or should I not use postMessage to communicate back to the angular2 app?
** Complete angular2 noob so any help is appreciated
I have a complete Angular2 OAuth2 skeleton application on Github that you can refer to.
It makes use of an Auth service for OAuth2 Implicit grants that in turn uses a Window service to create the popup window. It then monitors that window for the access token on the URL.
You can access the demo OAuth2 Angular code (with Webpack) here.
Here is the login routine from the Auth service, which will give you an idea of what's going on without having to look at the entire project. I've added a few extra comments in there for you.
public doLogin() {
var loopCount = this.loopCount;
this.windowHandle = this.windows.createWindow(this.oAuthTokenUrl, 'OAuth2 Login');
this.intervalId = setInterval(() => {
if (loopCount-- < 0) { // if we get below 0, it's a timeout and we close the window
clearInterval(this.intervalId);
this.emitAuthStatus(false);
this.windowHandle.close();
} else { // otherwise we check the URL of the window
var href:string;
try {
href = this.windowHandle.location.href;
} catch (e) {
//console.log('Error:', e);
}
if (href != null) { // if the URL is not null
var re = /access_token=(.*)/;
var found = href.match(re);
if (found) { // and if the URL has an access token then process the URL for access token and expiration time
console.log("Callback URL:", href);
clearInterval(this.intervalId);
var parsed = this.parse(href.substr(this.oAuthCallbackUrl.length + 1));
var expiresSeconds = Number(parsed.expires_in) || 1800;
this.token = parsed.access_token;
if (this.token) {
this.authenticated = true;
}
this.startExpiresTimer(expiresSeconds);
this.expires = new Date();
this.expires = this.expires.setSeconds(this.expires.getSeconds() + expiresSeconds);
this.windowHandle.close();
this.emitAuthStatus(true);
this.fetchUserInfo();
}
}
}
}, this.intervalLength);
}
Feel free to ask if you have any questions or problems getting the app up and running.
So with a bit of investigation found out the problem. I was de-referencing this. This github wiki helped me understand it a bit more.
To solve it for my case needed to do a couple of things. Firstly I created a service that encapsulated the adding of an eventListener
import {BrowserDomAdapter} from 'angular2/platform/browser';
export class PostMessageService {
dom = new BrowserDomAdapter();
addPostMessageListener(fn: EventListener): void {
this.dom.getGlobalEventTarget('window').addEventListener('message', fn,false)
}
}
Then using this addPostMessageListener I can attach a function in my other service to fire
constructor(public _postMessageService: PostMessageService,
public _router: Router) {
// Set up a Post Message Listener
this._postMessageService.addPostMessageListener((event) =>
this.onPostMessage(event)); // This is the important as it means I keep the reference to this
}
Then it works how I expected keeping the reference to this
I think this is the Angular2 way:
(Dart code but TS should be quite similar)
#Injectable()
class SomeService {
DomAdapter dom;
SomeService(this.dom) {
dom.getGlobalEventTarget('window').addEventListener("message", fn, false);
}
}
I fiddled around with this for ages but in the end, the most robust way for me was to redirect the user to the oath page
window.location.href = '/auth/logintwitter';
do the oath dance in the backend (I used express) and then redirect back to a receiving front end page...
res.redirect(`/#/account/twitterReturn?userName=${userName}&token=${token}`);
There are some idiosyncracies to my solution because e.g. I wanted to use only JsonWebToken on the client regardless of login type, but if you are interested, whole solution is here.
https://github.com/JavascriptMick/learntree.org

arr.splice(begin, until) - What am I doing wrong?

Here's my basic setup (javascript, of course):
var bookmark = {
...
deleteBookmark: function(_id) {
var oldbookmarks = this.readBookmarks();
var begin = oldbookmarks.indexOf(_id);
if (begin > -1) {
var newbookmarks = oldbookmarks.splice(begin, 1);
localStorageService.set('bookmarks', newbookmarks);
}
},
...
};
Note: this worked perfectly until today. Suddenly, newbookmarks isn't the difference, it's an array containing only the bookmark id from _id.
Environment:
Browser: Latest Chrome, Firefox
Server: Node 0.12.2 via Express
Framework: AngularJS, Yeoman, Angular-Fullstack Generator
Oh, wait. In the process of writing the question, I did some research and found out that the people who wrote the spec for this might have been idiots. It's because the splice method returns the deleted element from the array - meaning it's an operator, not a function.
The corrected usage from above would be:
var bookmark = {
...
deleteBookmark: function(_id) {
var oldbookmarks = this.readBookmarks();
var begin = oldbookmarks.indexOf(_id);
if (begin > -1) {
oldbookmarks.splice(begin, 1);
localStorageService.set('bookmarks', oldbookmarks);
}
},
...
};

Message Passing From firefox extension to mac app

I have a mac app which receives broadcast distributed notification messages
with code
NSDistributedNotificationCenter.defaultCenter().addObserver(sender, selector: "testaction:", name: "myNoti", object: nil)
i also have developed firefox extension using Addon SDK
I knows their is javascript - Objc bridge
in which we can import system Frameworks and write objective c code in firefox extension javascript code .
but I tried adding
Components.utils.import("/path/to/macosx.js");
then
include("macosx.js")
etc but nothing worked for me attached is the code link : : https://drive.google.com/file/d/0B9ioid0ZPVpaaHBqRzdEV2tGUjg/view?usp=sharing
Can anybody knows how can i pass message from firefox extension to mac app using anything
DistributedNotification seems good and Ok for me using macosx.js but it not working for me
Thanks
Added js-ctypes tag. Join moz irc js-ctypes for more help, I would actually love to chat with you about it, join here: https://client00.chat.mibbit.com/?url=irc%3A%2F%2Firc.mozilla.org%2F%23jsctypes or here irc://moznet/jsctypes . Awesome work you're doing here.
I'm not going to do this with ObjC Bridge because that has a TON of abstraction. You won't understand the fundamentals needed to run that. So start with no abstraction then later you can move into the abstracted if you want, otherwise troubleshooting will be a headache.
This is how you post a message with postNotification:object, try this code, I tested it, it ran without error, but I didn't set up an observer so didn't test if it actually worked. It just doesn't crash :P
Cu.import('resource://gre/modules/ctypes.jsm');
var objc = ctypes.open(ctypes.libraryName('objc'));
// BASIC TYPES
var BOOL = ctypes.signed_char;
var CHAR = ctypes.char;
var ID = ctypes.voidptr_t;
var SEL = ctypes.voidptr_t;
var VOID = ctypes.void_t;
// CONSTANTS
var NIL_ID = ctypes.cast(ctypes.uint64_t(0), ID);
var YES = BOOL(1);
var NO = BOOL(0);
// COMMON FUNCTIONS
var objc_getClass = objc.declare('objc_getClass', ctypes.default_abi, ID, CHAR.ptr);
var objc_msgSend = objc.declare('objc_msgSend', ctypes.default_abi, ID, ID, SEL, '...');
var sel_registerName = objc.declare('sel_registerName', ctypes.default_abi, SEL, CHAR.ptr);
// COMMON SELECTORS
var alloc = sel_registerName('alloc');
var init = sel_registerName('init');
var release = sel_registerName('release');
var shutdown = function() {
if (NSString_myNoti) {
console.log('releasing NSString_myNoti');
objc_msgSend(NSString_myNoti, release);
}
objc.close();
console.log('succesfully shutdown');
}
// my globals:
var NSString_myNoti;
function main() {
// default_center = [NSDistributedNotificationCenter defaultCenter];
var NSDistributedNotificationCenter = objc_getClass('NSDistributedNotificationCenter');
var defaultCenter = sel_registerName('defaultCenter');
var default_center = objc_msgSend(NSDistributedNotificationCenter, defaultCenter);
console.info('default_center:', default_center, default_center.toString(), uneval(default_center), default_center.isNull());
var NSString = objc_getClass('NSString');
var initWithUTF8String = sel_registerName('initWithUTF8String:');
NSString_myNoti = objc_msgSend(objc_msgSend(NSString, alloc), initWithUTF8String, CHAR.array()('myNoti'));
console.info('NSString_myNoti:', NSString_myNoti, NSString_myNoti.toString(), uneval(NSString_myNoti));
// postNotificationName:object:userInfo:deliverImmediately:
var postNotificationNameObject = sel_registerName('postNotificationName:object:');
var rez_postNotificationName = objc_msgSend(default_center, postNotificationNameObject, NSString_myNoti, NIL_ID); // returns void
//docs say rez_postNotificationName is VOID
console.log(postNotificationNameObject.toString(), postNotificationNameObject.toString() == YES.toString()); //its always returning 0x0 which iS NO, but its sending, 0x0 is VOID proabably i dont know, but i guess this matches the documentation
}
try {
main();
} catch (ex) {
console.error('Error Occured:', ex);
} finally {
shutdown();
}
EDIT
verified the code above works, i tested by adding observer for myNotif also with jsctypes, the addObserver:selector:name:object code is linked from the README. and also in this example i used postNotification:notificationName:object:userInfo:deliverImmediatey so this shows that as an added bonus: GitHubGIST :: Noitidart / _ff-addon-snippet-ObjC-postNotificationNameObjectUserInfoDeliverImmediately

Sammyjs routes not working with Phonegap

I have built an app with SammyJs. It currently works perfectly in the browser. However, when I package it to Android using PhoneGap, the routes does not work anymore.
I have found this SO question. However, the solution given does not work :
(function($) {
var app = $.sammy('[role=main]', function() {
this.disable_push_state = true;
...
});
}
Has anyone ever experienced the same issue?
EDIT
I am also using jquery mobile with the following script to disable its routing :
<script type="text/javascript">
// DISABLE JQM ROUTER
$(document).bind("mobileinit", function () {
$.mobile.ajaxEnabled = false;
$.mobile.linkBindingEnabled = false;
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
$.mobile.changePage.defaults.changeHash = false;
});
</script>
I created a gist with my app sammy javascript (including routes).
I think the problem is with this around clause:
this.around(function(callback) {
var context = this;
url = 'http://localhost:3000/api.json?school=' + localStorage.school
this.load(url)
.then(function(data) {
parsed = JSON.parse(data);
//if (parsed.meta != undefined) {
// alert(parsed.meta.message);
//}
context.products = parsed.products;
context.places = parsed.places;
context.school = parsed.school;
context.title = $('[data-role=header] h1');
})
.then(callback); // *** this won't get called if load() rejects promise
});
As I understand it, the around clause is called with a callback(), which will continue loading the route when it is called.
I think there is a problem with your promise chain. If load() returns a rejected promise (which probably does, as there is no localhost:3000 on your phone), then neither of your then() functions will load. As such, callback() isn't called and the app "stops". I would advise (a) adding some error handling there, so you can see what it happening, and definitely (b) executing callback no matter the result of load(). Also - JSON.parse(data) will throw an error if data is not a proper JSON-encoded string - you want a try/catch around that, too.
I would try this:
this.load(url)
.then(function(data) {
try {
parsed = JSON.parse(data);
} catch(e) {
console.log('error decoding json!: '+errorMsg);
}
//if (parsed.meta != undefined) {
// alert(parsed.meta.message);
//}
context.products = parsed.products;
context.places = parsed.places;
context.school = parsed.school;
context.title = $('[data-role=header] h1');
},function(errorMsg){
console.log('error loading json!: '+errorMsg);
})
.fin(callback); // *** fin() is meant to execute on both success and error, like a "finally".
If your promises implementation does not support fin(), look up what it is calling its equivalent. It is essentially shorthand for: .then(callback).otherwise(callback)
Long story short - you want to make sure that the callback passed to around will be executed no matter what, or you app will not continue loading the route, which is what your unexpected behaviour seems to be.
As for the point about not being able to see the console, I am not sure what your environment looks like, but I have had success with Eclipse and ADT in the past - I can see console logs and errors just fine.

Resources