Tuesday, January 26, 2016

SharePoint JavaScript - Basic Operations (Visual WebPart-SandBox)

SharePoint JavaScript - Basic Operations (Visual WebPart-SandBox)
                            
<script type="text/javascript"  src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script type="text/javascript"  src="/_layouts/15/sp.runtime.js"> </script>
<script type="text/javascript"  src="/_layouts/15/sp.js"> </script>

<style type="text/css">
     .myBlocks{
         display:inline-block;
         border: 1px solid blue;
         width:245px;
     }
     .myControls{
         display: inline-grid;
         border-bottom-color:red;        
         width:229px;
     }

</style>
<div><h2>Welcome to JSON with JQuery</h2></div>
<div id="resulFolder"></div>
<div class="myBlocks">
    <input type="button" value="Get all list in a site" onclick="allLists();" class="myControls" />
    <input type="button" value="Get lists/Fileds and apply filters" onclick="applyFilters();" class="myControls"/>
    <input type="button" value="String Contains" onclick="checkContains();" class="myControls"/>
    <input type="button" value="Create SPList" onclick="createSpList();"  class="myControls" />

<input type="button" value="Create Folder" onclick="createFolder();" class="myControls" />
</div>
<script type="text/javascript">

    var siteUrl = "http://rku:1111/sites/dev";
    var ctx = new SP.ClientContext(siteUrl);
    var oWebsite = ctx.get_web();

    function allLists() {
       
        this.oListColl = oWebsite.get_lists();
        ctx.load(oListColl, 'Include(Title,Id)');
       
        ctx.executeQueryAsync(
            Function.createDelegate(this, this.onQuerySucceeded),
            Function.createDelegate(this, this.onQueryFailed)
            );
    }

    function onQuerySucceeded() {
        var listInfo = '';
        var listEnumerator = oListColl.getEnumerator();
        var a = 1;
        while (listEnumerator.moveNext()) {
            var oList = listEnumerator.get_current();
            //listInfo += 'Title: ' + oList.get_title() + '--' + ' ID: ' + oList.get_id().toString() + '\n';
            listInfo += a.toString() + '-->  Title: ' + oList.get_title() + '\n';
            a++;
        }
        alert(listInfo);
    }

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

    }

    function applyFilters() {

        var oListColl = oWebsite.get_lists();

        this.listInfoArray = ctx.loadQuery(oListColl, 'Include(Title,Fields.Include(Title,InternalName))');
        ctx.executeQueryAsync(
            Function.createDelegate(this, this.onQuerySucceededLists),
            Function.createDelegate(this, this.onQueryFailed)
            );
    }

    function onQuerySucceededLists(sender, args) {
        var infoLists = '';
      
        for (var i = 0; i < 3 ; i++) { //this.listInfoArray.length
            var oList = this.listInfoArray[i];
            var oFieldColl = oList.get_fields();
            var fieldEnumerator = oFieldColl.getEnumerator();
            var a = 1;
            while (fieldEnumerator.moveNext())
            {
                var oField = fieldEnumerator.get_current();
                var regEx = new RegExp('name', 'ig');

                if (regEx.test(oField.get_internalName())) {
                    infoLists += '\nList: ' + oList.get_title() +
                        '\n\tField Title: ' + oField.get_title() +
                        '\n\tField Name: ' + oField.get_internalName();
                }
            }          
          
        }
        alert(infoLists);
    }

    function checkContains() {

        var charString = "Hyderabad is a beautiful city";
        var regExp = new RegExp("beauti");
        if (regExp.test(charString.toString()))
        {
            alert('True')
        }
              
        var regExp = new RegExp("beda");
        if (regExp.test(charString.toString())) {
            alert('True city')
        }
        else {
            alert('false');
        }
    }

   function createSpList() {
        var listCInfo = new SP.ListCreationInformation();
        listCInfo.set_title('MyList');
        listCInfo.set_templateType(SP.ListTemplateType.genericList);
        //Create ListCreationInformation object & pass this object to the add(parameters) function of the ListCollection object
        this.oList = oWebsite.get_lists().add(listCInfo);

        ctx.load(this.oList);
        ctx.executeQueryAsync(
            Function.createDelegate(this, this.onQuerySucceededListCreation),
            Function.createDelegate(this, this.onQueryFailed)
            );
    }

    function onQuerySucceededListCreation(){       
       alert(this.oList.get_title() + ': Created Successfully.');

    }


