App Part issues, spPageContextInfo - sharepoint-2013

I am trying to create an SharePoint hosted app that contains an app part, this app part should show what the user is following. I have used working code as an example in the app, but I don't get it to work inside of the App Part.
I get this within the app part: "Uncaught ReferenceError: _spPageContextInfo is not defined".
If anyone has a real example how to make this work inside an app part, and using social.following, please help!
This is the code in App.js:
var headline = new Array("People", "Documents", "Sites");
var ActorImg = new Array("/_layouts/15/images/person.gif", "/_layouts/15/images/lg_ICGEN.gif", "/_layouts/15/images/siteicon_16x16.png");
function doJSON(RESTuri, success, fail) {
var restUrl = _spPageContextInfo.webAbsoluteUrl + RESTuri;
var executor = new SP.RequestExecutor(_spPageContextInfo.webAbsoluteUrl);
executor.executeAsync(
{
url: restUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: success,
error: fail
}
);
}
function renderSuccess(data) {
var jsonObject = JSON.parse(data.body);
var n = document.getElementById('jsonout');
n.innerHTML = data.body;
var results = jsonObject.d.Followed.results;
var str = '';
var old = -1;
var img = null;
for (j = 0; j < 5; j++) {
str += "<div class=\"container container" + j + "\">";
for (i = 0; i < results.length; i++) {
if (j != results[i].ActorType) continue;
if (old != results[i].ActorType) str += "<h1 class=\"headline" + results[i].ActorType + "\">" + headline[results[i].ActorType] + "</h1>";
img = results[i].ImageUri;
if (img == null) img = ActorImg[results[i].ActorType];
switch (results[i].ActorType) {
case 0:
// Use case: depending on ActorType if you want to use indiviual markup for every item-type
str += "<a title=\"" + results[i].Name + "\" class=\"link" + results[i].ActorType + "\" style=\"background-image:url(" + img + ")\" href=\"" + results[i].Uri + "\">" + results[i].Name + "</a>";
break;
default:
str += "<a title=\"" + results[i].Name + "\" class=\"link" + results[i].ActorType + "\" style=\"background-image:url(" + img + ")\" href=\"" + results[i].Uri + "\">" + results[i].Name + "</a>";
break;
}
old = results[i].ActorType;
}
str += "</div>";
}
n = document.getElementById('htmlout');
n.innerHTML = str + "<h1></h1>";
}
function renderFail(data, errorCode, errorMessage) {
n = document.getElementById('htmlout');
n.innerHTML = errorMessage;
}
$(document).ready(function () {
doJSON("/_api/social.following/my/followed%28types=15%29", renderSuccess, renderFail);
});
This is the div that's being used in both the app page(default.aspx) and the app part page(AppPart.aspx):
<div class="classic">
<pre id="jsonout" style="display: none;"></pre>
<div id="htmlout"></div>
</div>

Sorry guys. I solved it by just adding a reference to the sp.requestexecutor.js file, and parsed the host- and app-url from the querystring

Related

CamlQuery Retrieve Folder and files from specific folder

