Create document set with REST in SharePoint Online - rest

I am struggling with the creation of a document set via REST API in SharePoint online. The only solution I found doing this was using the old SharePoint 2010 REST interface in the following way:
$http({
method: "POST",
url: url + "/_vti_bin/listdata.svc/" + listTitle,
data: JSON.stringify(docSetOptions),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $('#__REQUESTDIGEST').val(),
"Slug": _spPageContextInfo.siteServerRelativeUrl + "/" + url + docSetOptions.Path + "/" + docSetOptions.Title + "|" + docSetOptions.ContentTypeId,
}
}).success(function (data, status, headers, config) {
logtoconsole("document set created");
}).error(function (data, status, headers, config) {
logtoconsole("document set error");
});
docSetOptions are those:
var folder = new
{
Title = "foo",
Path = "foo",
ContentTypeId = "0x010050D9126DC6276846BF6D869EF2090EAD",
ContentType = "SP.Data.Shared_x0020_DocumentsItem",
};
The id is the id of my custom content type, derived from document set.
Source: http://www.itidea.nl/index.php/create-a-document-set-using-jsom-and-rest/
This works for me, but a regular folder is created. No document set. Does anybody know if this still works in SharePoint Online?
The only entries I found were regarding SharePoint 2013.
Update: I ran the same script against my SharePoint 2013 on Premise Server and it works perfectly. Document set is created. Microsoft changed this a few months ago. It used to be possible!

Okay, I found a solution.
Since a while it is not possible anymore, to create a document set via REST if the sites content type id is used.
In my case, I had to use the id of the content type in the library.
So I went to my library settings, selected my content type and copied it. The
id differs a little. In my case was 0x0120D5200085474276CB6D314E9BC0E6F067D47DBE. But in your case it will look different.
If I use this id my document set is created successfully!
This took me hours to find out.

Related

Not be able to console log Auth0 user_metadata. I created a custom rule I also see the data in postman.What am I doing wrong

** I'm doing as following, I already created a custom rule.**
componentDidMount() {
console.log(token)
let response = fetch('https://DOmain.eu.auth0.com/userinfo', {
method: 'GET',
headers: {
Authorization: 'Bearer ' + token,
},
}).then((response) => response.json())
.then(responseJson => data = responseJson).then(console.log(data.nickname));
const metadata = data["https://Domain.eu.auth0.com/user_metadata"]
console.log(metadata);
}
My rule:
The Rule you have setup looks good, but will not work as the namespace is an Auth0 domain
Any non-Auth0 HTTP or HTTPS URL can be used as a namespace identifier,
and any number of namespaces can be used
Give it a shot with an alternate namespace, example 'https://myapp.example.com/', and you should be good to go!
As a side note, I would try to avoid adding all the usermetadata to the idtoken which can cause the generated token to be too large. You should also ensure that the data being included is not sensitive and can be disclosed. Some items that may be helpful, a quick read here: https://auth0.com/docs/metadata and here: https://auth0.com/docs/scopes/current/custom-claims to help you along the way!

Post attachment in Service Now

