Change “Access Request Settings” via REST in SharePoint

  jQuery.ajax({
    url: “https://<yoursite>/sites/<yourSite>/ABCteamSite/_api/web”,
    type: “POST”,
    data: JSON.stringify({‘__metadata’:  {‘type’: ‘SP.Web’ },’Description’: ‘ABCteamSite’,’RequestAccessEmail’: ‘<youraddress>@gmail.com’}),
    headers: {
        “accept”: “application/json; odata=verbose”,
        “content-type”:”application/json;odata=verbose”,
        “X-RequestDigest”: jQuery(“#__REQUESTDIGEST”).val(),
        “X-HTTP-Method”: “MERGE”
    }
   }).done(function (data) {
    console.log(“Done”);
 
}).fail(function (error) {
   console.log(“failed”);
   });

Creating random value via REST API

lastDigYear = Math.floor((Math.random() * 6) + 1);
lastDigMonth = Math.floor((Math.random() * 8) + 1);
AllDigDay = Math.floor((Math.random() * 15) + 1);

TolastDigYear = lastDigYear + 1;
TolastDigMonth = lastDigMonth + 1;
ToAllDigDay = AllDigDay + 3;


var data2 = {
            __metadata: { ‘type’: ‘SP.Data.Form70ListItem’ },
           Title: ‘Please provide title here’,
           ReportingPeriodFrom: ‘201’+lastDigYear.toString()+’-0’+lastDigMonth.toString()+’-‘+AllDigDay.toString()+’T15:18:21.135Z’,
           ReportingPeriodTo: ‘201’+TolastDigYear.toString()+’-0’+TolastDigMonth.toString()+’-‘+ToAllDigDay.toString()+’T15:18:21.135Z’,
           PartSources: Math.floor((Math.random() * 100) + 1),
           ActivePermits: Math.floor((Math.random() * 100) + 1),
           InitialPermitsPeriod: Math.floor((Math.random() * 100) + 1),
           InitialPermits18Months: Math.floor((Math.random() * 100) + 1),
           RegionId: Math.floor((Math.random() * 10) + 1),
           PermitAuthId: Math.floor(Math.random()*(158-42+1)+42),        
           OutstandingInitialApps: Math.floor((Math.random() * 100) + 1),
           OutstandingRenewalPermits: Math.floor((Math.random() * 100) + 1),
           SignificantModPeriod: Math.floor((Math.random() * 100) + 1),
           SignificantMods18Months: Math.floor((Math.random() * 100) + 1),
           OutstandingSignficantMods: Math.floor((Math.random() * 100) + 1),
           Form70comments: ‘Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden’,
      };

$.ajax({
    url: “/_api/web/lists/GetByTitle(‘Form70’)/items”,
    type: “POST”,
    data: JSON.stringify(data2),
    headers: {
        “X-RequestDigest”: $(“#__REQUESTDIGEST”).val(),
        “accept”: “application/json; odata=verbose”,
        “content-type”: “application/json;odata=verbose”
    }
}).done(function () {
    console.log(“Done”);
}).fail(function () {
    console.log(“FaiL”);
});

REST API roledefinitions

jQuery.ajax({
    url: “https://usepa.sharepoint.com/sites/OAR_Custom/_api/web/roledefinitions“,
    type: “GET”,
    headers: {
        “accept”:”application/json;odata=verbose”
        }
   }).done(function (data) {
    console.log(“Done”);
    jQuery.each( data.d.results, function( key, value ) {
  console.log(value.PrincipalId);
});
}).fail(function (error) {
    console.log(error);
});

Adding Multiple value to lookup field via REST

             var itemProperties = {
                ‘__metadata’: { “type”: “SP.Data.QuestionsListItem” },
                ‘AnsChoicesId’: { “results”: [1,3] }  //multi-valued User field value 
            };

            $.ajax({

                url: appweburl + “/_api/web/lists/GetByTitle(‘ListTitleGoesHere’)/items(“+ListItem+”)”,
                type: “MERGE”,
                data: JSON.stringify(itemProperties),
                headers: {
                    “X-RequestDigest”: $(“#__REQUESTDIGEST”).val(),
                    “accept”: “application/json; odata=verbose”,
                    “If-Match”: “*”,
                    “content-type”: “application/json;odata=verbose”
                }
            }).done(function () {
                console.log(“Done”);
            }).fail(function () {
                console.log(“FaiL”);
            });


In the above code all of the array items will be replaced with the item ID’s specified. 

//code coming soon

Here is what adding Multiple values looks like in JSOM (This example is create a new record, not updating a record)

var clientContext = SP.ClientContext.get_current();
            var oList = clientContext.get_web().get_lists().getByTitle(‘ListTitleGoesHere’);
            var itemCreateInfo = new SP.ListItemCreationInformation();
            oListItem = oList.addItem(itemCreateInfo);
            oListItem.set_item(‘Title’, ‘HelloThisStuffWorld’);
            var lookupsIds = [1, 2, 3];
            var lookups = [];
            for (var ii in lookupsIds) {
                var lookupValue = new SP.FieldLookupValue();
                lookupValue.set_lookupId(lookupsIds[ii]);
                lookups.push(lookupValue);
            }
            oListItem.set_item(‘AnsChoices’, lookups);
            oListItem.update();
            clientContext.load(oListItem);
            clientContext.executeQueryAsync(
         function () { alert(“Success!”) },
         function () { alert(“Request failed”) }

        );

Office 365: Uploading a file to SharePoint Online using JSOM and REST

Get the Visual Studio files here

Here is the JavaScript:

‘use strict’;

jQuery(document).ready(function () {

    // Check for FileReader API (HTML5) support.
    if (!window.FileReader) {
        alert(‘This browser does not support the FileReader API.’);
    }
});

// Upload the file.
// You can upload files up to 2 GB with the REST API.
function uploadFile() {

    // Define the folder path for this example.
    var serverRelativeUrlToFolder = ‘/UploadRESTv2/Lists/shared_documents’;

    // Get test values from the file input and text input page controls.
    var fileInput = jQuery(‘#getFile’);
    var newName = jQuery(‘#displayName’).val();

    // Get the server URL.
    var serverUrl = _spPageContextInfo.webServerRelativeUrl;

    // Initiate method calls using jQuery promises.
    // Get the local file as an array buffer.
    var getFile = getFileBuffer();
    getFile.done(function (arrayBuffer) {

        // Add the file to the SharePoint folder.
        var addFile = addFileToFolder(arrayBuffer);
        addFile.done(function (file, status, xhr) {

            // Get the list item that corresponds to the uploaded file.
            var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
            getItem.done(function (listItem, status, xhr) {

                // Change the display name and title of the list item.
                var changeItem = updateListItem(listItem.d.__metadata);
                changeItem.done(function (data, status, xhr) {
                    alert(‘file uploaded and updated’);
                });
                changeItem.fail(onError);
            });
            getItem.fail(onError);
        });
        addFile.fail(onError);
    });
    getFile.fail(onError);

    // Get the local file as an array buffer.
    function getFileBuffer() {
        var deferred = jQuery.Deferred();
        var reader = new FileReader();
        reader.onloadend = function (e) {
            deferred.resolve(e.target.result);
        }
        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }
        reader.readAsArrayBuffer(fileInput[0].files[0]);
        return deferred.promise();
    }

    // Add the file to the file collection in the Shared Documents folder.
    function addFileToFolder(arrayBuffer) {

        // Get the file name from the file input control on the page.
        var parts = fileInput[0].value.split(‘\’);
        var fileName = parts[parts.length – 1];

        

        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
                “{0}/_api/web/getFolderByServerRelativeUrl(‘{1}’)/Files” +
                “/add(overwrite=true, url='{2}’)”,
                serverUrl, serverRelativeUrlToFolder, fileName);

        console.log(fileCollectionEndpoint);

        // Send the request and return the response.
        // This call returns the SharePoint file.
        return jQuery.ajax({
            url: fileCollectionEndpoint,
            type: “POST”,
            data: arrayBuffer,
            processData: false,
            headers: {
                “accept”: “application/json;odata=verbose”,
                “X-RequestDigest”: jQuery(“#__REQUESTDIGEST”).val(),
                “content-length”: arrayBuffer.byteLength
            }
        });
    }

    // Get the list item that corresponds to the file by calling the file’s ListItemAllFields property.
    function getListItem(fileListItemUri) {

        // Send the request and return the response.
        return jQuery.ajax({
            url: fileListItemUri,
            type: “GET”,
            headers: { “accept”: “application/json;odata=verbose” }
        });
    }

    // Change the display name and title of the list item.
    function updateListItem(itemMetadata) {

        // Define the list item changes. Use the FileLeafRef property to change the display name. 
        // For simplicity, also use the name as the title. 
        // The example gets the list item type from the item’s metadata, but you can also get it from the
        // ListItemEntityTypeFullName property of the list.
        var body = String.format(“{{‘__metadata’:{{‘type’:'{0}’}},’FileLeafRef’:'{1}’,’Title’:'{2}’}}”,
            itemMetadata.type, newName, newName);

        // Send the request and return the promise.
        // This call does not return response content from the server.
        return jQuery.ajax({
            url: itemMetadata.uri,
            type: “POST”,
            data: body,
            headers: {
                “X-RequestDigest”: jQuery(“#__REQUESTDIGEST”).val(),
                “content-type”: “application/json;odata=verbose”,
                “content-length”: body.length,
                “IF-MATCH”: itemMetadata.etag,
                “X-HTTP-Method”: “MERGE”
            }
        });
    }
}

// Display error messages. 
function onError(error) {
    alert(error.responseText);
}

SharePoint Designer 2013: Adding REST data source to data view web part

Audio Transcript:

Now we will discuss how to get data from a Rest Service and display that data on a page. We’ll do that by going to our data sources and selecting REST Service. In this scenario we, will use a RSS feed from a world news site. The URL we grab has a parameter in it, so we will add that parameter in the data source UI. Now we can save this data source and go to our SharePoint page and display the RSS feeds content. We’ll do this by adding a data view web part. Once, we have added the web part we can view our page in the browser and see the REST content. 

Upcoming topics include:

  • Styling data view web parts
  • Adding SOAP web services
  • Adding various other types of REST services
  • Using JavaScript in data view web parts
  • and using SharePoint Designer 2013 Workflows to call HTTP web services

SharePoint 2013 Get the host web list titles using the cross-domain library (REST)

Get the Visual Studio files
 
executor.executeAsync({
        url: appweburl + “/_api/SP.AppContextSite(@target)/web/lists?@target='”+hostweburl+”‘”,
        method: “GET”,
    headers: { “accept”: “application/json; odata=verbose” },
    success: successHandler,
    error: errorHandler
});
}
function successHandler(data) {
    var jsonObject = JSON.parse(data.body);

    $.each(jsonObject.d.results, function (i, item) {
        document.getElementById(“HostwebTitle”).innerHTML +=
         “<b>” + item.Title + “</b><br />”;
    });
}

SharePoint 2013 Get the host web title using the cross-domain library (REST)

Get the Visual Studio files

executor.executeAsync(
        {
            url:
                appweburl +
                “/_api/SP.AppContextSite(@target)/web/title?@target='” +
                hostweburl + “‘”,
            method: “GET”,
            headers: { “Accept”: “application/json; odata=verbose” },
            success: successHandler,
            error: errorHandler
        }
    );


Moving a site via .wsp that has a published InfoPath 2010 form associated with it

Moving a site via .wsp that has a published InfoPath 2010 form associated with it. Here is the scenario: I have one document library that contains an .xlsx file. That file contains data that is queried via REST for and InfoPath 2010 form (more on how to do that) The InfoPath form template is contained within the “Form Temp” form library. Needless to say a simple scenario. As everyone might know when you are creating data connections in InfoPath 2010 you are only allowed to use absolute URLs. This raises the question “Will moving the site or form break the data connections?” Well I wanted to test the moving the entire site by “Saving ste as template” and then restore the .wsp to another site collection. Good news, it worked beautifully. The absolute URLs are changed automatically.

One problem did come up. When I tried to upload the .wsp to a SharePoint Online site I got an error

Moving a InfoPath 2010 .xsn template to a different SharePoint 2010 server

You might encounter a scenario where your are moving a InfoPath 2010 .xsn template to a different server. Because all data connections in InfoPath require an absolute URL you might get nervous about moving a .xsn template. Not to worry. When you re-publish the .xsn to a different server you get the option to automatically change all data connection URLs.

Related posts: