Monday 26 August 2013

In sharepoint 2013 page layout when we used decodeuricomponent for search query string, return value is displaying only up to first index of the special character. Same code working fine when used in sitepage.

Here for fix actually we should use encodeuricomponent, mitakenly i used decodeuri which is not required.

Sunday 25 August 2013

 how to add the site url to a page layout and master pages.



The project property web control looks like:
<SharePoint:ProjectProperty Property="Title" runat="server"/>
The Property attribute takes the following values:
Name
Description
BlogCategoryTitle
Category of the current post
BlogPostTitle
Title of the current post
Description
Description of the current site (SPWeb)
RecycleBinEnabled
Returns 1 (recycle bin enabled) or 0 (recycle bin disabled)
SiteOwnerName
User name of the owner for the current site collection
SiteUrl
Url of the current site collection (SPSite)
Title
Title of the current site (SPWeb)
Url
URL of the current site (SPWeb)
   
Example:
Title: <SharePoint:ProjectProperty Property="Title" runat="server"/><br>
Description: <SharePoint:ProjectProperty Property="Description" runat="server"/><br>
RecycleBinEnabled: <SharePoint:ProjectProperty Property="RecycleBinEnabled" runat="server"/><br>
SiteOwnerName: <SharePoint:ProjectProperty Property="SiteOwnerName" runat="server"/><br>
SiteUrl: <SharePoint:ProjectProperty Property="SiteUrl" runat="server"/><br>
Url: <SharePoint:ProjectProperty Property="Url" runat="server"/><br>

Script Tags:
<script type="text/javascript" src='<asp:Literal runat="server" 
               Text="<% $SPUrl:~Site/appBin/js/jquery.min.js %>" />'></script>
<link rel="stylesheet" type="text/css" 
       href="<% $SPUrl:~Site/appBin/css/jquery-ui.css %>" />



Javascript code execution time.


var start = new Date().getTime();
//your code here.
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);

Wednesday 21 August 2013


Get Sharepoint List Base Template ID using javascript.




var siteUrl = '/ClientGNH/New%20ProjectTemplate';
var title = ""; // List name
function retrieveSpecificListProperties() {

    var clientContext = new SP.ClientContext(siteUrl);
    var oWebsite = clientContext.get_web();
    this.collList = oWebsite.get_lists().getByTitle(title);
    clientContext.load(collList);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

}
function onQuerySucceeded() {

    var listInfo = ''+collList.get_title() +'\n'+ collList.get_baseTemplate();  
    alert(listInfo);
}

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

retrieveSpecificListProperties();
Validate fields

