SharePoint weather web part - sharepoint-2013

Can any one help me to find out free weather forecast on my sharepoint 2013 site?
I found some limited calls APIs, but not completely free.

I did simple test by Yahoo Weather API.
Create an app in Apps, so you could use id&key&secret to request.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha1.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/enc-base64.js">
</script>
<script type="text/javascript">
var url = 'https://weather-ydn-yql.media.yahoo.com/forecastrss';
var method = 'GET';
var app_id = '80ggw87i';
var consumer_key = 'yourkey';
var consumer_secret = 'yoursecret';
var concat = '&';
var query = { 'location': 'sunnyvale,ca', 'format': 'json' };
var oauth = {
'oauth_consumer_key': consumer_key,
'oauth_nonce': Math.random().toString(36).substring(2),
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': parseInt(new Date().getTime() / 1000).toString(),
'oauth_version': '1.0'
};
var merged = {};
$.extend(merged, query, oauth);
// Note the sorting here is required
var merged_arr = Object.keys(merged).sort().map(function (k) {
return [k + '=' + encodeURIComponent(merged[k])];
});
var signature_base_str = method
+ concat + encodeURIComponent(url)
+ concat + encodeURIComponent(merged_arr.join(concat));
var composite_key = encodeURIComponent(consumer_secret) + concat;
var hash = CryptoJS.HmacSHA1(signature_base_str, composite_key);
var signature = hash.toString(CryptoJS.enc.Base64);
oauth['oauth_signature'] = signature;
var auth_header = 'OAuth ' + Object.keys(oauth).map(function (k) {
return [k + '="' + oauth[k] + '"'];
}).join(',');
$.ajax({
url: url + '?' + $.param(query),
headers: {
'Authorization': auth_header,
'X-Yahoo-App-Id': app_id
},
method: 'GET',
success: function (data) {
console.log(data);
debugger;
}
});
</script>
You need bind the data with proper CSS.

Related

How can I get list items by view name, using REST API ajax?

