Showing posts with label CSOM. Show all posts
Showing posts with label CSOM. Show all posts

Friday, 1 July 2016

SharePoint 2013 - Upload a file with metadata using javascript CSOM

Uploading a file using javscript is possible using sharepoint 2013 API and HTML 5 supported javascript FileReader object but there are some cases where we need add metadata also along with file.

Here I'm showing how to upload file with Metadata/Fields in a Document Library.

function CreateFile()
{
    //ensure file selection
    if ( document.getElementById("fupUpload").files.length === 0) {
        alert('No file was selected');
        return;
    }
    else{
       // Ensure the HTML5 FileReader API is supported
   if (window.FileReader)
   {
       input = document.getElementById("fupUpload");
       
       if (input)
       {
           file = input.files[0];      
   fr = new FileReader();
           fr.onload = receivedBinary;
           fr.readAsDataURL(file);
       }
   }
   else
   {
       alert("The HTML5 FileSystem APIs are not fully supported in this browser.");
   }
}

}

// Callback function for onload event of FileReader
function receivedBinary()
{
    // Get the ClientContext for the app web
    var clientContext = new SP.ClientContext.get_current();
    
    //get lib from its name
    var parentList = clientContext.get_web().get_lists().getByTitle("Documents");

    //File Object
    var fileCreateInfo = new SP.FileCreationInformation();

    //set file properties
    fileCreateInfo.set_url(file.name);
    fileCreateInfo.set_overwrite(true);
    fileCreateInfo.set_content(new SP.Base64EncodedByteArray());

    // Read the binary contents of the base 64 data URL into a Uint8Array
    // Append the contents of this array to the SP.FileCreationInformation
    var arr = convertDataURIToBinary(this.result);
    
    for (var i = 0; i < arr.length; ++i)
    {
        fileCreateInfo.get_content().append(arr[i]);
    }

    // Upload the file to the root folder of the document library
    newFile = parentList.get_rootFolder().get_files().add(fileCreateInfo);
 
    //file MetaData
    var oListItem = newFile.get_listItemAllFields();
    
    //set item properties
    oListItem.set_item('Description0',"Some text");
    
    //Lookup Column
    var depValue = new SP.FieldLookupValue();
depValue.set_lookupId("1");
oListItem.set_item('Department', depValue);
    
    //update item
    oListItem.update();

    //load and execute query
    clientContext.load( newFile );
    clientContext.executeQueryAsync( onSuccess, onQueryFailed );
}

function onSuccess(){
alert('File added successfully');
location.reload();
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

// Utility function to remove base64 URL prefix and store base64-encoded string in a Uint8Array
// Courtesy: https://gist.github.com/borismus/1032746
function convertDataURIToBinary(dataURI)
{
    var BASE64_MARKER = ';base64,';
    var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
    var base64 = dataURI.substring(base64Index);
    var raw = window.atob(base64);
    var rawLength = raw.length;
    var array = new Uint8Array(new ArrayBuffer(rawLength));

    for (i = 0; i < rawLength; i++)
    {
        array[i] = raw.charCodeAt(i);
    }
    return array;
}




Note: Browser should be HTML 5 supported.


Wednesday, 4 September 2013

Sharepoint 2013 - Get SP List Title, ID, RelativeURL using CSOM

There may be some condition where we need to get SP List properties like ID, relative URL.

Following is the CSOM code to get SP List properties.

<script type="text/javascript">

var list;
var listRootFolder;
ExecuteOrDelayUntilScriptLoaded(init, "sp.js");

function init() {

    //load site
   var currentcontext = new SP.ClientContext.get_current();
   list = currentcontext.get_web().get_lists().getByTitle('LIST_NAME');
   listRootFolder= list.get_rootFolder();

    currentcontext.load(list, 'Title', 'Id');
    currentcontext.load(listRootFolder);
    currentcontext.executeQueryAsync(Function.createDelegate(this, result), Function.createDelegate(this, oncListQueryFailed));
}

function result() {
var listID = list.get_id();
    var listName= list.get_title();
var listURL = listRootFolder.get_serverRelativeUrl();
alert(listID + listName + listURL);
}

function oncListQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }

</script>


Check all the properties for SP List.

Saturday, 1 June 2013

Sharepoint 2013 - Get all Site templates using Client object model

Code to get all site templates both inbuilt and custom site template ID using CSOM.


var templateCollection ;
function GetWebTemplates()
{

var context = new SP.ClientContext.get_current();
var web = context.get_web();

templateCollection = web.getAvailableWebTemplates(1033, false);

context.load(templateCollection);
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}

function success() {

var Templates = "";
var siteTemplatesEnum = templateCollection.getEnumerator();

while(siteTemplatesEnum.moveNext())
{
var siteTemplate = siteTemplatesEnum.get_current();
Templates +=  siteTemplate.get_name() +   ',';
}

alert("Site Templates - " + ',' + Templates);
}

function failed(sender, args) {
alert("Failed");
}


While you can get all the inbuilt site template ID from below link

And custom site template would have a format like this.
{GUID}#TemplateName

Sharepoint 2013 - Create a site from a custom site-template using client object model

Here, is the code to create a site from a custom site-template using CSOM.

