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


 

Friday, 22 January 2016

Things to keep in mind before migrating to Office 365 - SharePoint Online

Here are some of the points which we should consider before moving to Office 365 - SP Online


1. 5000 items limit:
On Office 365 there is a threshold limit of 5000 items per list/library. One of the solutions for this is to split the items into different lists such that each target list hs less than 5000 items.

2. Workflows:
Source sites need to be analyzed to check whether they contain workflows or not. If yes then required options should be selected while migration and the respective target lists need to be verified post migration.

3. Inherited Content Types:
If the source site inherits content types from parent site then such content types needs to be migrated before migrating anything else.

4. Alerts:
User alerts should be migrated after migrating everything. Otherwise, users will get unwanted mails for each item.

5. Page Layouts:
Sometimes migration tools fail to put page layout reference correctly. So, you may have to use some script to specify the layout URL explicitly.

6. Site templates:
Source site and sub sites templates should be analyzed and mapped properly while migration.

7. Site size:
Source site size should be checked before creating the target site. And there should be an adequate buffer as well.

Tuesday, 3 November 2015

How to add Content Editor Web Part in a SharePoint page programmatically?


using MSWPP = Microsoft.SharePoint.WebPartPages;
using SWUWW = System.Web.UI.WebControls.WebParts;

public  string AddWebPartToPage(SPWeb web, string pageUrl, string webPartName, string zoneID, int zoneIndex)
        {
            try
            {
                string iD;
                using (MSWPP.SPLimitedWebPartManager limitedWebPartManager = web.GetLimitedWebPartManager(pageUrl, SWUWW.PersonalizationScope.Shared))
                {
                    using (SWUWW.WebPart webPart = createContentWebPart())
                    {
                        limitedWebPartManager.AddWebPart(webPart, zoneID, zoneIndex);
                        iD = webPart.ID;
                    }
                }
                return iD;
            }
            catch (Exception ex)
            {
                using (StreamWriter streamWriter = File.AppendText("log.WebPart.txt"))
                {
                    Log("Error: " + "Add WebPart Exception: " + ex.Message, streamWriter);
                }
                return null;
            }
        }