I tried to get a list of items from the Sharepoint library by view name. I had ajax rest API URL:
url: webapp + "_api/web/list/getbytitle" + "('" + LibraryName + "')/View/getbytitle" +"('" + viewName + "')"
method:"GET"
header:"Accept":"application/json;odata=verbose
How can I get all the items in view name?
please refer the following code snippet to get items from specific view, Rest API not provider items endpoint return from a view directly.
So please do the following:
perform the first request to get CAML Query for List View using SP.View.viewQuery property
perform the second request to retrieve List Items by specifying CAML Query:
getListItemsForView(_spPageContextInfo.webAbsoluteUrl,'MyList12','View1')
.done(function(data)
{
var items = data.d.results;
for(var i = 0; i < items.length;i++) {
console.log(items[i].Title);
}
})
.fail(
function(error){
console.log(JSON.stringify(error));
});
function getListItemsForView(webUrl,listTitle,viewTitle)
{
var viewQueryUrl = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
return getJson(viewQueryUrl).then(
function(data){
var viewQuery = data.d.ViewQuery;
return getListItems(webUrl,listTitle,viewQuery);
});
}
function getJson(url)
{
return $.ajax({
url: url,
type: "GET",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function getListItems(webUrl,listTitle, queryText)
{
var viewXml = '<View><Query>' + queryText + '</Query></View>';
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
var queryPayload = {
'query' : {
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml' : viewXml
}
};
return $.ajax({
url: url,
method: "POST",
data: JSON.stringify(queryPayload),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose"
}
});
}
Same question has been answered here:
Using REST to fetch SharePoint View Items

Signing GET HTTP Requests to Amazon Elasticsearch Service

I need to call "Signing GET HTTP Requests to Amazon Elasticsearch Service" using lambda function.
I have already tried http package and it's working fine in http request
http.get(`http://search-"my_ES_service_name"-xxxxxxxxxxx-6fa27gkk4v3dugykj46tzsipbu.xx-xxxx-x.es.amazonaws.com/${event['index']}/doc/_search/?q=${event['keyParam']}`,
function(res) {
var body = '';
res.on('data', function(d) {
body += d;
});
res.on('end', function() {
context.succeed(JSON.parse(body.replace(/\n|\r/g, ""))); //Remove and newline/linebreak chars
});
}).on('error', function(e) {
console.log("Error: " + e.message);
context.done(null, 'FAILURE');
});
var AWS = require('aws-sdk');
exports.handler = function(event, context) {
var region = 'xx-xxxx-x';
var domain = 'http://search-"my_ES_service_name"-xxxxxxxxxxx-6fa27gkk4v3dugykj46tzsipbu.xx-xxxx-x.es.amazonaws.com';
var index = event['index'];
var type = `_doc/_search`;
var endpoint = new AWS.Endpoint(domain);
var request = new AWS.HttpRequest(endpoint, region);
request.method = 'GET';
request.path += index + '/' + type+'?q=_doc_key_here:_doc_key_value';
request.headers['host'] = domain;
> e.g. URL genrate like: http://search-"my_ES_service_name"-xxxxxxxxxxx-6fa27gkk4v3dugykj46tzsipbu.xx-xxxx-x.es.amazonaws.com/node-test/doc/_search/?q=user_name:johndoe
var credentials = new AWS.EnvironmentCredentials('AWS');
var signer = new AWS.Signers.V4(request, 'es');
signer.addAuthorization(credentials, new Date());
var client = new AWS.HttpClient();
client.handleRequest(request, null, function(response) {
console.log("response: ",response.statusCode);
var responseBody = '';
response.on('data', function (chunk) {
responseBody += chunk;
});
response.on('end', function (chunk) {
console.log('Response body: ' + responseBody);
context.succeed(responseBody)
});
}, function(error) {
console.log('Error: ' + error);
context.done(error);
});
}
when I'm trying to call "Signing GET HTTP Requests" using above function, then it's thrown me the following error:
response: 400 Bad Request
Only one thing is missing here, I have added encodeURI() in request and it works fine for me
var index = event['index'];
var type = `_doc/_search?q=_doc_key_here:_doc_key_value`;
request.method = 'GET';
request.path += index + '/' + encodeURI(type);
I hope it will help other guys
Thanks

How to get Facebook post likes?

I Am trying to retrieve FB Post Likes and Reactions using Graph API. The code that I used to retrieve the 'LIKE','LOVE','HAHA' of a post is shared below.
<script type="text/javascript">
var postID = '';
var access_token = '';
var refreshTime = 1;
var defaultCount = 0;
var reactions = ['LIKE', 'LOVE', 'HAHA'].map(function (e) {
var code = 'reactions_' + e.toLowerCase();
return 'reactions.type(' + e + ').limit(0).summary(total_count).as(' + code + ')'
}).join(',');
function refreshCounts() {
var url = 'https://graph.facebook.com/v2.8/?ids=' + postID + '&fields=' + reactions + '&access_token=' + access_token;
$.getJSON(url, function(res){
var v1 = res[postID].reactions_like.summary.total_count;
var v2 = res[postID].reactions_love.summary.total_count;
var v3 = res[postID].reactions_haha.summary.total_count;
$('#counter1').text(v1);
$('#counter2').text(v2);
$('#counter3').text(v3);
});
}
$(document).ready(function(){
setInterval(refreshCounts, refreshTime * 3000);
refreshCounts();
});
</script>
But the code showing two {} instead of the result.
Why don't you using javascript SDK?
var postID = $('#post_id').val();
FB.api(
'/' + postID + '/',
'GET',
{
"fields": "reactions.type(LIKE).limit(0).summary(1).as(like),reactions.type(WOW).limit(0).summary(1).as(wow),reactions.type(SAD).limit(0).summary(1).as(sad),reactions.type(LOVE).limit(0).summary(1).as(love),reactions.type(HAHA).limit(0).summary(1).as(haha),reactions.type(ANGRY).limit(0).summary(1).as(angry)",
"access_token": "token"
},
function (response) {
console.log(response);
var like_count = response.like.summary.total_count;
var love_count = response.love.summary.total_count;
var wow_count = response.wow.summary.total_count;
var haha_count = response.haha.summary.total_count;
var sad_count = response.sad.summary.total_count;
var angry_count = response.angry.summary.total_count;
}
);
This worked for me

"Missing credentials in config" Returned From Amazon S3 JavaScript SDK Server

I've been following the boilerplate code at http://aws.amazon.com/developers/getting-started/browser/ to get CORS uploading to work with my S3 account.
I've created a Facebook App, changed the CORS configuration XML for my S3 bucket, and filled in the appropriate variables in the JavaScript code. But when I try to upload a file through my webpage, I get the Error: Missing credentials in config response.
Can someone point me in the right direction to debugging this?
My JS:
var appId = '999943416325248';
var roleArn = 'arn:aws:iam::458182047307:role/s3-test';
var bucketName = 'my-bucket';
var fbUserId;
var bucket = new AWS.S3({
params: {
Bucket: bucketName
}
});
var fileChooser = document.getElementById('video-file-input');
var button = document.getElementById('submit-button');
var results = document.getElementById('results');
button.addEventListener('click', function () {
var file = fileChooser.files[0];
if(file){
results.innerHTML = '';
//Object key will be facebook-USERID#/FILE_NAME
var objKey = 'facebook-' + fbUserId + '/' + file.name;
var params = {
Key: objKey,
ContentType: file.type,
Body: file,
ACL: 'public-read'
};
bucket.putObject(params, function (err, data) {
if(err){
results.innerHTML = 'ERROR: ' + err;
}
else{
listObjs();
}
});
}
else{
results.innerHTML = 'Nothing to upload.';
}
}, false);
function listObjs() {
var prefix = 'facebook-' + fbUserId;
bucket.listObjects({
Prefix: prefix
}, function (err, data) {
if(err){
results.innerHTML = 'ERROR: ' + err;
}
else{
var objKeys = "";
data.Contents.forEach(function (obj) {
objKeys += obj.Key + "<br>";
});
results.innerHTML = objKeys;
}
});
}
/*!
* Login to your application using Facebook.
* Uses the Facebook SDK for JavaScript available here:
* https://developers.facebook.com/docs/javascript/gettingstarted/
*/
window.fbAsyncInit = function () {
FB.init({
appId: appId
});
FB.login(function (response) {
bucket.config.credentials = new AWS.WebIdentityCredentials({
ProviderId: 'graph.facebook.com',
RoleArn: roleArn,
WebIdentityToken: response.authResponse.accessToken
});
fbUserId = response.authResponse.userID;
button.style.display = 'block';
});
};
// Load the Facebook SDK asynchronously
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if(d.getElementById(id)){
return;
}
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
Turns out Chrome was blocking pop-ups on my domain so Facebook authentication couldn't process. Once I allowed pop-ups from the domain, everything worked as expected

Mark list item as viewed/read in SharePoint 2013

When a user views an item in SharePoint list, I need to capture that it has been viewed and who viewed the item (in additional columns). Is there a way to do that?
I did this by adding a script editor web part and inserting this script in there:
<script type="text/javascript" src="/jquery-1.10.2.min.js"></script>
<script src="/jquery.SPServices-2013.02a.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () { ExecuteOrDelayUntilScriptLoaded(loadConstants, "sp.js"); });
function loadConstants() {
var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : onSuccess,
error : onError
});
function onSuccess(data, request){
var loginName = data.d.Title;
var docurl = document.URL;
var beginindex = docurl.indexOf('?ID=') + 4;
var endindex = docurl.indexOf('&Source=');
var itemid = docurl.substring(beginindex, endindex);
var ctx = new SP.ClientContext("your website url");
var oList = ctx.get_web().get_lists().getByTitle('your library name');
this.oListItem = oList.getItemById(itemid);
this.oListItem.set_item('Read', loginName + ' ' + getTodayDate());
this.oListItem.update();
ctx.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onError(error) {
alert("error");
}
function getTodayDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = mm+'/'+dd+'/'+yyyy;
return today;
}
}
</script>