Thursday, December 8, 2016

Get site collection usage report using PowerShell

Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue

$sizeLog = "C:\SiteUsage.csv"
$webApps = Get-SPWebApplication
$arr = @()
foreach($webApp in $webApps)
{
    $sites = Get-SPSite -WebApplication $webApp -Limit All
    foreach($site in $sites)
    {
        $sizeInKB = $site.Usage.Storage
        $sizeInMB = $sizeInKB/1024/1024
        $sizeInMB = [math]::Round($sizeInMB,2)

        $obj = New-Object System.Object
        $obj | Add-Member -type NoteProperty -name "Title" -value $site.RootWeb.Title
        $obj | Add-Member -type NoteProperty -name "Site URL" -value $site.URL      
        $obj | Add-Member -type NoteProperty -name "Database" -Value $site.ContentDatabase.Name
        $obj | Add-Member -type NoteProperty -name "Size in MB" -Value $sizeInMB
        $obj | Add-Member -type NoteProperty -name "Last Access Date" -Value $site.LastContentModifiedDate
     
        $arr += $obj
    }
}
$arr | Export-Csv $sizeLog -Delimiter "," -NoTypeInformation
Write-Host "Exported to" $sizeLog
$site.Dispose()

Saturday, June 25, 2016

Get folder item count using CSOM

ClientContext clientContext = new ClientContext(<SITEURL>)
List list = clientContext.Web.Lists.GetByTitle(<LIBRARYNAME>);
var query = new CamlQuery();
var folderServerRelativeUrl = "/sites/demo/Documents/Sample";
query.ViewXml = "<View Scope=\"RecursiveAll\"> " +
                    "<Query>" +
                        "<Where>" +
                            "<Eq>" +
                                "<FieldRef Name=\"FileDirRef\" />" +
                                "<Value Type=\"Text\">" + folderServerRelativeUrl + "</Value>" +
                            "</Eq>" +
                        "</Where>" +
                    "</Query>" +
                "</View>";
var folderItems = list.GetItems(query);
clientContext.Load(folderItems);
clientContext.ExecuteQuery();
Console.WriteLine(folderItems.Count);

Wednesday, June 15, 2016

Export and Import Site Columns and Contenttypes using powershell

Export Columns

$sourceWeb = Get-SPWeb http://siteurl
$xmlFilePath = "C:\Install\Script-SiteColumns.xml"

#Create Export Files
New-Item $xmlFilePath -type file -force

#Export Site Columns to XML file
Add-Content $xmlFilePath "<?xml version=`"1.0`" encoding=`"utf-8`"?>"
Add-Content $xmlFilePath "`n<Fields>"
$sourceWeb.Fields | ForEach-Object {
    if ($_.Group -eq "WBOpsProjects Columns") {
        Add-Content $xmlFilePath $_.SchemaXml
    }
}
Add-Content $xmlFilePath "</Fields>"

$sourceWeb.Dispose()
______________________________________________________________________________

Export Content Types

Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue
$sourceWeb = Get-SPWeb http://siteurl
$xmlFilePath = "C:\Install\Script-SiteContentTypes.xml"

#Create Export File
New-Item $xmlFilePath -type file -force

#Export Content Types to XML file
Add-Content $xmlFilePath "<?xml version=`"1.0`" encoding=`"utf-8`"?>"
Add-Content $xmlFilePath "`n<ContentTypes>"
$sourceWeb.ContentTypes | ForEach-Object {
    if ($_.Group -eq "WBOpsProject Content Types") {
        Add-Content $xmlFilePath $_.SchemaXml
    }
}
Add-Content $xmlFilePath "</ContentTypes>"

$sourceWeb.Dispose()
______________________________________________________________________________

Import Columns

$destWeb = Get-SPWeb http://siteurl
$installPath = "C:\Install"

#Get exported XML file
$fieldsXML = [xml](Get-Content($installPath + "\Script-SiteColumns.xml"))