I'm in a quandary on how to get this working.
In Postman, I can upload an attachment without any issue.
I'm uploading a simple text file.
The code from postmanshows this:
var form = new FormData();
form.append("uploadFile", "C:\\temp\\test.txt");
var settings = {
"async": true,
"crossDomain": true,
"url": "https://xxxxxxx.service-now.com/api/now/attachment/file?table_name=problem&table_sys_id=oiui5346jh356kj3h634j6hk&file_name=Toast",
"method": "POST",
"headers": {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==",
"Cache-Control": "no-cache",
"Postman-Token": "39043b7f-8b2c-1dbc-6a52-10abd25e91c1"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}
$.ajax(settings).done(function (response) {
console.log(response);
});
When I use this on an .asp page I get a 400 error and a response from the console that says:
"Failed to create the attachment. File part might be missing in the request."
How do you get the file you want attach into the code correctly. I thought hard coding it in would have worked. How do you get the code to find the file on the local users pc. Once I get this working I eventually want to have a file input button to select the file.
Thanks,
Scott
Your code looks fine except this line:
form.append("uploadFile", "C:\\temp\\test.txt");
Passing the file name as the second parameter won't work, according to the documentation of FormData.append here, you need to pass some blob/file object pointing to the document it self (not a string)
Now there are 2 possible scenarios:
Scenario 1
The user selects the file manually using a browse button
Here you need to add the input to your page and a trigger to upload the file when it's selected, something like below maybe:
uploadDataFile();
function uploadDataFile(fileInput) {
// creates the FormData object
var form = new FormData();
// get the first file in the file list of the input
// (you will need a loop instead if the user will select many files)
form.append("uploadFile", fileInput.files[0]);
// ... the rest of your AJAX code here ...
}
<input type="file" onchange="uploadDataFile(this)" />
Scenario 2
Uploading the file directly without user intervention
Here you need to construct the file object manually same as in this answer and then you will add it normally to your data object
function uploadDataFile() {
// creates the file object
var fileObject = new File (...);
// creates a data object and appends the file object to it
var form = new FormData();
form.append("uploadFile", fileObject);
// ... the rest of your AJAX code here ...
}
One final note
Please pay attention to the browser compatibility for FormData & File objects

SharePoint 2013 REST API - Return specific 'likes' for a post in my news feed

This is my first question that I have ever posted on here so please be gentle!
I am trying to use a SharePoint 2013 REST service call using JQUERY Ajax to return the total 'likes' the most recent post to a user's SharePoint (MySite) newsfeed has recieved. Basically I have developed a little social webpart for our company intranet that displays the user's portrait and their last post (truncated). I thought it would be cool to also show how many likes that post has recieved but I have not been able to find out how to do so.
Here is a segment of my code which is working but I am only adding it to this question to give some insight to what I am trying to achieve -
$.ajax({
url: "/_api/social.feed/my/feed(MaxThreadCount=1,SortOrder=1)",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
dataType: 'json',
success: function (data) {
if (data.d.SocialFeed.UnreadMentionCount != null)
{document.getElementById("unreadmentions").innerHTML = data.d.SocialFeed.UnreadMentionCount;}
else
document.getElementById("unreadmentions").innerHTML = 0;
html = data.d.SocialFeed.Threads.results[0].Actors.results[0].StatusText;
if (html == null)
{document.getElementById("socialstatus").innerHTML = "No posts available";}
else
{
html = html.substring(0,30) + " ...";
document.getElementById("socialstatus").innerHTML = html;
}
}, error: function (data) {}
For the life of me I can not understand why that particular feed does not also return how many likes that post has recieved. Seems kind of silly that it wouldnt.
Cheers for the help!

How to update a document using a rest service (extension library) in XPages

i am trying to update a specific document by using rest service control.
I have set up the control (documentJsonService, pathInfo, form name etc)
I know that i have to perform a post (patch) request to the url of the service followed by /unid/ (same way as i ve done to read the document using the same rest).
I have an input field and a button. I want to enter a value to the field, press the button and update a field in the document with the value. How can i do this request?
This is the js function i used in worklight to update a document in Domino:
function updateDoc(docId,newValue) {
var identity = Base64.encode("myDominoUsername:myDominoPassword");
path = "/Databases/Temp/dominoApp.nsf/BestRestTest.xsp/updateService/unid/"+docId;
var input = {
method : 'post',
returnedContentType : 'json',
headers:{
Authorization: "Basic "+"b4lzdD234GG3M6SdW1XI=" //base64 encoding of your //credentials, see above. The function Base64.encode can be found by googling about it in //js. So you replace this string with identity variable.
"X-HTTP-Method-Override":"PATCH",
"Content-Type":"application/json"
},
body: {
contentType: 'application/json; charset=utf-8',
content: JSON.stringify({"theField":newValue})
},
path : path
};
return WL.Server.invokeHttp(input);
}
Now on the Domino side i have added an extension library REST control (alternatively you can do it with Domino Data Service). The properties i ve added are:
pathInfo: whatever you want
service: documentJsonService
computeWithForm:true
defaultItems:true
formName:myformName
This is just client side javascript, so you can do it in a similar way from an XPage.

How to construct a REST API that takes an array of id's for the resources

I am building a REST API for my project. The API for getting a given user's INFO is:
api.com/users/[USER-ID]
I would like to also allow the client to pass in a list of user IDs. How can I construct the API so that it is RESTful and takes in a list of user ID's?
If you are passing all your parameters on the URL, then probably comma separated values would be the best choice. Then you would have an URL template like the following:
api.com/users?id=id1,id2,id3,id4,id5
api.com/users?id=id1,id2,id3,id4,id5
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
IMO, above calls does not looks RESTful, however these are quick and efficient workaround (y). But length of the URL is limited by webserver, eg tomcat.
RESTful attempt:
POST http://example.com/api/batchtask
[
{
method : "GET",
headers : [..],
url : "/users/id1"
},
{
method : "GET",
headers : [..],
url : "/users/id2"
}
]
Server will reply URI of newly created batchtask resource.
201 Created
Location: "http://example.com/api/batchtask/1254"
Now client can fetch batch response or task progress by polling
GET http://example.com/api/batchtask/1254
This is how others attempted to solve this issue:
Google Drive
Facebook
Microsoft
Subbu Allamaraju
I find another way of doing the same thing by using #PathParam. Here is the code sample.
#GET
#Path("data/xml/{Ids}")
#Produces("application/xml")
public Object getData(#PathParam("zrssIds") String Ids)
{
System.out.println("zrssIds = " + Ids);
//Here you need to use String tokenizer to make the array from the string.
}
Call the service by using following url.
http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76
where
http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76
As much as I prefer this approach:-
api.com/users?id=id1,id2,id3,id4,id5
The correct way is
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
or
api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5
This is how rack does it. This is how php does it. This is how node does it as well...
There seems to be a few ways to achieve this. I'd like to offer how I solve it:
GET /users/<id>[,id,...]
It does have limitation on the amount of ids that can be specified because of URI-length limits - which I find a good thing as to avoid abuse of the endpoint.
I prefer to use path parameters for IDs and keep querystring params dedicated to filters. It maintains RESTful-ness by ensuring the document responding at the URI can still be considered a resource and could still be cached (although there are some hoops to jump to cache it effectively).
I'm interested in comments in my hunt for the ideal solution to this form :)
You can build a Rest API or a restful project using ASP.NET MVC and return data as a JSON.
An example controller function would be:
public JsonpResult GetUsers(string userIds)
{
var values = JsonConvert.DeserializeObject<List<int>>(userIds);
var users = _userRepository.GetAllUsersByIds(userIds);
var collection = users.Select(user => new { id = user.Id, fullname = user.FirstName +" "+ user.LastName });
var result = new { users = collection };
return this.Jsonp(result);
}
public IQueryable<User> GetAllUsersByIds(List<int> ids)
{
return _db.Users.Where(c=> ids.Contains(c.Id));
}
Then you just call the GetUsers function via a regular AJAX function supplying the array of Ids(in this case I am using jQuery stringify to send the array as string and dematerialize it back in the controller but you can just send the array of ints and receive it as an array of int's in the controller). I've build an entire Restful API using ASP.NET MVC that returns the data as cross domain json and that can be used from any app. That of course if you can use ASP.NET MVC.
function GetUsers()
{
var link = '<%= ResolveUrl("~")%>users?callback=?';
var userIds = [];
$('#multiselect :selected').each(function (i, selected) {
userIds[i] = $(selected).val();
});
$.ajax({
url: link,
traditional: true,
data: { 'userIds': JSON.stringify(userIds) },
dataType: "jsonp",
jsonpCallback: "refreshUsers"
});
}