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);
            }

        }

Friday, 4 March 2016

How to export DataTable or Data Grid View data into Excel file ?


Method to convert DataTable rows into Excel file:

using SWF = System.Windows.Forms;using IO = System.IO;
 
public static string pPopulateExcel(DataTable myTable)
{  StringBuilder sb = new StringBuilder();
sb.AppendLine("<table cellspacing='0' cellpadding='4' rules='all' bordercolor='#CCCCCC' border='1' style='color:Black;background-color:White;border-color:#CCCCCC;border-width:1px;border-style:Solid;font-family:Tahoma;font-size:10pt;height:24px;border-collapse:collapse;'>");
sb.AppendLine("<tr style='color:Blue;background-color:aliceblue;font-weight:bold;'>");
sb.AppendLine("<td align='center'>Sl.No.</td>");
for (int llngCol = 0; llngCol < myTable.Columns.Count; llngCol++)
sb.AppendLine("<td align='center'>" + myTable.Columns[llngCol].ColumnName + "</td>");
sb.AppendLine("</tr>");
if (myTable.Rows.Count > 0)

{ 
int i = 1;
foreach (DataRow objDR in myTable.Rows)
{
 
sb.AppendLine("<tr class='body'>");

sb.AppendLine("<td align='right'>" + i + "</td>");
for (int llngCol = 0; llngCol < myTable.Columns.Count; llngCol++)
{
switch (myTable.Columns[llngCol].DataType.ToString())

{
 
case "System.Int32":
case "System.Decimal":
case "System.Double":
sb.AppendLine("<td align='right'>" + objDR[llngCol]);
break;
case "System.DateTime":
sb.AppendLine("<td align='center'>");
if (Convert.ToDateTime(objDR[llngCol]) != DateTime.MinValue)
sb.AppendLine((objDR[llngCol].ToString().Length == 0 ? "" : Convert.ToDateTime(objDR[llngCol].ToString()).ToString("dd-MMM-yyyy")) + "");
else
sb.AppendLine("&nbsp;");
break;
case "System.String":
sb.AppendLine("<td align='left'>" + objDR[llngCol]);
break;
default:
sb.AppendLine("<td align='center'>" + objDR[llngCol]);
break;

}
sb.AppendLine("</td>");

}
sb.AppendLine("</tr>");

i++;

}
sb.AppendLine("</table>");

}
else
sb.AppendLine("<tr class='body'><td colspan='" + (myTable.Columns.Count + 1) + "' align='left'>No Records found!</td></tr></table>");
return sb.ToString();

}

Export To Excel Button:

private void btnExportToExcel_Click(object sender, EventArgs e)
{ string XLSFileName = IO.Path.Combine(CurrentDirectory(), "Status Report " + DateTime.Now.ToString("ddMMMyyyyHHmm") + ".xls");

StringBuilder sbExcelText = new StringBuilder();

sbExcelText.AppendLine(ExcelUtil.pPopulateExcel((DataTable)dataGridResults.DataSource));

sbExcelText.AppendLine("<br />");

IO.File.WriteAllText(XLSFileName, sbExcelText.ToString());

SWF.MessageBox.Show("Completed! File: " + XLSFileName, "Status Report");

}


Method to get current directory path:

internal static string CurrentDirectory()

{
string lstrPath = System.IO.Path.GetDirectoryName(SWF.Application.ExecutablePath).ToLower();

if (lstrPath.Contains(@"\bin\debug") || lstrPath.Contains(@"\bin\release") || lstrPath.Contains(@"\bin\x86"))

{lstrPath = System.IO.Path.GetDirectoryName(SWF.Application.ExecutablePath).Substring(0, lstrPath.IndexOf(@"\bin"));

}return lstrPath + @"\Reports";
}