public  MSWPP.ContentEditorWebPart createContentWebPart()
        {
            try
            {
                MSWPP.ContentEditorWebPart contentWebPart = new MSWPP.ContentEditorWebPart();
                //Set properties of new webpart object  
                contentWebPart.ZoneID = "TOP";
                contentWebPart.Title = "Migration Status";
                contentWebPart.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal;
                contentWebPart.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;

                //Add content to CEWP
                XmlDocument xmlDoc = new XmlDocument();
                XmlElement xmlElement = xmlDoc.CreateElement("Root");
                xmlElement.InnerText = @"<div style=""border:dashed;border-width:1px;padding:4px;font-family:calibri;font-size:12px;"">" +
                    "<b>MIGRATED</b><br/>" +
                    "</div>";
                contentWebPart.Content = xmlElement;
                contentWebPart.Content.InnerText = xmlElement.InnerText;

                return contentWebPart;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

Tuesday, 13 October 2015

How to add a web part zone in a SharePoint custom page layout?


Create a custom page layout using SharePoint designer.

Select the content type for the page layout as shown below:



How to add a web part zone in a SharePoint custom page layout?


How to add a web part zone in a SharePoint custom page layout?


Then, create the web part zones like this:

<WebPartPages:WebPartZone runat="server"
      AllowPersonalization="true"
      ID="SomeID"
      FrameType="TitleBarOnly"
      Title="SomeTitle"
      Orientation="Horizontal">
</WebPartPages:WebPartZone>


How to hide SharePoint top bar (header) and left navigation from SharePoint custom master page using CSS?

You can either create a blank master page using SharePoint designer or

use the following styles:

#s4-ribbonrow, .ms-cui-topBar2, .s4-notdlg, .s4-pr s4-ribbonrowhidetitle,
.s4-notdlg noindex, #ms-cui-ribbonTopBars, #s4-titlerow,
#s4-pr s4-notdlg s4-titlerowhidetitle, #s4-leftpanel-content,#sideNavBox
{
    display:none !important;
}


.s4-ca
{
    margin-left:0px !important; margin-right:0px !important;
}


#contentBox
{
    margin-left:0px;
    margin-right:0px;
    min-width:auto;
}


#contentRow
{
padding-top:0px !important;
}


#s4-workspace
{
 width:auto !important;
}


#s4-bodyContainer
{
 padding:0px;
}

How to create SharePoint App (App-Part or Client WebPart) to embed Yammer feed in SharePoint 2013/Online?


Step 1. Create an App for SharePoint 2013 in Visual Studio.

Step 2. Add an App-Part or Client Web-Part in your App.

Step 3. Go to the Element.xml of your App Part (Client Web Part) and prepare it like this:


<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ClientWebPart Name="YammerFeed" Title="Yammer Feed by CompanyName" Description="Yammer Feed is an app-part by CompanyName to display yammer feeds. This app-part can be used to embed group, topic and user feeds." DefaultWidth="500" DefaultHeight="500">

    <!-- Content element identifies the location of the page that will render inside the client web part
         Properties are referenced on the query string using the pattern _propertyName_
         Example: Src="~appWebUrl/Pages/ClientWebPart1.aspx?Property1=_property1_" -->

    <Content Type="html" Src="~appWebUrl/Pages/YammerFeed.aspx?network=_network_&amp;feedId=_feedId_&amp;feedType=_feedType_&amp;header=_header_&amp;footer=_footer_&amp;hideNetworkName=_hideNetworkName_&amp;{StandardTokens}" />

    <!-- Define properties in the Properties element.
         Remember to put Property Name on the Src attribute of the Content element above. -->

    <Properties>
      <Property
        Type="string"
        Name="network"
        WebBrowsable="true"
        WebDisplayName="Network"
        WebCategory="Yammer Settings"
        RequiresDesignerPermission="true"
        DefaultValue="CompanyName.com">
     </Property>

     <Property
        Type="string"
        Name="feedId"
        WebBrowsable="true"
        WebDisplayName="Feed ID"
        WebCategory="Yammer Settings"
        RequiresDesignerPermission="true"
        DefaultValue="5512843">
      </Property>

     <Property
        Name="feedType"
        Type="enum"
        RequiresDesignerPermission="true"
        DefaultValue="group"
        WebCategory="Yammer Settings"
        WebDisplayName="Feed Type">
        <EnumItems>
        <EnumItem WebDisplayName="Group" Value="group"/>
         <EnumItem WebDisplayName="Topic" Value="topic"/>
         <EnumItem WebDisplayName="User" Value="user"/>
        </EnumItems>
      </Property>


     <Property
        Name="header"
        Type="boolean"
        RequiresDesignerPermission="true"
        DefaultValue="false"
        WebCategory="Yammer Settings"
        WebDisplayName="Header">
      </Property>
 

      <Property
        Name="footer"
        Type="boolean"
        RequiresDesignerPermission="true"
        DefaultValue="true"
        WebCategory="Yammer Settings"
        WebDisplayName="Footer">
      </Property>

         <Property
            Name="hideNetworkName"
            Type="boolean"
            RequiresDesignerPermission="true"
            DefaultValue="false"
            WebCategory="Yammer Settings"
            WebDisplayName="Hide Network Name">
            </Property>

    </Properties>

  </ClientWebPart>
</Elements>
 



Step 4. Add an ASPX page under 'Pages' module and add the following HTML


<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<html>
<head>
    <title></title>
    <link href="../Content/App.css" rel="stylesheet" />
    <script src="../Scripts/App.js"></script>
    <script type="text/javascript" src="../Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
    <script type="text/javascript" data-app-id="xxxxxxxxxxxxxxxxxxxxx" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js"></script>
    <script type="text/javascript" src="https://c64.assets-yammer.com/assets/platform_embed.js"></script>
    <script src="../Scripts/Yammer/YammerFeed.js"></script>
    <script type="text/javascript">
        yamLogin();
    </script>

</head>
<body style="border:solid;border-width:1px;border-color:#8f8c8c;">
    <table id="tblWait" class="fullWidth" style="display: none">
        <tr>
            <td align="center">
                <br /><br /><br />

                <img src="../Images/wait_SP.gif" />
                <img src="../Images/workingonItTextSmall.png" />

                <br /><br /><br /><br />

            </td>
        </tr>
    </table>

    <table class="loginStyle" id="tblBeforeLogin">
       <tr>
            <td align="center">
                <br /><br />

                <img id="imgSmallLogo" src="../Images/yammer-logo-final.png" />

               <br /><br />

               <input id="yammer-login" value="Login" type="button" class="loginButtonYam" />
                <br /> <br /><br /><br />

           </td>
       </tr>

    </table>  
    <div id="embedded-feed" style="height:480px;width:100%;display: none;"></div>
          
<%--Script to adjust Height and Width of the App Part--%>
    <script type="text/javascript">
        "use strict";
        window.Communica = window.Communica || {};
 
        $(document).ready(function () {
            Communica.Part.init();

        });

        Communica.Part = {
            senderId: '',

            init: function () {
               var params = document.URL.split("?")[1].split("&");

                for (var i = 0; i < params.length; i = i + 1) {
                    var param = params[i].split("=");

                    if (param[0].toLowerCase() == "senderid")
                        this.senderId = decodeURIComponent(param[1]);

                }

                this.adjustSize();

            },

            adjustSize: function () {
                var step = 30,

                newHeight,
                    contentHeight = $('#userDataContent').height(),

                    resizeMessage = '<message senderId={Sender_ID}>resize({Width}, {Height})</message>';
               resizeMessage = resizeMessage.replace("{Sender_ID}", this.senderId);
                resizeMessage = resizeMessage.replace("{Height}", "500px");
                resizeMessage = resizeMessage.replace("{Width}", "100%");
                window.parent.postMessage(resizeMessage, "*");          
            }
        };
</script>
</body>
</html>



Step 5. YammerFeed.js


// Login to yammer
function yamLogin() {
    try {
        yam.getLoginStatus(
      function (response) {
          if (response.authResponse) {
              yamGroupFeeed();
          }
          else {
              yam.connect.loginButton('#yammer-login', function (resp) {
                  if (resp.authResponse) {
                      yamGroupFeeed();

                 }
             });
          }
      }

    );
    }
   catch (err) {
        //alert(err.message);
    }
 
}

//Fetch yammer feed
function yamGroupFeeed() {
    try {
        //fetch app configurations
        var yamNetwork = decodeURIComponent(getQueryStringParameter('network'));
        var yamFeedId = decodeURIComponent(getQueryStringParameter('feedId'));
        var yamFeedType = decodeURIComponent(getQueryStringParameter('feedType'));
        var yamHeader = decodeURIComponent(getQueryStringParameter('header'));
        var yamFooter = decodeURIComponent(getQueryStringParameter('footer'));
        var yamHideNetworkName = decodeURIComponent(getQueryStringParameter('hideNetworkName'));

        //request feed
        yam.connect.embedFeed(
            {
                container: '#embedded-feed',
                network: yamNetwork,
                feedType: yamFeedType,                // can be 'group', 'topic', or 'user'         
                feedId: yamFeedId,                 // feed ID from the instructions above
                config: {
                use_sso: true
                //defaultGroupId: XXXXXXX      // specify default group id to post to

                    , header: yamHeader
                    , footer: yamFooter
                    ////, showOpenGraphPreview: false
                    ////, defaultToCanonical: false
                    , hideNetworkName: yamHideNetworkName
                }
            });
   
       document.getElementById('tblBeforeLogin').style.display = "none";
       document.getElementById('embedded-feed').style.display = "block";
    }
    catch (err) {
        //alert(err.message);
    }
}