Latest From My Blog

SharePoint: CSOM break folder permissions

Consider a scenario where you need to break permissions of a folder using client object model (CSOM) in SharePoint. The code below creates a folder in the document library, breaks its permissions and gives a particular user Contribute permissions on it. The main thing to note here is that, in CSOM Folder does not     have BreakRoleInheritance or Item method. It has a property named ListItemAllFields. This is used to break permissions as shown: 
using (var clientContext = new ClientContext("http://sitename"))
{                    
    Web web = clientContext.Web;
    List list = web.Lists.GetByTitle("Documents");
    Folder newFolder = list.RootFolder.Folders.Add("FolderName");
    clientContext.ExecuteQuery();    
    newFolder.ListItemAllFields.BreakRoleInheritance(false, true);
    var role = new RoleDefinitionBindingCollection(clientContext);
    role.Add(web.RoleDefinitions.GetByType(RoleType.Contributor));
    User user = web.EnsureUser("contoso\\adamb");
    newFolder.ListItemAllFields.RoleAssignments.Add(user, role);
    newFolder.Update();
    clientContext.ExecuteQuery();
}

SharePoint: Update XSLTListViewWebPart properties

Consider a web part page having an XSLTListViewWebpart on it and the requirement is to update its properties using PowerShell. In this example, we get the first XSLTListViewWebpart present on a page and update its Server Render property to true.
$SiteUrl = "http://aissp2013/sites/TestSite/"
$pageURL = "http://aissp2013/sites/TestSite/Lists/MyList/AllItems.aspx"
$web = Get-SPWeb $SiteUrl
$wpm = $web.GetLimitedWebPartManager($pageURL, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$wp = $wpm.WebParts[0]
$wp.ServerRender = $true
$wpm.SaveChanges($wp)


SharePoint: Add multiple users to Person field

Suppose there is a Person and Group column which allows multiple selections of Users. We need to set this field of a list item in code using Server Object model. This can be done by first creating SPFieldUserValue objects and then adding them to SPFieldUserValueCollection. Code sample:
using (SPSite site = new SPSite("http://aissp2013/sites/TestSite/"))
{
    SPWeb root = site.RootWeb;
    SPList list = root.Lists["XYZ"];
    SPListItem item = list.AddItem();
    item["Title"] = "From Code";
    SPUser user1 = root.EnsureUser("contoso\\aaronp");
    SPUser user2 = root.EnsureUser("contoso\\adamb");
    SPFieldUserValueCollection users = new SPFieldUserValueCollection();
    users.Add(new SPFieldUserValue(root, user1.ID, user1.LoginName));
    users.Add(new SPFieldUserValue(root, user2.ID, user2.LoginName));                
    item["Users"] = users;
    item.Update();
}

SharePoint PowerShell: Get files in Library

Get the Name and Url of the files inside a SharePoint Document library using PowerShell:
Code Example 1:
$web = Get-SPWeb "http://aissp2013/sites/TestSite"
$list = $web.Lists["Docs"]
$items = $list.Items
foreach($item in $items)
{
    Write-Host Name: $item.File.Name Url: $item.File.Url
}
Code Example 2:
Get-SPWeb "http://aissp2013/sites/TestSite" | Select -ExpandProperty Lists | Where {$_.Title -eq "Docs" } | Select -ExpandProperty Items | Select Name, Url

Output:

PowerShell Output


SharePoint Online: Create a list using PowerShell

Here is a sample PowerShell code which creates a list (Document Library) in SharePoint online.
Before running this code make sure SharePoint Online Client Components SDK and SharePoint Online Management Shell is installed on your machine. 
#Import the required DLL
Import-Module 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll'
#OR
#Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll'

#Mysite URL
$site = 'https://yoursite.sharepoint.com/'

#Admin User Principal Name
$admin = 'admin@tenant.onmicrosoft.com'

#Get Password as secure String
#$password = Read-Host 'Enter Password' -AsSecureString
$password = ConvertTo-SecureString "YourPassword" -asplaintext -force
#Get the Client Context and Bind the Site Collection
$context = New-Object Microsoft.SharePoint.Client.ClientContext($site)

#Authenticate
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($admin , $password)
$context.Credentials = $credentials
$listCreationInformation = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$listCreationInformation.Title = "My Documents"
$listCreationInformation.Description = "Library created through PowerShell"
$listCreationInformation.TemplateType = 101
$list = $context.Web.Lists.Add($listCreationInformation)
$context.Load($list)
$context.ExecuteQuery()
If you want to prompt the user for password use $password = Read-Host 'Enter Password' -AsSecureString instead of $password = ConvertTo-SecureString "YourPassword" -asplaintext -force.

Library


SharePoint: Programatically reset a customized page to the site definition

Suppose the default.aspx page of a a site has been customized (unghosted) and needs to be reset. Following code shows how this can be done using SPFile.RevertContentStream()
using (SPSite site = new SPSite("http://aissp2013/sites/Team/"))
{   
    using(SPWeb web in site.RootWeb)
    {
        SPFile file = web.GetFile(web.Url + "/default.aspx");
        if (file.Exists)
        {
            file.RevertContentStream();
        }                      
    }
} 

SharePoint: Reorder fields in content type

Here is a PowerShell script to re-order fields in a List Content Type:

$web = Get-SPWeb http://aissp2013/sites/TestSite
$list = $web.Lists["MyList"]
$contentType = $list.ContentTypes | where {$_.Name eq "MyTestCT"}
$ctFields = "Title","ColumnA","ColumnB","ColumnD","ColumnC"
$contentType.FieldLinks.Reorder($ctFields)
$contentType.Update()

SharePoint 2013: Strings.js

Ever wondered where the text like "drag files here" in Document Library or "edit this list" come from.

Drag Files Here

Edit This List

There is a JavaScript file named strings.js file which contains these values. It is stored in TEMPLATE\LAYOUTS\LCID, where LCID is the language identified. For English it is 1033. Here, you will also find a debug version of this file named strings.debug.js. Even though actual changes if needed are to be done in strings.js file but since it is minified reading it becomes quite difficult. The debug version is easy to read and understand. This is how "drag files here" is defined:
Strings.STS.L_SPAddNewAndDrag='{0} or drag files here';

SharePoint 2013: Recursive Calendar Event

The code in this post will show how to create recursive calendar events. The data about the Recurrence is stored in a field named "RecurrenceData". It is xml based data. One of the easy ways to determine what the value of "RecurrenceData" should be is to create an a recurrence item in the list from UI, get that item from code and find the data. Example:
SPList cal = web.Lists["Cal"];
SPListItem item = cal.GetItemById(1);
string data = item["RecurrenceData"].ToString();
Here is sample recurrence xml data
<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><weekly tu="TRUE" weekFrequency="1" /></repeat><repeatInstances>2</repeatInstances></rule></recurrence>
This is how it shows in UI. It is a weekly recurrence:

Weekly Recurrence

There are few other fields which need to be updated when creating a Recurrence event apart from "RecurrenceData". "EventType" which needs to be set to 1,"UID" which takes a GUID and "Recurrence" which is set to true. Here is a sample code which creates a Recurrence event.
static void Main(string[] args)
{
    using (SPSite site = new SPSite("http://aissp2013/sites/Team1/"))
    {
        SPWeb rootWeb = site.RootWeb;
        SPList cal = rootWeb.Lists["AIS Calendar"];
        SPListItem newItem = cal.AddItem();
        newItem["Title"] = "IDC Townhall";
        newItem["Location"] = "WAR Room 13";
        newItem["EventDate"] = new DateTime(2015,2,10, 10,0,0);
        newItem["EndDate"] = new DateTime(2015, 2, 10, 11, 0, 0);
        newItem["Recurrence"] = true;
        newItem["RecurrenceData"] = "<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><weekly tu='TRUE'" +
        " weekFrequency='1' /></repeat><repeatInstances>2</repeatInstances></rule></recurrence>";
        newItem["EventType"] = 1;
        newItem["UID"] = System.Guid.NewGuid();
        newItem.Update();
        cal.Update();
    }
}
Here is the Recurrence event in the UI created as a result of above code:

Recurrence Event


profile for Nadeem Yousuf at SharePoint Stack Exchange, Q&A for SharePoint enthusiasts

+