Friday, 2 September 2016

How to reset SharePoint list items permission from unique permission to inheriting from parent?


public static void ResetItemPermissions(string listName)
        {
            ClientContext context = new ClientContext("https://domain.com/sites/siteColl/siteName/");
            string decryptedPwdt = "password";
            foreach (char c in decryptedPwdt)
            {
                securePassword.AppendChar(c);
            }
            context.Credentials = new NetworkCredential("user", decryptedPwdt, "Domain");
            Web web = context.Web;
            context.Load(web);

            List list = web.Lists.GetByTitle(listName);
            context.Load(list);

            CamlQuery camlQuery = new CamlQuery();
            ListItemCollection itemColl = list.GetItems(camlQuery);
            context.Load(itemColl);
            context.ExecuteQuery();

            foreach (ListItem item in itemColl)
            {
                item.ResetRoleInheritance();
                item.Update();
                context.ExecuteQuery();

                Console.Write(".");
           
            }
            Console.WriteLine("\r\nDone!");
            Console.Read();
        }

Saturday, 20 August 2016

How to get User object using CSOM from SharePoint online list item?





newItem["Created_x0020_By_x0020_History"] = web.EnsureUser((((Microsoft.SharePoint.Client.FieldUserValue)(item["Author"])).Email).ToString());


                            newItem["Modified_x0020_By_x0020_History"] = web.EnsureUser((((Microsoft.SharePoint.Client.FieldUserValue)(item["Editor"])).Email).ToString());

Wednesday, 17 August 2016

How to remove multiple SharePoint user permission without getting following error message: "You have chosen to delete too many groups at once. Select fewer groups and try again".


SharePoint doesn't allow to delete all 1000s of users at once. But, we can delete 400 at a time. That again is quite tedious - selecting 400 hundred check-boxes manually.

We can reduce the effort for selecting checkboxes manually by using the browser's developer tool.

Press F12 on your browser to open the developer tool.

Go to console and execute the following to select only 400 users at a time:

(function() {
    var aa = document.querySelectorAll("input[type=checkbox]");
    for (var i = 1; i < 400; i++){
        aa[i].checked = true;
    }
})()



Note: Loop is executed from the 2nd index to avoid 'select all' checkbox.


-----------------------------------------OR---------------------------------------------------

Use the following CSOM code:

public static void RemoveSitePermissions()
        {
            ClientContext ctxSource = new ClientContext("https://domain.com/sites/siteColl/siteName/");
            string decryptedPwd = "password";
            foreach (char c in decryptedPwd)
            {
                securePassword.AppendChar(c);
            }
            ctxSource.Credentials = new SharePointOnlineCredentials("user@domain.com", securePassword);
            Web webSource = ctxSource.Web;
            ctxSource.Load(webSource);
            UserCollection userColl = webSource.SiteUsers;
            ctxSource.Load(userColl);
            ctxSource.ExecuteQuery();

            foreach (User user in userColl.ToList())
            {
                try
                {
                    userColl.Remove(user);
                    ctxSource.ExecuteQuery();
                    Console.Write(".");
                 
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

Thursday, 23 June 2016

How to hide a part of navigation for a set of users on SharePoint 2013?


First organize all the site users into different groups,

Then go to Site Settings > Navigation and edit the part of navigation you want to hide and set the target audience. 

How to hide left navigation on a particular page in SharePoint 2013?


Add a Script Editor web-part on the page where you need to hide the left navigation and add the following:

<style> 
#sideNavBox
{ 
display: none; 
}
</style>

To re-use this on multiple pages, in case of Publishing site, add the above on Page Layout.

Wednesday, 15 June 2016

How to prepare basic variables for SharePoint hosted App?





    //Global variables
    var context;
    var hostweburl;
    var appweburl;
    var appContextSite;
    var list;
    var web;

    //Code included inside $( document ).ready() will only run once the page
    //Document Object Model (DOM) is ready for JavaScript code to execute
    $(document).ready(function () {
        //Ensures that the specified file that contains the specified function is loaded and
        //then runs the specified callback function.
        //SP.SOD.executeFunc('file name','function name',methos to call post execution);
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getUrl);
    });

    function getUrl() {
        //Fetch query string parameters
        hostweburl = getQueryStringParameter("SPHostUrl");
        appweburl = getQueryStringParameter("SPAppWebUrl");

        //Decode
        hostweburl = decodeURIComponent(hostweburl);
        appweburl = decodeURIComponent(appweburl);

        //Build absolute path to the layouts root with the spHostUrl
        var scriptbase = hostweburl + "/_layouts/15/"; 

        //Before you get SP.js, you have to get SP.Runtime.js
        //Once SP.js can be retrieved, it makes a call to the execOperation method.
        //SP.ProxyWebRequestExecutorFactory is located in sp.requestexecutor.js,
        //which also provides objects, methods, and properties for
        //managing Web request executors for client requests.
        $.getScript(scriptbase + "SP.Runtime.js",
            function () {
                $.getScript(scriptbase + "SP.js",
                function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); }
                );
            }
        );
            
    }

    function execCrossDomainRequest() {

        context = new SP.ClientContext(appweburl);
        var factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
        context.set_webRequestExecutorFactory(factory);
        appContextSite = new SP.AppContextSite(context, hostweburl);

        web = appContextSite.get_web();
        context.load(web);

        list = web.get_lists().getByTitle("Shared Documents");
        context.load(list);

        context.executeQueryAsync(onSuccess, onFail);
        }
        function onSuccess() {
              alert("List loaded Successfully");   
        }

        // This function is executed if the above call fails
        function onFail(sender, args) {
               alert( args.get_message());
        }

        //Generic function to fetch query sting parameters   
        function getQueryStringParameter(paramToRetrieve)
        {
            var params =
                document.URL.split("?")[1].split("&");
            for (var i = 0; i < params.length; i = i + 1)
            {
                var singleParam = params[i].split("=");
                if (singleParam[0] == paramToRetrieve)
                    return singleParam[1];
            }
        }