function CreateSite() {

        //load site
   var currentcontext = new SP.ClientContext.get_current();
   var currentweb = currentcontext.get_web();
   //site object
   var webCreateInfo = new SP.WebCreationInformation();
   //set values
   webCreateInfo.set_description("This site is created from CSOM");
   webCreateInfo.set_language(1033);
   webCreateInfo.set_title("My Title");
   webCreateInfo.set_url("/myURL");
   webCreateInfo.set_useSamePermissionsAsParentSite(true);
   webCreateInfo.set_webTemplate("MyTemplateID");
   //add sub site
   this.NewWebsite = this.currentweb.get_webs().add(webCreateInfo);
   //Load and execute query
   currentcontext.load(this.NewWebsite, 'ServerRelativeUrl', 'Created');
   currentcontext.executeQueryAsync(Function.createDelegate(this, this.Success), Function.createDelegate(this, this.oncListQueryFailed));    
}

function Success() {
alert(this.NewWebsite.get_serverRelativeUrl());
}

function oncListQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


Template ID is the most important thing here.It defines what is the type of site we are creating like would it be a Team Site,Blank Site, Wiki, Blog etc.
We can find all default template ID from here 
https://www.nothingbutsharepoint.com/sites/devwiki/sp2010dev/pages/site%20templates%20in%20sharepoint%202010.aspx

But , since here we are using our own custom site template . So we can get our template id from the code given in this blog.

Get web-template


Your custom site template id would  be in this format.
{GUID}#TemplateName

Monday, 27 May 2013

Sharepoint 2013 - Create a SP Group using CSOM javascript

In this example we will get to know how to create and assign permission to a SP Group using CSOM - client object model in javascript.

//Sample - http://msdn.microsoft.com/en-us/library/jj246414.aspx
function createSPGroups()
{
//Load new Site
   var currentCTX = new SP.ClientContext();
   var currentWEB  = currentCTX.get_web();

   //Get all groups in site
   var groupCollection = currentWEB.get_siteGroups();

   // Create Group information for Group
var membersGRP = new SP.GroupCreationInformation();
membersGRP.set_title('Group Name');
membersGRP.set_description('Use this group to grant people contribute permissions to the SharePoint site: ');


//add group
oMembersGRP = currentWEB.get_siteGroups().add(membersGRP);

//Get Role Definition by name (http://msdn.microsoft.com/en-us/library/jj246687.aspx)
//return SP.RoleDefinition object
var rdContribute = currentWEB.get_roleDefinitions().getByName('Contribute');

// Create a new RoleDefinitionBindingCollection.
        var collContribute = SP.RoleDefinitionBindingCollection.newObject(currentCTX);
     
        // Add the role to the collection.
        collContribute.add(rdContribute);

// Get the RoleAssignmentCollection for the target web.
        var assignments = currentWEB.get_roleAssignments();
     
 // assign the group to the new RoleDefinitionBindingCollection.
var roleAssignmentContribute = assignments.add(oMembersGRP, collContribute);

currentCTX.load(oMembersGRP);

//Execute Query
currentCTX.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

        function onQuerySucceeded() {
            alert("Done");
        }

        function onQueryFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }

Here, I my assigning a predefined permission level i.e. Contribute to the group.We can create our own custom permission level and assign to the group.Creating custom permission level will be discussed in upcoming blogs.

Saturday, 25 May 2013

Sharepoint 2013 - Add SP User to a SP Group using CSOM - javascript

In many scenarios we want to add a SP user to a group in Sharepoint.

Since, in SP 2013 client object model is very rich we can very much do all the stuff using CSOM.

Here, i m describing a use case to add a SP User to a SP Group using javascript.

Below is the javascript code:

var user;
var visitorsGroup;

function AddUsers()
{
//Load Current Site
var clientContext = new SP.ClientContext();

//Get all groups in site
var groupCollection = clientContext.get_web().get_siteGroups();
      
// Get the group by name
visitorsGroup = groupCollection.getByName('Approvers');
      
//ensure SP User
var usr2 = clientContext.get_web().ensureUser('domain\\loginname');
      
//Get all SP Users in SP Group
var userCollection = visitorsGroup.get_users();
      
//Add User to Group
var oUSR2 = userCollection.addUser(usr2);

//Load data
clientContext.load(oUSR2); clientContext.load(userCollection);  
      
//Execute Query
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed)); 
        }

        function onQuerySucceeded() {
            alert("Done");
        }

        function onQueryFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }

Friday, 17 May 2013

Get Full Site and Page URL in sharepoint using javascript or client object model

In many cases we want the page to redirect to new page in sharepoint using javascript.

So, the first thing which we need to understand is to get site collection URL like (http://www.contoso.com)

Then after we can get the current page relative URL.

The below code gives you the details how to achieve this.

var SiteCol_URL = window.location.protocol + '//' + window.location.host;

var currentcontext;

This will give you the site collection URL like (http://www.contoso.com)

After then if you want to get current page URL using client object model , here is the code

function GetCurrentPageURL() {


    currentcontext = new SP.ClientContext.get_current();


    currentcontext.executeQueryAsync(Function.createDelegate(this, this.OnSuccess), 

Function.createDelegate(this, this.oncListQueryFailed));}


function OnSuccess() {   var PageURL= SiteCol_URL + currentcontext.get_url(); }


 currentcontext.get_url()  contains that page relative URL like (/sitespages/page1.aspx)


So, this way u can get full page URL and also site collection URL