sharePoint online count unread message from office365 - javascript

As part of a project whose aim is to notably improve the visual side of a SharePoint Online site, I'm a bit stuck. On the home page in the left banner, users want to see the number of unread messages they have in Office365.
I created an area in the master page to put the result in. I thought the Rest API used to do this :
$.ajax ({
type: "GET",
url: " https://outlook.office365.com/ews/odata/Me/Folders/Inbox",
dataType : "json",
success : function (resp) {
// count unread messages
},
error : function (e) {
alert (' Error121212 :' + JSON.stringify (e));
}
})
Unfortunately I get an error like cross domain. I tried with JSONP but it does not work either (uncaught syntax error unexpected token).
Can you please tell me if this is a good practice? I feel that it anyways I must find a technic for authentication. (In the case of JSONP I have a popup that asks me authentication and then problem occurs on callback apparently)...
I want to avoid developing a type requiring a typical deployment Wsp...
Thank you in advance for your help.

Your URL for the ajax request seems incorrect. The URL for getting the inbox messages via the API is: https://outlook.office365.com/api/v1.0/me/folders/inbox/messages
Once you get the response, you can count the number of objects with the IsRead property set to false using a simple for loop and display that count.

The issue here is related to CORS and how browsers refuse to handle cross-domain requests. To get around this, typically you would either
Change the response header on the remote server - not an option here
Use some sort of proxy to handle the requests - here's where SharePoint apps come in.
I know you stipulated that you want to avoid using a WSP style deployment but there simply isn't a way around it, you have to use the SharePoint App Model
This article goes a long way to answer your question, but for completion the basic steps are as follows
Create a SharePoint hosted app in Visual Studio
In the App Manifest, you need to define the trust relationship with the remote host (in this case the host of outlook.office365.com) using the AppManifest section
Use SP.RequestExecutor.executor to make the request on your behalf

Related

Fastest redirects Javascript

My main function is I am creating a link-shortening app. When someone entered a long URL, it will give a short URL. If the user clicked on the short link it will search for the long URL on the DB and redirect it to the long URL.
Meantime I want to get the click count and clicked user's OS.
I am currently using current code :
app.get('/:shortUrl', async (req, res) => {
const shortUrl = await ShortUrl.findOne({short: req.params.shortUrl})
if (shortUrl == null) return res.sendStatus(404)
res.redirect(shortUrl.full)
})
findOne is finding the Long URL on the database using ShortID. I used mongoDB here
My questions are :
Are there multiple redirect methods in JS?
Is this method work if there is a high load?
Any other methods I can use to achieve the same result?
What other facts that matter on redirect time
What is 'No Redirection Tracking'?
This is a really long question, Thanks to those who invested their time in this.
Your code is ok, the only limitation is where you run it and mongodb.
I have created apps that are analytics tracker, handling billion rows per day.
I suggest you run your node code using AWS Beanstalk APP. It has low latency and scales on your needs.
And you need to put redis between your request and mongodb, you will call mongodb only if your data is not yet in redis. Mongodb has more read limitations than a straight redis instance.
Are there multiple redirect methods in JS?
First off, there are no redirect methods in Javascript. res.redirect() is a feature of the Express http framework that runs in nodejs. This is the only method built into Express, though all a redirect response consists of is a 3xx (often 302) http response status and setting the Location header to the redirect location. You can manually code that just as well as you can use res.redirect() in Express.
You can look at the res.redirect() code in Express here.
The main things it does are set the location header with this:
this.location(address)
And set the http status (which defaults to 302) with this:
this.statusCode = status;
Then, the rest of the code has to do with handling variable arguments, handling an older design for the API and sending a body in either plain text or html (neither of which is required).
Is this method work if there is a high load?
res.redirect() works just fine at a high load. The bottleneck in your code is probably this line of code:
const shortUrl = await ShortUrl.findOne({short: req.params.shortUrl})
And, how high a scale that goes to depends upon a whole bunch of things about your database, configuration, hardware, setup, etc... You should probably just test how many request/sec of this kind your current database can handle.
Any other methods I can use to achieve the same result?
Sure there are. But, you will have to use some data store to look up the shortUrl to find the long url and you will have to create a 302 response somehow. As said earlier, the scale you can achieve will depend entirely upon your database.
What other facts that matter on redirect time
This is pretty much covered above (hint, its all about the database).
What is 'No Redirection Tracking'?
You can read about it here on MDN.

How to make a REST GET request (with authentication) and parse the result in javascript?

Due to circumstances beyond my control, Javascript is the only language option available for me. I'm a beginner and am not even sure if I'm approaching the problem in a "recommended" manner.
Simply put, a customer has setup a MarkLogicDB server online and has given me read-only access. I can query the server with the HTTP GET protocol to return an XML document that has to be parsed. I've been able to create a curl command to return the data I need (example below);
curl --anyauth --user USERNAME:PASSWORD \
-X GET \
http://test.com:8020/v1/documents?uri=/path/to/file.xml
The above returns the requested XML file. Can someone please show me how I could convert the above to javascript code? Additionally, how would I parse the data? Let's say I want to get all the info from a certain element or attribute. How can this be accomplished?
This would be trivial for me to do in Java/.NET, but after reading plenty of online tutorials on Javascript, my head is spinning. Every tutorial talks about web-browsers, but I'm doing this on a server environment (The parse.com CloudCode). There isn't any UI or HTML involved. For debugging, I just read the logs created with console.log().
https://parse.com/docs/cloud_code_guide#networking seems pretty clear, as far as it goes.
Parse.Cloud.httpRequest({
url: 'http://test.com:8020/v1/documents',
params: {
uri : '/path/to/file.xml'
},
success: function(httpResponse) {
console.log(httpResponse.text);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
}
});
But you'll also need authentication. The Parse.Cloud.httpRequest docs don't include any examples for that. If you have support with that vendor, ask the vendor about digest authentication.
If you're stuck you might try adding user and password to the httpRequest params and see what happens. It might work, if the developers of this stack followed the XMLHttpRequest convention.
Failing support from the vendor and existing functionality, you'll have to implement authentication yourself, in JavaScript. This works by generating strings that go into the request headers. These resources should help:
http://en.wikipedia.org/wiki/Digest_access_authentication
http://en.wikipedia.org/wiki/Basic_access_authentication
Basic auth is much easier to implement, but I'd recommend using digest for security reasons. If your HTTPServer doesn't support that, try to get the configuration changed.

What is the best/proper configuration? (javascript SOAP)

I need to retrieve data from a web service (via SOAP) during a nightly maintenance process on a LAMP server. This data then gets applied to a database. My research has returned many options and I think I have lost sight of the forest for the trees; partially because of the mix of client and server terms and perspectives of the articles I have read.
Initially I installed node.js and node-soap. I wrote a simple script to test functionality:
var soap = require('/usr/local/lib/node_modules/npm/node_modules/soap');
var url = "https://api.authorize.net/soap/v1/Service.asmx?WSDL";
soap.createClient(url, function(err, client)
{
if(typeof client == 'undefined')
{
console.log(err);
return;
}
console.log('created');
});
This uses a demo SOAP source and it works just fine. But when I use the actual URL I get a 5023 error:
[Error: Invalid WSDL URL: https://*****.*****.com:999/SeniorSystemsWS/DataExportService.asmx?WSDL
Code: 503
Response Body: <html><body><b>Http/1.1 Service Unavailable</b></body> </html>]
Accessing this URL from a browser returns a proper WSDL definition. I am told by the provider that the 503 is due to a same-origin policy violation. Next, I researched adding CORS to node.js. This triggered my stepping back and asking the question: Am I in the right forest? I'm not sure. So, I am looking for a command-line, SOAP capable, CORS app (or equivalent) configuration. I am a web developer primarily using PHP and Javascript, so Javascript is where I turned first, but that is not a requirement. Ideas? Or, is there a solution to the current script error (the best I think I have found is using jQuery in node.js which includes CORS)
Most likely, this error belongs to your website server.
Please go through this link, it might be helpful.
http://pcsupport.about.com/od/findbyerrormessage/a/503error.htm
Also you can open your wsdl in web browser, search for soap:address location tag under services. And figure out correct url, you are trying to invoke from your script. Directly access this url in browser and see what are you getting.
I think I have a better approach to the task. I found over the weekend that PHP has a full SOAP client. I wrote the same basic login script in PHP and it runs just fine. I get a valid authentication code in the response to loginExt (which is required in further requests), so it looks like things are working. I will comment here after verifying that I can actually use the web service.

Google OAuth WildCard Domains