function createFolder() {
        var ctx = new SP.ClientContext.get_current();
        var oList = ctx.get_web().get_lists().getByTitle("Documents")
        var itemCreatInfo = new SP.ListItemCreationInformation();
        itemCreatInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);
        itemCreatInfo.set_leafName("CreatedWith JSON1");
        this.oListItem = oList.addItem(itemCreatInfo);
        this.oListItem.update();

        ctx.load(this.oListItem);
      
        ctx.executeQueryAsync(
            Function.createDelegate(this,SuccessHandler),
            Function.createDelegate(this, errorHandler)
            );

        function SuccessHandler() {
            $get('resulFolder').innerHTML = "Go to the " + "<a href='../Shared Documents'> Document Library </a>" + "To see your folder";
          }

        function errorHandler() {
            $get('resulFolder').innerHTML =
                "Request failed: " + arguments[1].get_message();
        }


    }
 

</script>



Upload File
<input id="inputFile" type="file" >
<input id="uploadDocumentButton" type="Button" value="Upload Document">

$("#uploadDocumentButton").click(function () {
    if (document.getElementById("inputFile").files.length === 0) {
        alert("Select a file!");
        return;
    }
    var parts = document.getElementById("inputFile").value.split("\\");
    var filename = parts[parts.length - 1];
    var file = document.getElementById("inputFile").files[0];
    uploadFile("ListName", "1", filename, file);                     
});


function uploadFile(listName, listId, fileName, file){
        uploadFileSP(listName, listId, fileName, file)
               .then(                 
                   function (files) {                
                       alert("Uploaded successfully");                      
                   },                 
                   function (sender, args) {                 
                       alert(args.get_message());                    
                   }                  
               );             
}

function getFileBuffer(file){
        var deferred = $.Deferred();
        var reader = new FileReader();
        reader.onload = function(e){
               deferred.resolve(e.target.result);
        }
        reader.onerror = function(e){
               deferred.reject(e.target.error);
        }
        reader.readAsArrayBuffer(file);
        return deferred.promise();
}

function uploadFileSP(listName, id, fileName, file){
        var deferred = $.Deferred();
        getFileBuffer(file).then(
               function(buffer){
                       var bytes = new Uint8Array(buffer);
                       var content = new SP.Base64EncodedByteArray();
                       var binary = '';
                       for(var b=0; b<bytes.length; b++){
                               binary += String.fromCharCode(bytes[b]);                       
                       }
                       var scriptbase = _spPageContextInfo.webServerRelativeUrl+ "/_layouts/15/";
 
                       $.getScript(scriptbase + "SP.RequestExecutor.js", function(){
                               var createitem = new SP.RequestExecutor("https://SharePointURL/SiteCollectionUrl");
                           createitem.executeAsync({
                               url: "/SiteCollectionUrl/_api/web/lists/GetByTitle('"+listName+"')/items("+id+")/AttachmentFiles/add(FileName='" + file.name + "')",
                               method: "POST",
                               binaryStringRequestBody: true,
                               body: binary,
                               success: fsucc,
                               error: ferr,
                               state: "Update"
                           });
                        
                           function fsucc(data) {
                               alert('success');
                           }
                        
                           function ferr(data) {
                               alert('error\n\n' + data.statusText + "\n\n" + data.responseText);
                           }
                       });     
               },
               function(err){
                       deferred.reject(err);
               }
        );
        return deferred.promise();
}


function fsucc(data) {
        alert('success');
}
        
function ferr(data) {
        alert('error\n\n' + data.statusText + "\n\n" + data.responseText);
}















No comments:

Post a Comment