$fieldsXML.Fields.Field | ForEach-Object {
 
    #Configure core properties belonging to all column types
    $fieldXML = '<Field Type="' + $_.Type + '"
    Name="' + $_.Name + '"
    ID="' + $_.ID + '"
    Description="' + $_.Description + '"
    DisplayName="' + $_.DisplayName + '"
    StaticName="' + $_.StaticName + '"
    Group="' + $_.Group + '"
    Hidden="' + $_.Hidden + '"
    Required="' + $_.Required + '"
    Sealed="' + $_.Sealed + '"'
 
    #Configure optional properties belonging to specific column types – you may need to add some extra properties here if present in your XML file
    if ($_.ShowInDisplayForm) { $fieldXML = $fieldXML + "`n" + 'ShowInDisplayForm="' + $_.ShowInDisplayForm + '"'}
    if ($_.ShowInEditForm) { $fieldXML = $fieldXML + "`n" + 'ShowInEditForm="' + $_.ShowInEditForm + '"'}
    if ($_.ShowInListSettings) { $fieldXML = $fieldXML + "`n" + 'ShowInListSettings="' + $_.ShowInListSettings + '"'}
    if ($_.ShowInNewForm) { $fieldXML = $fieldXML + "`n" + 'ShowInNewForm="' + $_.ShowInNewForm + '"'}
     
    if ($_.EnforceUniqueValues) { $fieldXML = $fieldXML + "`n" + 'EnforceUniqueValues="' + $_.EnforceUniqueValues + '"'}
    if ($_.Indexed) { $fieldXML = $fieldXML + "`n" + 'Indexed="' + $_.Indexed + '"'}
    if ($_.Format) { $fieldXML = $fieldXML + "`n" + 'Format="' + $_.Format + '"'}
    if ($_.MaxLength) { $fieldXML = $fieldXML + "`n" + 'MaxLength="' + $_.MaxLength + '"' }
    if ($_.FillInChoice) { $fieldXML = $fieldXML + "`n" + 'FillInChoice="' + $_.FillInChoice + '"' }
    if ($_.NumLines) { $fieldXML = $fieldXML + "`n" + 'NumLines="' + $_.NumLines + '"' }
    if ($_.RichText) { $fieldXML = $fieldXML + "`n" + 'RichText="' + $_.RichText + '"' }
    if ($_.RichTextMode) { $fieldXML = $fieldXML + "`n" + 'RichTextMode="' + $_.RichTextMode + '"' }
    if ($_.IsolateStyles) { $fieldXML = $fieldXML + "`n" + 'IsolateStyles="' + $_.IsolateStyles + '"' }
    if ($_.AppendOnly) { $fieldXML = $fieldXML + "`n" + 'AppendOnly="' + $_.AppendOnly + '"' }
    if ($_.Sortable) { $fieldXML = $fieldXML + "`n" + 'Sortable="' + $_.Sortable + '"' }
    if ($_.RestrictedMode) { $fieldXML = $fieldXML + "`n" + 'RestrictedMode="' + $_.RestrictedMode + '"' }
    if ($_.UnlimitedLengthInDocumentLibrary) { $fieldXML = $fieldXML + "`n" + 'UnlimitedLengthInDocumentLibrary="' + $_.UnlimitedLengthInDocumentLibrary + '"' }
    if ($_.CanToggleHidden) { $fieldXML = $fieldXML + "`n" + 'CanToggleHidden="' + $_.CanToggleHidden + '"' }
    if ($_.List) { $fieldXML = $fieldXML + "`n" + 'List="' + $_.List + '"' }
    if ($_.ShowField) { $fieldXML = $fieldXML + "`n" + 'ShowField="' + $_.ShowField + '"' }
    if ($_.UserSelectionMode) { $fieldXML = $fieldXML + "`n" + 'UserSelectionMode="' + $_.UserSelectionMode + '"' }
    if ($_.UserSelectionScope) { $fieldXML = $fieldXML + "`n" + 'UserSelectionScope="' + $_.UserSelectionScope + '"' }
    if ($_.BaseType) { $fieldXML = $fieldXML + "`n" + 'BaseType="' + $_.BaseType + '"' }
    if ($_.Mult) { $fieldXML = $fieldXML + "`n" + 'Mult="' + $_.Mult + '"' }
    if ($_.ReadOnly) { $fieldXML = $fieldXML + "`n" + 'ReadOnly="' + $_.ReadOnly + '"' }
    if ($_.FieldRef) { $fieldXML = $fieldXML + "`n" + 'FieldRef="' + $_.FieldRef + '"' }

    $fieldXML = $fieldXML + ">"
 
    #Create choices if choice column
    if ($_.Type -eq "Choice") {
        $fieldXML = $fieldXML + "`n<CHOICES>"
        $_.Choices.Choice | ForEach-Object {
           $fieldXML = $fieldXML + "`n<CHOICE>" + $_ + "</CHOICE>"
        }
        $fieldXML = $fieldXML + "`n</CHOICES>"
    }
 
    #Set Default value, if specified
    if ($_.Default) { $fieldXML = $fieldXML + "`n<Default>" + $_.Default + "</Default>" }
 
    #End XML tag specified for this field
    $fieldXML = $fieldXML + "</Field>"
 
    #Create column on the site
    $destWeb.Fields.AddFieldAsXml($fieldXML.Replace("&","&amp;"))
    write-host "Created site column" $_.DisplayName "on" $destWeb.Url
 
    $destWeb.Dispose()
}
______________________________________________________________________________