I am using the google auth but keep getting an origin mismatch. The project I am working has sub domains that are generated by the user. So for example there can be:
john.example.com
henry.example.com
larry.example.com
In my app settings I have one of my origins being http://*.example.com but I get an origin mismatch. Is there a way to solve this? Btw my code looks like this:
gapi.auth.authorize({
client_id : 'xxxxx.apps.googleusercontent.com',
scope : ['https://www.googleapis.com/auth/plus.me',
state: 'http://henry.example.com',
'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'],
immediate : false
}, function(result) {
if (result != null) {
gapi.client.load('oath2', 'v2', function() {
console.log(gapi.client);
gapi.client.oauth2.userinfo.get().execute(function(resp) {
console.log(resp);
});
});
}
});
Hooray for useful yet unnecessary workarounds (thanks for complicating yourself into a corner Google)....
I was using Google Drive using the javascript api to open up the file picker, retrieve the file info/url and then download it using curl to my server. Once I finally realized that all my wildcard domains would have to be registered, I about had a stroke.
What I do now is the following (this is my use case, cater it to yours as you need to)
On the page that you are on, create an onclick event to open up a new window in a specific domain (https://googledrive.example.com/oauth/index.php?unique_token={some unique token}).
On the new popup I did all my google drive authentication, had a button to click which opened the file picker, then retrieved at least the metadata that I needed from the file. Then I stored the token (primary key), access_token, downloadurl and filename in my database (MySQL).
Back on step one's page, I created a setTimeout() loop that would run an ajax call every second with that same unique_token to check when it had been entered in the database. Once it finds it, I kill the loop and then retrieve the contents and do with them as I will (in this case I uploaded them through a separate upload script that uses curl to fetch the file).
This is obviously not the best method for handling this, but it's better than entering each and every subdomain into googles cloud console. I bet you can probably do this with googles server side oauth libraries they use, but my use case was a little complicated and I was cranky cause I was frustrated at the past 4 days I've spent on a silly little integration with google.
Wildcard origins are not supported, same for redirect URIs.
The fact that you can register a wildcard origin is a bug.
You can use the state parameter, but be very careful with that, make sure you don't create an open redirector (an endpoint that can redirect to any arbitrary URL).

How to get twitter oAuth token of a logged in user

I'm trying to set up a javascript function to post a status to a twitter account using POST statuses/update, details here: https://dev.twitter.com/docs/api/1/post/statuses/update. The goal is a Twitter post similar to the open graph actions on Facebook.
I'm using jQuery ajax to make the post request, here's what I have so far:
$.ajax
({
type: "POST",
url: "https://api.twitter.com/1/statuses/update.json",
headers: jsonData,
data: {},
dataType: "jsonp",
success: function( data )
{
}
});
I believe that I need to generate a header something like this for security:
Authorization: OAuth oauth_consumer_key=consumerKey, oauth_nonce=nonce,
oauth_signature=signature, oauth_signature_method="HMAC-SHA1",
oauth_timestamp=timestamp, oauth_token=userToken, oauth_version="1.0"
I have the consumer key for my app, I can generate a nonce, I'm generating the signature and timestamp using the methods from this question Twitter OAuth authentication in javascript. The only thing I have left is th oauth_token, which I believe is the token of the user whose feed I wish to post to. Please correct me if I'm wrong about that.
The problem is, I have absolutely no idea how to get this token from the user in order to post to their feed. I've spent the last 2 hours running around in circles through Twitter's oAuth documention without finding anything that looked useful; everything I've found was either flowcharts with no code examples or predicated on my code already having the user's oAuth token.
My question is this: how can I get the logged in user's oAuth token using javascript?
If that is not possible, I have another page where I am currently storing the user's twitter id in the database with their permission, getting their token and databasing it in PHP would also be satisfactory, assuming it doesn't change very frequently.
In order to obtain the oauth_token you need to follow the authentication process. Your application needs to be authorized to act on the behalf of the user.
I would recomend to take some time first and learn how OAuth exactly works (there is a lot of information available) and then implement it in your app. (http://hueniverse.com/oauth/)
You could also benefit from a library which will make your life easier. (in your case, look at: https://dev.twitter.com/docs/twitter-libraries#php).
Hope this has been useful.
Here is example for get twitter oauth token and post tweet in twitter .
Code sample is in php .
http://www.phpgang.com/how-to-post-tweet-on-twitter-with-php_414.html
1) to obtain the oauth token you need to follow the authentication process.
2) and your application needs to be authorized to act on the behalf of the user.
you can also see this twitter example for better understanding how it works
In this use can see the process of authorized user and post and get json result.
https://dev.twitter.com/rest/tools/console
I hope this will help you.
thanks

Categories

Resources