Wednesday, 9 March 2016

How to get all items from a SharePoint Online list with all columns data?


Here is one of the ways to get all SPOL list items with all columns:


Method to fetch items:

private void btnGetListItems_Click(object sender, EventArgs e)
        {
            progressBar.Minimum = 0;
            progressBar.Maximum = 10;
            progressBar.Value = 1;
            var targetSite = new Uri(txtSiteUrl.Text.Trim());
            var login = txtUserID.Text.Trim();
            var password = txtPassword.Text;
            var securePassword = new SecureString();

            progressBar.Value = 3;
            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }

            var onlineCredentials = new SharePointOnlineCredentials(login, securePassword);

            using (ClientContext clientContext = new ClientContext(targetSite))
            {
                try
                {
                    clientContext.Credentials = onlineCredentials;
                    Web web = clientContext.Web;
                    var list = clientContext.Web.Lists.GetByTitle(drpLists.SelectedItem.ToString());
                    var view = list.Views.GetByTitle("All Items");
                    clientContext.Load(view, v => v.ViewFields, v => v.ListViewXml);
                    clientContext.ExecuteQuery();
                    progressBar.Value = 4;
                    var query = new CamlQuery();
                    query.ViewXml = "<View><Query>" + view.ListViewXml + "</Query></View>";
                    var items = list.GetItems(query);
                    clientContext.Load(items);
                    clientContext.ExecuteQuery();
                    progressBar.Value = 5;
                    dtResults = new DataTable();
                    columnNames = new List<string>();
                    string clmn = string.Empty;
                    foreach (var listColumn in view.ViewFields)
                    {
                        if (listColumn.ToString().ToLower().Contains("linktitle"))
                        {
                            columnNames.Add("Title");
                            dtResults.Columns.Add("Title");
                            continue;
                        }
                        if (listColumn.ToString().ToLower().Contains("attachments"))
                            continue;
                        columnNames.Add(listColumn.ToString());

                        dtResults.Columns.Add(listColumn.ToString());
                    }
                    progressBar.Value = 6;
                 
                    FillGridView(items);
                    btnExportToExcel.Enabled = true;
                    progressBar.Value = 10;
                }
                catch (Exception ex)
                {
                    progressBar.Value = 10;
                    SWF.MessageBox.Show("Error: " + ex.Message);
                }
            }
        }

Method to fill items in DataTable/GridView:

        protected void FillGridView(ListItemCollection itemsColl)
        {
            try
            {
                progressBar.Value = 7;
                DataRow row;
                foreach (ListItem item in itemsColl)
                {
                    row = dtResults.NewRow();
                    foreach (string listColumn in columnNames)
                    {
                        try
                        {
                            row[listColumn] = item.FieldValues[listColumn].ToString();
                        }
                        catch (Exception ex)
                        {
                            row[listColumn] = string.Empty;
                        }

                    }
                    dtResults.Rows.Add(row);
                }
                progressBar.Value = 8;

                dataGridResults.DataSource = dtResults;
                try
                {
                    for (int col = 0; col < dtResults.Columns.Count; col++)
                    {
                        dtResults.Columns[col].ColumnName = dtResults.Columns[col].ColumnName.Replace("_x0020_", " ");
                        dtResults.Columns[col].ColumnName = dtResults.Columns[col].ColumnName.Replace("_x00", string.Empty);

                    }
                }
                catch (Exception ex) { }
            }
            catch (Exception ex)
            {
                progressBar.Value = 10;
                SWF.MessageBox.Show("Error while generating report: " + ex.Message);
            }

        }