Hi I'm working with sharepoint designer 2013 and I have this structure for document library webpart:
Folder1
SubFolder1
SubFile1.txt SubFile2.txt
File1.txt
I managed to target the Folder1, but it displays everything, SubFolder1, Subfile1.txt, Subfile2.txt and File1.txt at the same level. But what I want is SubFolder1 and File1.txt. And then if we click on SubFolder1 we have the files inside.
Something like this
what I did :
<Query><Where><Contains><FieldRef Name="FileDirRef"/><Value Type="Text">pathOfFolder1</Value></Contains></Where></Query>
I set the scope to recursiveAll, and I tried also "All" but it didn't work.
The example below for your reference:
<style>
input[type=button] {
background: #ccc;
border: 0 none;
cursor: pointer;
-webkit-border-radius: 0px;
border-radius: 0px;
margin-left: 0px !important;
font-size: small;
font-weight: bold;
}
.dupHier img {
padding-right: 10px;
}
.dupHier a {
position: relative;
top: -2px;
}
.dupHier {
padding-top: 5px;
padding-bottom: 5px;
}
</style>
<!--To Populate Libraries-->
<select id="drpSelectSourceLibrary"></select>
<!--To Populate Levels on click-->
<input class="getLevels" name="getLevels" type="button" value="Get Levels" onclick="return false;" />
<!--To Populate Hidden Levels-->
<div class="genHier"></div>
<hr />
<!--To Populate Hierarchy Visible on page-->
<div class="dupHenHier"></div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
//Site Context URL
var spctx = _spPageContextInfo.siteAbsoluteUrl;
//Array to Store all the objects
var hm = [];
//Object involving File/Folder name, path, level in hierarchy, whether it is file or folder
function hierMaker(name, path, level, isFile) {
this.name = name;
this.path = path;
this.level = level;
this.isFile = isFile;
}
var virtualLevel = 0;
var boolVirtual = true;
var maxLevel = 0;
function getLevels() {
//Reset global variables
hm.length = 0;
virtualLevel = 0;
boolVirtual = true;
maxLevel = 0;
tctr = 1;
$('.genHier').html("");
$('.dupHenHier').html("");
//Main code below
var appWebUrl = spctx;
var listName = $("#drpSelectSourceLibrary option:selected").text();
var certURL = appWebUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$expand=Folder,File&$select=ID,Title,FileLeafRef,Folder/ServerRelativeUrl,File/ServerRelativeUrl";
$.ajax({
url: certURL,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
getFolderSchema(data.d.results);
},
error: function (data) {
alert(JSON.stringify(data));
}
});
function getFolderSchema(data) {
maxLevel = 0;
dLength = data.length;
if (dLength >= 0) {
for (var i = 0; i < dLength; i++) {
if (boolVirtual) {
if (data[i].Folder.ServerRelativeUrl) {
virtualLevel = data[i].Folder.ServerRelativeUrl.split('/').length;
boolVirtual = false;
}
else {
virtualLevel = data[i].File.ServerRelativeUrl.split('/').length;
boolVirtual = false;
}
}
var isFile = false;
var path = "";
var level = 0;
if (data[i].Folder.ServerRelativeUrl) {
//It is folder
isFile = false;
path = data[i].Folder.ServerRelativeUrl;
level = data[i].Folder.ServerRelativeUrl.split('/').length - virtualLevel;
}
else {
//It is file
isFile = true;
path = data[i].File.ServerRelativeUrl;
level = data[i].File.ServerRelativeUrl.split('/').length - virtualLevel;
}
var tmpDiv = "<div class='subHier' isFile='" + isFile + "' level='" + level + "' path='" + path + "'><a href='" + path + "' target='_blank'>" + data[i].FileLeafRef + "</a></div>";
$(".genHier").append(tmpDiv);
maxLevel++;
var hmsc = new hierMaker(data[i].FileLeafRef, path, level, isFile);
hm.push(hmsc);
}
providePaddding();
}
}
}
var d = 1;
function providePaddding() {
var kickCtr = 0;
var hmlength = hm.length;
for (var j = 0; j < hmlength; j++) {
//Creation of level 0 elements
if (hm[j].level == 0) {
var tmpDiv = "";
if (hm[j].isFile) {
tmpDiv = "<div class='dupHier' isFile='" + hm[j].isFile + "' level='" + hm[j].level + "' path='" + hm[j].path + "'><img src='" + file + "' /><a href='" + hm[j].path + "' target='_blank'>" + hm[j].name + "</a></div>";
}
else {
tmpDiv = "<div class='dupHier' isFile='" + hm[j].isFile + "' level='" + hm[j].level + "' path='" + hm[j].path + "'><img src='" + folder + "' /><a href='" + hm[j].path + "' target='_blank'>" + hm[j].name + "</a></div>";
}
kickCtr++;
$('.dupHenHier').append(tmpDiv);
}
}
call();
}
var tctr = 1;
var folder = spctx + "/Style Library/folder.JPG";
var file = spctx + "/Style Library/file.JPG";
function call() {
$('.dupHier').each(function () {
if ($(this).attr('isDone')) {
//continue;
}
else {
for (var j = 0; j < hm.length; j++) {
if (hm[j].level == tctr) {
var str = hm[j].path + "";
var ts = $(this).attr('path');
var tmpDiv = "";
if (str.indexOf(ts) > -1) {
if (hm[j].isFile) {
tmpDiv = "<div class='dupHier' isFile='" + hm[j].isFile + "' level='" + hm[j].level + "' path='" + hm[j].path + "'><img src='" + file + "'/><a href='" + hm[j].path + "' target='_blank'>" + hm[j].name + "</a></div>";
}
else {
tmpDiv = "<div class='dupHier' isFile='" + hm[j].isFile + "' level='" + hm[j].level + "' path='" + hm[j].path + "'><img src='" + folder + "'/><a href='" + hm[j].path + "' target='_blank'>" + hm[j].name + "</a></div>";
}
$(this).append(tmpDiv);
}
}
}
}
$(this).attr('isDone', true);
});
tctr++;
if (tctr < 10)
call();
//Provide padding as per level, level * 10px
$('.dupHier').each(function () {
var tmpPad = $(this).attr('level') * 10 + "px";
$(this).css({ "padding-left": tmpPad });
});
}
$(document).ready(function () {
$('.getLevels').click(function () {
getLevels();
});
$('.genHier').hide();
});
//Population of libraries
ExecuteOrDelayUntilScriptLoaded(loadDocLibraries, "SP.js");
function loadDocLibraries() {
var clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
clientContext.load(web);
listColl = web.get_lists();
clientContext.load(listColl);
clientContext.executeQueryAsync(onLibSuccess, onLibfail);
}
function onLibSuccess() {
var listEnumerator = listColl.getEnumerator();
var Lib = "";
$('#drpSelectSourceLibrary').empty();
$("#drpSelectSourceLibrary").prepend('<option value="Select" selected="selected">Select Documents Library</option>');
while (listEnumerator.moveNext()) {
var list = listEnumerator.get_current();
var value = list.get_hidden();
//console.log(value);
if (list.get_baseTemplate() == '101') {
if (value == false) {
var x = document.getElementById("drpSelectSourceLibrary");
var option = document.createElement("option");
var filename = list.get_title();
option.text = filename;
x.add(option);
}
}
}
}
function onLibfail() {
console.log(arguments[1].get_message());
}
</script>
Refer to: http://www.sharepointjunkies.com/unlimited-files-folders-hierarchy-sharepoint-online-using-rest-api/