Import Content Types

Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue
$destWeb = Get-SPWeb http://siteurl
$xmlFilePath = "C:\Install\Script-SiteContentTypes.xml"

#Create Site Content Types
$ctsXML = [xml](Get-Content($xmlFilePath))
$ctsXML.ContentTypes.ContentType | ForEach-Object {

    #Create Content Type object inheriting from parent
    $spContentType = New-Object Microsoft.SharePoint.SPContentType ($_.ID,$destWeb.ContentTypes,$_.Name)
 
    #Set Content Type description and group
    $spContentType.Description = $_.Description
    $spContentType.Group = $_.Group
 
    $_.Fields.Field  | ForEach-Object {
        if(!$spContentType.FieldLinks[$_.DisplayName])
        {
            #Create a field link for the Content Type by getting an existing column
            $spFieldLink = New-Object Microsoft.SharePoint.SPFieldLink ($destWeb.Fields[$_.DisplayName])
     
            #Check to see if column should be Optional, Required or Hidden
            if ($_.Required -eq "TRUE") {$spFieldLink.Required = $true}
            if ($_.Hidden -eq "TRUE") {$spFieldLink.Hidden = $true}
     
            #Add column to Content Type
            $spContentType.FieldLinks.Add($spFieldLink)
        }
    }
 
    #Create Content Type on the site and update Content Type object
    $ct = $destWeb.ContentTypes.Add($spContentType)
    $spContentType.Update()
    write-host "Content type" $ct.Name "has been created"
}

$destWeb.Dispose()
______________________________________________________________________________

Monday, May 23, 2016

Send mail using JSOM

function SendEmail(from, to, body, subject) {
    var mailUrl = _spPageContextInfo.webServerRelativeUrl + "/_api/SP.Utilities.Utility.SendEmail";
    $.ajax({
        contentType: 'application/json',
        url: mailUrl,
        type: "POST",
        data: JSON.stringify({
            'properties': {
                '__metadata': {
                    'type': 'SP.Utilities.EmailProperties'
                },
                'From': from,
                'To': {
                    'results': [to]
                },
                'Body': body,
                'Subject': subject
            }
        }),
        headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        },
        success: function(data) {
            alert('Email Sent Successfully');
        },
        error: function(err) {
            alert('Error in sending Email: ' + JSON.stringify(err));
        }
    });
}

Delete folders in a document library using CSOM

            ClientContext clientContext = new SP.ClientContext.get_current();
            List docLib = clientContext.Web.Lists.GetByTitle(<LIBRARY NAME>);
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='FSObjType' />"
                + "<Value Type='Integer'>1</Value></Eq></Where></Query></View>";
            ListItemCollection items = docLib.GetItems(camlQuery);
            clientContext.Load(items);
            clientContext.ExecuteQuery();
            foreach (var item in items)
            {
                items.GetById(item.Id).DeleteObject();
                clientContext.ExecuteQuery();
            }

Thursday, April 28, 2016

Get an item value from a list using an ajax call


$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/lists/getbytitle('SampleList')/items?$filter=Title eq '" + XYZ + "'",
    type: "GET",
    async: false,
    headers: { "Accept": "application/json;odata=verbose" },
    success: function (data) {
        for (var i = 0; i < data.d.results.length; i++) {
            var item = data.d.results[i];
            value = item.CustomColumn;
        }
    },
    failure: function () {
        console.log("Unable to get value", "error");
    }
});

Friday, March 4, 2016

Setting permission for a library to a user using CSOM

            string siteURL = "<SITEURL>";
            ClientContext context = new ClientContext(siteURL);
            List list = context.Web.Lists.GetByTitle("<LIBRARYNAME>");
            User user = context.Web.EnsureUser(@"<DOMAIN\USERNAME>");
            list.BreakRoleInheritance(true, false);
            RoleDefinition roleDefinition = context.Web.RoleDefinitions.GetByName("<PERMISSION LEVEL>");
            RoleDefinitionBindingCollection collRoleDefinitionBinding = new RoleDefinitionBindingCollection(context);
            collRoleDefinitionBinding.Add(roleDefinition);
            list.RoleAssignments.Add(user, collRoleDefinitionBinding);
            context.ExecuteQuery(); 

How to launch a document by clicking a link to the file?

Word: <a href='ms-word:ofe|u|path/to/web/word/document.docx'>Link to document</a> Excel: <a href='ms-excel:o...