Tuesday, April 18, 2017

Create site collection using CSOM

                string userName = WebConfigurationManager.AppSettings.Get("UserName");
                string password = WebConfigurationManager.AppSettings.Get("Password");
                string domain = WebConfigurationManager.AppSettings.Get("Domain");

                using (var ctx = new ClientContext("http://siteUrl/"))
                {
                    ctx.Credentials = new System.Net.NetworkCredential(userName, password, domain);
                    ctx.RequestTimeout = Timeout.Infinite;

                    var tenant = new Tenant(ctx);
                    var properties = new SiteCreationProperties()
                    {
                        Url = "http://siteUrl/sites/site1",
                        Owner = string.Format("{0}\\{1}",domain,userName),
                        Title = "Test Site",
                        Template = "STS#0"
                    };

                    SpoOperation op = tenant.CreateSite(properties);
                    ctx.Load(op, i => i.IsComplete);
                    ctx.ExecuteQuery();
                }

Monday, March 27, 2017

Get current user image using javascript

siteUrl+ "/_layouts/15/userphoto.aspx?size=M&accountname=" + _spPageContextInfo.userLoginName;

Thursday, January 5, 2017

How to Create an Export to Excel Link on Any List or Library for 2010 and 2013

Generate the below URL for any list / library

SiteURL/_vti_bin/owssvr.dll?CS=109&Using=_layouts/query.iqy&List={List ID}&View={View ID}&CacheControl=1


Ex:

http://SharepointSiteCollection:80/_vti_bin/owssvr.dll?CS=109&Using=_layouts/query.iqy&List={XXXXXXXX-XXXX-XXXX-XXXXXXXXX&View={XXXXXXXX-XXXX-XXXX-XXXXXXXXX}&CacheControl=1


Note : For List ID and View ID, you could get it from List Setting page and View page respectively

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

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...