django admin custom time widget

I am trying to override django's time widget.
if (!$) {
$ = django.jQuery;
}
function overrideTimeOptions() {
$('.timelist').each(function(num, el) {
var time_format = '%H:%M';
$(el).html('');
for (var i=1; i<25; i++) {
var time = new Date(1970,1,1,i,0,0);
console.log(time)
var lnk = "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '" + time.strftime(time_format) + "');"
console.log("this is link");
console.log(lnk);
$(el).append('<li>' + time.strftime(time_format) + '</li>');
}
});
}
setTimeout(function(){overrideTimeOptions()},500);
Here I can see the time options but when I click the time it gives me some weired value in the input field like NaNaNa
Can anyone help me on this whats going on here ??

How to pass multipart file data to a web service

I wanna do something like this.
1.Uploading a file from a jsp in multipart
2.Calling a servlet
3.In dopost of that servlet i wanna call a webservice which takes all the params passed by jsp to servlet along with the multipart data.
dopost(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response){
webserviceMethod(request,response);
}
I'm stuck on third point where I can set all request params to webservice method. But I don't know how to pass multipart file data to that websevice. I failed to do so. How can i do that part??
Have a look at that jquery plugin:
http://jquery.malsup.com/form/
I'm also using this in my Application together with a java servlet:
uploadImage: function (e) {
var self = this;
self.ignoreDrag(e);
if ($('#feed_imageUploader').find('input').hasClass('error')) {
return;
}
//cant put this in an model - ajaxSubmit has no done callback
$('#img_uploaded h1').text(polyglot.t('iview.loading'));
$('#feed_imageUploader').ajaxSubmit({
target: '#img_uploaded',
type: "POST",
url: path.apiPath + 'item.uploadImg/' + self.itemId + '/' + token,
dataType: "text",
async: true,
success: function () {
self.afterUploadImage();
}
});
},
afterUploadImage: function () {
var self = this;
self.changed = true;
var xFactorItemImage = 0;
var yFactorItemImage = 0;
var randomnumber = Math.floor(Math.random() * 10100000);
$('#img_uploaded').html("<img src=\"" + path.tempImage + userId + "_" + self.itemId + ".jpg?id=" + randomnumber + "\" style=\"display:none\" id=\"cropPhoto_uploaded\">");
var theImage = new Image();
var cropPhoto = $('#cropPhoto_uploaded');
theImage.src = cropPhoto.attr("src");
var widthPhoto = 0;
var heightPhoto = 0;
var NwidthPhoto = 0;
var NheightPhoto = 0;
$(theImage).load(function () {
$('#img_uploaded h1').empty();
$('#additemimage').hide();
NwidthPhoto = theImage.width;
NheightPhoto = theImage.height;
cropPhoto.css({
maxHeight: $('#img_uploaded').height() + 'px',
maxWidth: $('#img_uploaded').width() + 'px'
});
cropPhoto.show();
$('#addimage_upload').fadeIn(aSpeed.middle);
widthPhoto = cropPhoto.width();
heightPhoto = cropPhoto.height();
xFactorItemImage = NwidthPhoto / widthPhoto;
yFactorItemImage = NheightPhoto / heightPhoto;
cropPhoto.Jcrop({
setSelect: helper.getMiddleSelectionOfImage(widthPhoto, heightPhoto, widthPhoto, heightPhoto),
bgOpacity: 0.3,
onChange: showItemImageCoords,
onSelect: showItemImageCoords
});
});
function showItemImageCoords(c) {
$('#x111').val(parseInt(xFactorItemImage * c.x));
$('#y111').val(parseInt(yFactorItemImage * c.y));
$('#x222').val(parseInt(xFactorItemImage * c.w));
$('#y222').val(parseInt(yFactorItemImage * c.h));
}
},
And the servlet part:
public void UploadImage(HttpServletRequest request, String filename, String folder,String bucketname) {
File file;
PropertyReader mainconf = new PropertyReader();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items ;
mainconf.getProb("conf/MainConfig.properties");
s3 s3=new s3();
try {
items = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = items.iterator();
//Iterate through the items
String finalPath = "";
FileItem fi;
while (i.hasNext()) {
fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String your_os = System.getProperty("os.name").toLowerCase();
String workingDir = "images";
finalPath = mainconf.read("imagePath");
if (your_os.indexOf("win") >= 0) {
finalPath = finalPath + workingDir + "\\" + folder + "\\";
} else if (your_os.indexOf("nix") >= 0 || your_os.indexOf("nux") >= 0) {
finalPath = finalPath + workingDir + "/" + folder + "/";
} else {
finalPath = finalPath + workingDir + "{others}" + folder + "{others}";
}
file = new File(finalPath + filename + ".jpg");
fi.write(file);
s3.writeFile(bucketname, file, filename+".jpg");
file.delete();
}
break;
}
} catch (Exception ex) {
Logger.getLogger(UploadItemImage.class.getName()).log(Level.SEVERE, null, ex);
}
}