<script type="text/javascript" language = "javascript">
var ck_name = /^[A-Za-z0-9 ]{2,30}$/;
var errors = [];
var isValid;
function ValidateFields()
{
var name = jQuery("#FolderNameTextBox").val().trim();
if( 2 > name.lenght || name.lenght > 30)
{
errors[errors.length] = "Please provide name less than 30 charecters"+"\n";
}
if (!ck_name.test(name))
{
errors[errors.length] = "Please provide valid name." +"\n";
}
if(errors.length > 0)
{
reportErrors(errors);
isValid = false;
}
else
{
isValid = true;
}

}
function reportErrors(errors){
var msg = "Please enter valide data. \n";
for (var i = 0; i<errors.length; i++)
{
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
errors.length = 0;
}
</script>

Create Cookie and Delete old cookie using javascript


function SetCookie(id,text)
    {
createCookie("ClientActiveTab","",-1);
createCookie("ClientSelectedTab","",-1);
           var date = new Date();
createCookie("ClientActiveTab",id,1);
createCookie("ClientSelectedTab",text,1);
getSelectedTabFiles(text);
    }
function createCookie(name,value,time)
{
if (time) {
        var date = new Date();
        date.setTime(date.getTime()+(time*24*60*60*1000)); // day 24 hrs
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

Monday 19 August 2013

Update/Edit List title using Javascript Sharepoint.


var oList="";
var Listname="Document Sharing";
var NewTitle="Sharing Documents";
function updateList() {
    var clientContext = new SP.ClientContext.get_current();
    var oWebsite = clientContext.get_web();
    oList = clientContext.get_web().get_lists().getByTitle(Listname);
   this.oList.set_title(NewTitle);
oList.update();
    clientContext.load(oList);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    var result ="List title updated to"+ oList.get_title() + '.';
    alert(result);
}

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

updateList("Test");

Tuesday 13 August 2013

Get Sharepoint site Title Using ECMA script



var siteUrl = '/ProjectTemplate';
   
function retrieveWebSite() {
    var clientContext = new SP.ClientContext(siteUrl);
    this.oWebsite = clientContext.get_web();

    clientContext.load(this.oWebsite);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
    alert('Title: ' + this.oWebsite.get_title() + ' Decription: ' + this.oWebsite.get_description());
}
   
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
retrieveWebSite();

Check out Page using SpServices.



function getGMTDate(){
var myDate = new Date();
var month = myDate.getMonth()+1;
var gmtdate = myDate.getDate()+' '+month+' '+myDate.getFullYear();
gmtdate = gmtdate +' '+ myDate.getHours()+':'+myDate.getUTCMinutes()+':'+myDate.getSeconds()+' GMT';
return gmtdate;
}

function CheckOutPage(bookURL,date) {
jQuery().SPServices({
operation: "CheckOutFile",
pageUrl: bookURL,
checkoutToLocal: "false",
lastmodified: "4 Jul 2013 3:15:00 GMT" });

}

Get date In GMT Format using javascript


function getGMTDate(){
var myDate = new Date();
var month = myDate.getMonth()+1;
var gmtdate = myDate.getDate()+' '+month+' '+myDate.getFullYear();
gmtdate = gmtdate +' '+ myDate.getHours()+':'+myDate.getUTCMinutes()+':'+myDate.getSeconds()+' GMT';
return gmtdate;
}

Modal Dialog With Custom Code.




<script type="text/javascript" >
ShowNewFolderModalPopUp();
function ShowNewFolderModalPopUp()
{

var options = SP.UI.$create_DialogOptions();
options.title = "Enter folder name";
options.autosize = true;
options.html =  createFolderDialogElement();
options.showClose= true;
options.allowMaximize = false;
options.dialogReturnValueCallback = FolderNewCallback;
SP.UI.ModalDialog.showModalDialog(options);
}

function createFolderDialogElement() {      
        var dialogElement = jQuery(jQuery('#DialogMarkup').html());
dialogElement.find('#cancelButton').on('click', function() {
        SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, jQuery('#FolderNameTextBox').val());
        });
        dialogElement.find('#SubmitButton').on('click', function() {
        SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, jQuery('#FolderNameTextBox').val());
        });      
        return dialogElement.get(0);
    }

function FolderNewCallback(dialogResult, returnValue) {
       
        if(dialogResult == SP.UI.DialogResult.OK && returnValue) {
if(returnValue != '')
{
SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
}
        }
if(dialogResult == SP.UI.DialogResult.cancel) {

        }
    }
</script>

<script type="text/html" id="DialogMarkup">
    <div>
        <label for="FolderNameTextBox">Enter Folder Name :</label>
        <input type="text" id="FolderNameTextBox"/><br><br>
        <input type="button" id="SubmitButton" value="Submit"/>&nbsp; &nbsp;
<input type="button" id="cancelButton" value="Cancel"/>
    </div>
</script>

Monday 12 August 2013

Delete SharePoint List or Document Library.


var Title = "TestsDelete";
function deleteList(Title) {
    var clientContext = new SP.ClientContext.get_current();
    var oWebsite = clientContext.get_web();  

    this.oList = oWebsite.get_lists().getByTitle(Title);
    oList.deleteObject();

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    alert(Title  + ' deleted.';);
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() );
}
 deleteList(Title ) ;

Sunday 11 August 2013

Get Current Site Display name using SPServices


function GetCurrentSiteDisplayName(){
jQuery().SPServices({
    operation: "SiteDataGetWeb",
    async: false,
completefunc: function (xData, Status) {
siteTitle = jQuery(xData.responseXML).SPFilterNode("Title").text();
}
});
}

Grey out image using css.

.greyout {
-webkit-filter: grayscale(100%);
       -moz-filter: grayscale(100%);
         -o-filter: grayscale(100%);
        -ms-filter: grayscale(100%);
            filter: grayscale(100%); 

Saturday 10 August 2013


Create Treeview of Current site All Lists and their Folders.


function retrieveAllFolders(listname, ulElement) {

    $().SPServices({
        operation: "GetListItems",
        listName: listname,
        CAMLQuery: '<Query><OrderBy><FieldRef Name="Modified"
Ascending="True" /></OrderBy></Query>',
        CAMLQueryOptions: '<QueryOptions><ViewAttributes
Scope="RecursiveAll"/></QueryOptions>',
        completefunc: function (xData, Status) {

            $(xData.responseXML).find("[nodeName='z:row']").each(function () {
                var thisFSObjType =
$(this).attr("ows_FSObjType").split(";#")[1];

                if (thisFSObjType == 1) {

                    var leafRef = $(this).attr("ows_FileRef").toLowerCase();
                    var nodename =
$(this).attr("ows_LinkFilename").toLowerCase();


                    if (leafRef.endsWith(("/" + listname + "/" +
nodename).toLowerCase())) {

                        var childULElement = document.createElement("ul");
                        childULElement.setAttribute("id",
updateID("pare_" + nodename));

                        var liElement = document.createElement("li");
                        liElement.setAttribute("id",
updateID("listname_" + nodename));


                        var textNode = document.createTextNode(nodename);
                        var anchorElement = document.createElement("a");
                        anchorElement.setAttribute("class", "anchorStyle");
                        anchorElement.appendChild(textNode);
                        $(anchorElement).click(toggleExpandCollapse);
                        anchorElement.setAttribute("href", "#");

                        liElement.setAttribute("class", "collapse");
                        liElement.appendChild(anchorElement);
                        liElement.appendChild(childULElement);
                        ulElement.appendChild(liElement);
                    }
                    else {

                        var leafRef = $(this).attr("ows_FileRef").toLowerCase();

                        var actualPath =
leafRef.substring(leafRef.indexOf(listname) + listname.length + 1);
                        var parent = actualPath.substring(0,
actualPath.lastIndexOf("/"));
                        parent = parent.replace("/", "_");
                        var nodeID = actualPath.replace("/", "_");

                        var parentElement =
document.getElementById(updateID("pare_" + parent));

                        var childULElement = document.createElement("ul");
                        childULElement.setAttribute("id",
updateID("pare_" + nodeID));
                        var liElement = document.createElement("li");
                        liElement.setAttribute("class", "collapse");
                        liElement.setAttribute("id", updateID(listname
+ "_parent_" + nodename));
                        var anchorElement = document.createElement("a");
                        anchorElement.setAttribute("class", "anchorStyle");

                        var textNode = document.createTextNode(nodename);
                        anchorElement.appendChild(textNode);
                        anchorElement.setAttribute("href", "#");
                        $(anchorElement).click(toggleExpandCollapse);
                        liElement.appendChild(anchorElement);
                        liElement.appendChild(childULElement);
                        liElement.click(toggleExpandCollapse);
                        parentElement.appendChild(liElement);

                    }
                }

                ImplementExpandCollapse(ulElement);
            });
        }
    });
}
function setupTree() {
    RetreiveAllSubsites();

}
function RetreiveAllSubsites() {


    $('#tree1').html().SPServices({
        operation: "GetAllSubWebCollection",
        completefunc: function (xData, status) {
            var ulElement1 = document.createElement("ul");
            ulElement1.setAttribute("id", "folderStruct");
            $('#tree1').html("").append(ulElement1);


            $(xData.responseXML).find("Web").each(function () {
                var webtitle = $(this).attr("Title").toLowerCase();
                var weburlvar = $(this).attr("Url").toLowerCase();



                var liElement = document.createElement("li");
                liElement.setAttribute("id", updateID(webtitle));

                liElement.setAttribute("class", "collapse");

                var childULElement = document.createElement("ul");
                childULElement.setAttribute("id", updateID("pare_" + webtitle));

                var textNode = document.createTextNode(webtitle);
                var anchorelement = document.createElement("a");

                anchorelement.appendChild(textNode);
                anchorelement.setAttribute("href", "#");
                anchorelement.setAttribute("class", "anchorStyle");

                $(anchorelement).click(toggleExpandCollapse);

                liElement.appendChild(anchorelement);
                liElement.appendChild(childULElement);
                ulElement1.appendChild(liElement);

                RetreiveAllLists(weburlvar, childULElement);

            });
        }

    });

}

function RetreiveAllLists(url, ulElement1) {

    $().SPServices({
        operation: "GetListCollection",
        webURL: url,
        completefunc: function (xData, Status) {



            $(xData.responseXML).find("[nodeName='List']").each(function () {
                var baseType = $(this).attr("BaseType");
                var listurl = $(this).attr("DefaultViewUrl").toLowerCase();
                var title = $(this).attr("Title").toLowerCase();
                if ((baseType == "1") &&
(listurl.indexOf("/_catalogs/") == -1) && (title != "converted forms")
&& (title != "customized reports") && (title != "form templates") &&
(title != "reporting templates") && (title != "style library") &&
(title != "site pages") && (title != "site assets") && (title !=
"wfpub")) {
                    var liElement = document.createElement("li");
                    liElement.setAttribute("id", updateID(title));
                    liElement.setAttribute("class", "collapse");

                    var childULElement = document.createElement("ul");
                    childULElement.setAttribute("id", updateID("pare_"
+ title));
                    var textNode = document.createTextNode(title);
                    var anchorelement = document.createElement("a");
                    anchorelement.appendChild(textNode);
                    anchorelement.setAttribute("href", "#");
                    anchorelement.setAttribute("class", "anchorStyle");
                    $(anchorelement).click(toggleExpandCollapse);

                    liElement.appendChild(anchorelement);
                    liElement.appendChild(childULElement);
                    ulElement1.appendChild(liElement);

                    retrieveAllFolders(title, childULElement);


                }
            });
        }
    });
}


function ImplementExpandCollapse(parentulElement) {
    PopulateCollapse($(parentulElement));
    addClickEvents();
}
function addClickEvents() {

    $("#folderStruct > li").each(function () {
        $(this).click = toggleExpandCollapse;
    });


}


function PopulateCollapse(parentulElement) {
    var count = $(parentulElement).children().length;

    if (count < 1)
        return;
    else {

        $(parentulElement).parent().attr("class", "collapse");
        $(parentulElement).hide();

        $("#" + parentulElement.attr("id") + "> li").each(function () {
            var lielement = $(this);
            $("#" + lielement.attr("id") + " > ul").each(function () {
                PopulateCollapse($(this));
            });
        });
    }
}


function toggleExpandCollapse(event) {
    var thisSiteUrl = $().SPServices.SPGetCurrentSite();
    var anchorElement = $(this);
    var liElement = anchorElement.parent();
    var classValue = liElement.attr("class");
    var AppendingText = "";

    if (classValue == "collapse") {
        liElement.attr("class", "expand");
        $("#" + liElement.attr("id") + " > ul").each(function () {
            var childElement = $(this);
            childElement.show();

        });
    }
    else {

        liElement.attr("class", "collapse");
        $("#" + liElement.attr("id") + " > ul").each(function () {
            var childElement = $(this);
            childElement.hide();

            PopulateCollapse(childElement);
        });
    }


    var textBox = $("input[id$= tbxUrl]").each(function () {
        $(anchorElement).parents().each(function () {
            var lielement = $(this);
            if (lielement.get(0).tagName == "LI") {
                $("#" + lielement.attr("id") + " > a").each(function () {

                    var liText = $(this).text();
                    AppendingText = liText + "/" + AppendingText;

                });
            }
        });
        $(this).val(thisSiteUrl + "/" + AppendingText);
    });
}

function updateID(tokenID) {

    tokenID = tokenID.replace("#", "_");
    tokenID = tokenID.replace(" ", "_");
    tokenID = tokenID.replace("/", "_");
    tokenID = tokenID.replace("/", "_");

    return tokenID;
}

Friday 9 August 2013

Delete list item using  JSOM :


Delete Folder Also uisng same code.


function deleteListItem() {

    this.itemId = 2;

    var clientContext = new SP.ClientContext.get_current();;
    var oList = clientContext.get_web().get_lists().getByTitle('ListTitle');

    this.oListItem = oList.getItemById(itemId);

    oListItem.deleteObject();

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
 Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

    alert('Item deleted: ' + itemId);
}

function onQueryFailed(sender, args) {

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

How to Get ECMAScript Intellisence

When you will use ECMAScript library in Visual Studio, it’s possible to get intellisense for ECMAScript. There are three ways you may need to enable the intellisense:
Get Intellisense in Application Page: In the case you want to put your javascript in aspx file as inline, you need to add the following lines in the markup file. However, this will not work for webpart file. For webpart file you need to put your javascript in another js file as described in option 2.
<script type=”text/ecmascript” src=”/_layouts/SP.debug.js” />
<script type=”text/ecmascript” src=”/_layouts/SP.Debug.js” />
<script type=”text/ecmascript” src=”/_layouts/SP.Runtime.Debug.js” />
<script type=”text/javascript”>
// get intellisense here
</script>
Get Intellisense in js file: If you want to get intellisense in js file then you need to add the following lines in the top of the js file. As shown in the snippet below, the first reference is to MicrosoftAjax.js file. This is mandatory to have this js file reference at the top. Then I have added two other references. The two files (SP.Core.Debug.js and SP.debug.js) have basic SharePoint namespaces. However, if you need more functionalities try to add more js file reference from the path “C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/14/TEMPLATE/LAYOUTS”
Get Intellisense in webpart: To get intellisense in webpart you need to add the following two lines in the webpart ascx file:
<script type=”text/javascript” src=”/_layouts/MicrosoftAjax.js” ></script>
<script type=”text/javascript” src=”/_layouts/SP.debug.js” />

Get List Items Using SPServices.

var items="";

function GetListItems()
{
jQuery().SPServices({
    operation: "GetListItems",
    async: false,
    listName:masterlstname,
    CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
    completefunc: function (xData, Status) {
      jQuery(xData.responseXML).SPFilterNode("z:row").each(function() {
 var title = decodeURIComponent(jQuery(this).attr("ows_Title"));
        items = items+title+'\n' ;
      });
    }
  });  
alert(items);
}

JSOM Check out and check in a Page in sharepoint.


function checkOut(){
        var ctx = SP.ClientContext.get_current();
        var page = ctx.get_web().getFileByServerRelativeUrl(window.location.pathname);
        page.checkOut();
        ctx.load(page);
        ctx.executeQueryAsync(Function.createDelegate(this, checkOut_Success),
                                            Function.createDelegate(this, checkOut_Fail));
}
function checkOut_Success(sender, args){

alert("Checked Out");
}
function checkOut_Fail(sender, args){

   alert("Fail checkout");
}

function checkIn(){
         var ctx = SP.ClientContext.get_current();
        var web = ctx.get_web();
        var page = web.getFileByServerRelativeUrl(window.location.pathname);    
        page.checkIn();
        page.publish();
        ctx.executeQueryAsync(Function.createDelegate(this, checkIn_Success),
                                            Function.createDelegate(this, checkIn_Fail));
}
function checkIn_Success(sender, args){      
    alert(" checked in ");
}
function checkIn_Fail(sender, args){

   
    alert("Fail  checked in "+args.message);
}

SPServices Add New Folder in library and also subfolders.

For New Folder:

var librarynaem = "";
var newfolder = "foldername";
function CreateFolder() {
jQuery().SPServices({
operation: "UpdateListItems",
async: false,
listName: librarynaem ,
updates: "<Batch OnError='Continue' PreCalc='TRUE' ListVersion='0' >" +
"<Method ID='1' Cmd='New'>" +
"<Field Name='FSObjType'>1</Field>" +
"<Field Name='BaseName'>" + newfolder + "</Field>" +
"</Method>" +
"</Batch>",
completefunc: function(xData, Status) {
//alert("Status=" + Status);
}
});
}

To dd sub folders pass the folder location:
as newfolder ="folder1/folder2/yourfoldername";

Open modal popup in sharepoint using Content Editor webpart.



added refferences: sp.js ,  sp.core.js  ,sp.init.js

function OpenModalDialog()
{
var options = SP.UI.$create_DialogOptions();
options.title = "Modal dialog Title";
options.autosize = true;
options.url=  "http://www.youraddress.com";
options.showClose= true;
options.allowMaximize = false;
 SP.UI.ModalDialog.showModalDialog(options);
}
SPServices Change folder Name



function ChangeFolderName(FolderName,NewFolderName )
{
jQuery().SPServices({
        operation: "GetListItems",
        async: false,
        listName: Sourcelist,
        CAMLViewFields: "<ViewFields Properties='True' />",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>1</Value></Eq></Where></Query>",
        CAMLQueryOptions: "<QueryOptions><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns></QueryOptions>",
        completefunc: function(xData, Status) {        
         jQuery(xData.responseXML).SPFilterNode('z:row').each(function() {
                strFileName = jQuery(this).attr("ows_FileLeafRef").split(";#")[1];
if(strFileName == FolderName)
{
                FolderID = jQuery(this).attr("ows_ID");
 
 jQuery().SPServices({
                        operation: "UpdateListItems",
                        async: false,
                        batchCmd: "Update",
                        listName: Sourcelist,
                        valuepairs: [["Title", NewFolderName], ["BaseName", NewFolderName]],
                        ID: FolderID,
                        completefunc: function(xData, Status) {    
alert(Status);                  
                        }
                    });
 }
 });
}
});

}
Get all Folders in a library using SPServices.

var LibName="";
var folders = "";
function GetLibraryFolders()
{ jQuery().SPServices({
operation:  "GetListItems",
listName: LibName,
asunc:false,
completefunc: function (xData, Status) {
    jQuery(xData.responseXML).SPFilterNode("z:row").each(function() {
      var thisFSObjType = jQuery(this).attr("ows_FSObjType").split(";#")[1];
      if(thisFSObjType == 1)
folders  = folders+  jQuery(this).attr("ows_LinkFilename")+"\n";
    });
}
});
alert(folders  );
}
Get current site display name using SPServices


var CurrentSiteName
 function GetCurrentSiteDisplayName(){
jQuery().SPServices({
    operation: "SiteDataGetWeb",
    async: false,
completefunc: function (xData, Status) {
CurrentSiteName= jQuery(xData.responseXML).SPFilterNode("Title").text();
}
});
}
SPServices Check Is user is in a Perticual group.

var groupname="your group name";

function IsUserInGroup(){
jQuery().SPServices({
      operation: "GetGroupCollectionFromUser",
      userLoginName: jQuery().SPServices.SPGetCurrentUser(),
      async: false,
      completefunc: function(xData, Status) {      
        jQuery(xData.responseXML).find("Group").each(function(){
if(jQuery(this).attr("Name") == groupname)
{
//Method to call if user is in perticualr group.
executeifOwners();
return;
}
});
}
    });
}


Get all Folders in a Library using jsom


function GetFolders()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle("Project Documents");
var query = SP.CamlQuery.createAllFoldersQuery();
allItems = list.getItems(query);
context.load(allItems);
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success()
{
var FolderNames = "";
var ListEnumerator = this.allItems.getEnumerator();
while(ListEnumerator.moveNext())
{
var currentItem = ListEnumerator.get_current();
var _contentType = currentItem.get_fileSystemObjectType();
if(currentItem.get_fileSystemObjectType() == 1)
{
FolderNames  += currentItem.get_item('Title')+ '\n';
}
}
alert(FolderNames);
}
function failed(sender, args)
{
alert("failed. Message:" + args.get_message());
}
GetFolders();


Friday 2 August 2013

Sharepoint get all webparts titles in a page using client object model javascript.


//array to store webpart titles in the page.
var WebpartTitles = [];

// to get webpart count and index count.
var WebpartsCount=0,wpindex = 0;

function GetWebPartTitlesFromPage() {
    this.clientContext = new SP.ClientContext.get_current();
    var oFile = clientContext.get_web().getFileByServerRelativeUrl(serverRelativeUrl);
    var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
    this.collWebPart = limitedWebPartManager.get_webParts();
    clientContext.load(collWebPart);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.getTitle), Function.createDelegate(this, this.onQueryFailed));
}
function getTitle() {
if(WebpartsCount == 0)
{
WebpartsCount = collWebPart.get_count();
}
if(!WebpartsCount )
{
alert("No webparts in the current Page");
return;
}
var oWebPartDefinition = collWebPart.get_item(wpindex);
this.oWebPart = oWebPartDefinition.get_webPart();
clientContext.load(oWebPart, 'Title');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededGetTitle), Function.createDelegate(this, this.onQueryFailed));
} function onQuerySucceededGetTitle()
{
wpindex++;
var title = this.oWebPart.get_title(); WebpartTitles.push(title); if(wpindex < WebpartsCount)
{
getTitle(); }
else{ //bingo u got all webparts titles here.
alert(WebpartTitles); }
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n'); }