Random alert text and pop up only once

I'm try to write up code that will allow me to create a message with text that randomly displays one of three messages. In addition, this message will appear as an alert after you click a button. I now want to also program the button so it will only appear once per user. I've been able to make the random text part work, but not the one-time pop up feature. Let me know what I should do! Below is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Random thingy</title>
<script language type="text/javascript">
<!--
function getMessage() {
var ar = new Array(20)
ar[0] = "your assignment will be GRADED"
ar[1] = "your assignment will be UNGRADED"
ar[2] = "your assignment will be FUN"
// add as many more that you can stand but make
// sure you update the value '7' in the alert box
var now = new Date()
var sec = now.getSeconds()
alert("Your Grading Scheme:\n\n" + ar[sec % 3])
}
<!-- Begin
var expDays = 1; // number of days the cookie should last
var page = "only-popup-once.html";
var windowprops = "width=300,height=200,location=no,toolbar=no,menubar=no,scrollbars=no,resizable=yes";
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function amt(){
var count = GetCookie('count')
if(count == null) {
SetCookie('count','1')
return 1
}
else {
var newcount = parseInt(count) + 1;
DeleteCookie('count')
SetCookie('count',newcount,exp)
return count
}
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function checkCount() {
var count = GetCookie('count');
if (count == null) {
count=1;
SetCookie('count', count, exp);
alert('MESSAGE');
}
else {
count++;
SetCookie('count', count, exp);
}
}
// End -->
</script>
</head>
<body onLoad="getMessage(); checkCount()">
<form>
<input type="button" name="again" value="Your Self-Assessment Grading Scheme. Click To Find Out." onClick="getMessage()">
</form>
</body>
</html>

Google Friend Connect fcauth cookie in php

this may be easy for most of you .. but not me.
I am using some "sample" Google code - as it fits my purpose so why change what works - but for the life of me I cannot access/find/get etc the FCAuth cookie after a user is logged in.
Help please - thanks in advance.
Here is my code (the Site ID is in a set variable, and all the calls work todate. just need to find/get the FCAuth cookie.
var viewer, ownerFriends, activities;
google.friendconnect.container.setParentUrl('/api/' /* location of rpc_relay.html and canvas.html */);
google.friendconnect.container.loadOpenSocialApi({
site: SITE_ID,
onload: function() { initAllData(); }});
function initAllData() {
var params = {};
params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
[opensocial.Person.Field.ID,opensocial.Person.Field.NAME,opensocial.Person.Field.THUMBNAIL_URL,opensocial.Person.Field.PROFILE_URL];
var req = opensocial.newDataRequest();
req.add(req.newFetchPersonRequest('VIEWER', params), 'viewer');
req.add(req.newFetchPeopleRequest(
new opensocial.IdSpec({'userId' : 'OWNER', 'groupId' : 'FRIENDS'}), params),
'ownerFriends');
req.add(req.newFetchActivitiesRequest(new opensocial.IdSpec({'userId' : 'OWNER', 'groupId' : 'FRIENDS'})), 'activities');
var idspec = new opensocial.IdSpec({ 'userId' : 'VIEWER','groupId' : 'FRIENDS' });
req.add(req.newFetchPeopleRequest(idspec), 'viewer_friends');
req.send(onData);
req.send(setupData);
};
function setupData(data) {
ownerFriends = data.get('ownerFriends').getData().asArray();
var html = "";
for (var i = 0; i < ownerFriends.length && i < 8; i++) {
var person = ownerFriends[i];
html += "<a title='" + person.getField("displayName") + "' href='" + person.getField("profileUrl") + "'>";
html += "<img class='memberPhoto' src='" + person.getField("thumbnailUrl") + "' width='50px' alt='" + person.getField("displayName") + "'/>";
html += "</a> ";
};
document.getElementById('members').innerHTML = html;
viewer = data.get('viewer').getData();
if (viewer) {
document.getElementById('memberstate').innerHTML =
'<h2>' + viewer.getField("displayName") + ' welcome to the Yoga Council of Canada </h2>' ;
} else {
document.getElementById('memberstate').innerHTML =
'<h2>Join with one click</h2> After joining, you will automatically appear as a recent member.';
}
viewer = data.get('viewer').getData();
if (viewer) {
document.getElementById('profile').innerHTML =
'<img align="left" src="' + viewer.getField("thumbnailUrl") + '" style="margin-right: 20px;" >' +
'<strong>' + viewer.getField("displayName") + '</strong><br>' +
'Settings<br>' +
'Invite a friend<br>' +
'Sign out<br>';
} else {
google.friendconnect.renderSignInButton({ 'id': 'profile' });
}
};
function onData(data) {
if (!data.get("viewer_friends").hadError()) {
var site_friends = data.get("viewer_friends").getData();
var list = document.getElementById("friends-list");
list.innerHTML = "";
site_friends.each(function(friend) {
list.innerHTML += "<li>" + friend.getDisplayName() + "</li>";
});
}
};
OK, I am/was being totally thick, the cookie is automatically set as
$_COOKIE['fcauth<your appID>'];
So you can "just call it" i.e.
<?php if($_COOKIE['fcauth<your appID>']): do something endif; ?>