Top Menu

Friday, December 6, 2013

SharePoint 2013 - Claim Information in a Web Part

I ran into a situation where I have to see what is the claims information for the current SharePoint user. You have to have Windows Identity Foundation (WIF) 4.5 installed on the SharePoint server in order to run the code.

Following is the updated version of the code I found on MSDN:

Ref: http://msdn.microsoft.com/en-us/library/ee517271.aspx
using Microsoft.IdentityModel.Claims;

protected override void CreateChildControls()
{
try
  {
      this.Controls.Add(new LiteralControl(GetClaimInfo()));
  }
  catch (System.Exception exp)
  {
       this.Controls.Add(new LiteralControl(exp.Message));
  }
}

public string GetClaimInfo()
{
    String strClaim = null;
    IClaimsPrincipal icp = Page.User as IClaimsPrincipal;

    // Access IClaimsIdentity which contains claims
    IClaimsIdentity claimsIdentity = (IClaimsIdentity)icp.Identity;

            
    // Access claims
    foreach (Claim claim in claimsIdentity.Claims)
    {
     strClaim = claim.Issuer + " - " + claim.ClaimType + " - " + claim.Value + "<br/>" + strClaim;
    }
    return strClaim;
}
Here is another version of the code to get all the AD groups for a user:
public string GetClaimInfo()
        {
            String strClaim = null;
            string strGroup = null;

            IClaimsPrincipal icp = Page.User as IClaimsPrincipal;

            // Access IClaimsIdentity which contains claims
            IClaimsIdentity claimsIdentity = (IClaimsIdentity)icp.Identity;

            
            // Access claims
            foreach (Claim claim in claimsIdentity.Claims)
            {
                if (claim.ClaimType.EndsWith("groupsid"))
                {
                    strGroup = new System.Security.Principal.SecurityIdentifier(claim.Value).Translate(typeof(System.Security.Principal.NTAccount)).ToString();
                    strClaim = claim.Value + " - " + strGroup + "<br/> " + strClaim;
                }
            }
            return strClaim;
        }

Tuesday, December 3, 2013

PowerShell - Get List Size

Following is the PowerShell script to get the size of a SharePoint list by calculating the size of the attachments for all items in a list:
function GetListSize($List)
{
    [long]$listSize = 0
    $allAttachmentsFolder = $List.RootFolder.SubFolders["Attachments"]

    foreach ($listItem in $List.Items)
    {                   
        $listItemAttachments = $listItem.Attachments
        $attachmentsFolder = $allAttachmentsFolder.SubFolders[$listItem.ID]
        foreach($file in $listItemAttachments) 
        {            
            $listSize += $attachmentsFolder.Files[$file].Length
        }
    }

    $totalInMb = ($listSize/1024)/1024
    $totalInMb = "{0:N2}" -f $totalInMb

    return $totalInMb    
}

Ref: http://sharepoint.stackexchange.com/questions/12652/get-total-size-of-attached-files-on-all-list-items-in-sharepoint-2007with-powers

Friday, November 15, 2013

Detect iPhone through JavaScript

Here is a quick script to redirect iOS (iphone and iPad) users to the mobile page.
<html>
<head>
<script type="text/javascript">
   if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i))) {
        window.location = "Default_m.aspx";
        }
</script>
</head>
<body>
     This is a non mobile page.
</body>
</html>
This script should be inside the head tag for performance. Script will redirect user to mobile page before the body of the page gets rendered.

Monday, November 11, 2013

SharePoint 2013 - Download MySite Profile Picture

Scenario:
There was a requirement to download all the profile pictures from SharePoint 2013 MySite and save them in different folders (based on user's domain name). After downloading images need to be resized to 30x30 pixels.


Solution:
I wrote following command line utility to achieve the goal.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using System.Web;
using System.Net;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Configuration;

namespace MySiteDownloader
{
    class Program
    {
        static string strURL = ConfigurationManager.AppSettings["MySiteURL"];
        static string strDomain = ConfigurationManager.AppSettings["Domain"];
        static string strLogin = ConfigurationManager.AppSettings["Login"];
        static string strPassword = ConfigurationManager.AppSettings["Password"];
        

        static void Main(string[] args)
        {
            Console.WriteLine("MySite Downloader");
            Console.WriteLine("=================");

            GetProfilePictures();

            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        }

        static void GetProfilePictures()
        {
            try
            {
                string strAccount = null;
                string strProfilePicURL = null;
                string strFileName = null;
                Uri uri = null;

                WriteLog("Getting user profiles from " + strURL);

                using (SPSite site = new SPSite(strURL))
                {
                    SPServiceContext context = SPServiceContext.GetContext(site);
                    UserProfileManager upm = new UserProfileManager(context);
                    WriteLog("Total user profiles found: " + upm.Count);

                    foreach (UserProfile profile in upm)
                    {
                        strAccount = profile.GetProfileValueCollection("AccountName").ToString();

                        try
                        {
                            strProfilePicURL = profile.GetProfileValueCollection("PictureURL").ToString();
                        }
                        catch(System.Exception ex)
                        {
                            strProfilePicURL = "";
                        }

                        WriteLog(strAccount + " - " + strProfilePicURL);

                        if (strProfilePicURL != "")
                        {
                            uri = new Uri(strProfilePicURL);
                            strFileName = System.IO.Path.GetFileName(uri.LocalPath);

                            DownloadPicture(strProfilePicURL, strAccount.Split('\\')[0], strFileName);
                        }
                    }

                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        static  void DownloadPicture(string strPicURL, string strFolder, string strFile)
        {
            string FilePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + strFolder + "\\" + strFile.Replace("_MThumb", "");

            //File Download

            try
            {
                using (WebClient Client = new WebClient())
                {
                    if (!System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\" + strFolder))
                    {
                        System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\" + strFolder);
                    }

                    Client.Credentials = new NetworkCredential(strLogin, strPassword, strDomain);
                    Client.DownloadFile(strPicURL, FilePath);
                }

            }
            catch(System.Exception ex)
            {
                WriteLog(ex.ToString());
            }

            

            //Image Processing

            try
            {
                var image = Image.FromFile(FilePath);
                var newImage = ScaleImage(image, 30, 30);
                newImage.Save(FilePath.Replace("_MThumb", ""), ImageFormat.Png);
                //System.IO.File.Delete(FilePath);
            }
            catch (System.Exception ex)
            {
                WriteLog(ex.ToString());
            }

        }

        public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
        {
            var ratioX = (double)maxWidth / image.Width;
            var ratioY = (double)maxHeight / image.Height;
            var ratio = Math.Min(ratioX, ratioY);

            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);

            var newImage = new Bitmap(newWidth, newHeight);
            Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
            return newImage;
        }

        static void WriteLog(string strMessage)
        {
            Console.WriteLine(strMessage);

            string strLogMessage = string.Empty;
            string strLogFile = AppDomain.CurrentDomain.BaseDirectory;
            strLogFile += "MySiteDownloader.txt";
            StreamWriter swLog;

            strLogMessage = string.Format("{0}: {1}", DateTime.Now, strMessage);

            if (!File.Exists(strLogFile))
            {
                swLog = new StreamWriter(strLogFile);
            }
            else
            {
                swLog = File.AppendText(strLogFile);
            }

            swLog.WriteLine(strLogMessage);
            swLog.Close();

        }
    }
}
Note: Image re-sizing code has been copied from internet.

App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="MySiteURL" value="http://mysite" />
    <add key="Domain" value="US" />
    <add key="Login" value="Login" />
    <add key="Password" value="Password" />
  </appSettings>
</configuration>

Free E-Books by Microsoft

Yup, you read it right. Free e-books from Microsoft.
http://social.technet.microsoft.com/wiki/contents/articles/11608.e-book-gallery-for-microsoft-technologies.aspx


Wednesday, October 30, 2013

SharePoint - Tech Bytes: SharePoint 2010 - Creating a Visual Webpart

My team mate Neal posted this easy article about creating a Visual WebPart. Enjoy!

SharePoint - Tech Bytes: SharePoint 2010 - Creating a Visual Webpart: Overview Visual webparts wraps asp.net user control inside a classic webpart, so that programmer could work on ascx file as for any other ...


Friday, October 4, 2013

User Profile Properties through JSOM

Following is the code to get the current user's Profile Properties through JSOM (JavaScript Object Model) in SharePoint 2013.
<script src="/_layouts/15/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="/_layouts/15/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/_layouts/15/init.js" type="text/javascript"></script>
<script src="/_layouts/15/sp.runtime.js" type="text/javascript"></script>
<script src="/_layouts/15/sp.js" type="text/javascript"></script>
<script src="/_layouts/15/SP.UserProfiles.js" type="text/javascript"></script>

<script type="text/javascript">

    //$(document).ready(function(){
        SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');
    //});

    var userProfileProperties;

    function getUserProperties() {

        var clientContext = new SP.ClientContext.get_current();
        var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
        userProfileProperties = peopleManager.getMyProperties();
        clientContext.load(userProfileProperties);
        clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
    }

    // This function runs if the executeQueryAsync call succeeds.
    function onRequestSuccess() {
        var messageText = "<b>";
        if (userProfileProperties.get_userProfileProperties()['Title'] != "")
            messageText += userProfileProperties.get_userProfileProperties()['Title'];
        if (userProfileProperties.get_userProfileProperties()['SPS-Department'] != "")
            messageText += ", " + userProfileProperties.get_userProfileProperties()['SPS-Department'];
        if (messageText.length > 5)
            messageText += "<br/>";
        if (userProfileProperties.get_userProfileProperties()['Office'] != "")
            messageText += userProfileProperties.get_userProfileProperties()['Office'];
        if (userProfileProperties.get_userProfileProperties()['WorkPhone'] != "")
            messageText += ", " + userProfileProperties.get_userProfileProperties()['WorkPhone'];
        messageText += "</b>";
        $get("results").innerHTML = messageText;
    }

    // This function runs if the executeQueryAsync call fails.
    function onRequestFail(sender, args) {
        $get("results").innerHTML = "Error: " + args.get_message();
    }

</script>

<div id="results"></div>

Tuesday, September 10, 2013

Adding Java Script File Reference to Head Tag from WebPart

Scenario: In my recent web part development project, I had to include a custom java script and css file for the UI of the web part. Now, I was writing all the C# code in CreateChildControl so reference to js file comes in the Body tag of the rendered HTML page. Ideally all the references to js and css should render inside the Head tag.

Solution: In CreateChildControl function, use following code:
using System.Web.UI.HtmlControls;

HtmlGenericControl MyJS = new HtmlGenericControl("script");
MyJS.Attributes.Add("type", "text/javascript");
MyJS.Attributes.Add("src", "/_layouts/15/scripts/Mobile_Custom.js");
Page.Header.Controls.Add(MyJS);

HtmlGenericControl MyCSS = new HtmlGenericControl("link");
MyCSS.Attributes.Add("rel", "stylesheet");
MyCSS.Attributes.Add("href", "/_layouts/15/Styles/Mobile_Custom.css");
Page.Header.Controls.Add(MyCSS);

Wednesday, August 7, 2013

SAML 2.0 Authentication

Recently I have been working on a project where one of our web part needs to use a third party API/services which requires SAML authentication.
Thought to make notes here how the SAML 2.0 authentication works. Here is a very good diagram from Google that explains what is the flow of authentication:


Tuesday, June 11, 2013

SharePoint 2007 - PowerShell to Get All Versions of a Document

This script will get details(URL, Size, Created by, Created Date, Attachment Size etc) of all the versions of the items/document in a list/library.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$SiteName = "http://MyDomaon.com/sites/portal"
$LogPath="C:\Temp"
$LogName="GetAllDocumentVersions.txt"

$Logfile = $LogPath + "\" + $LogName
New-Item -ItemType directory -Path $LogPath -Force -ErrorAction SilentlyContinue

#Check if file exists and delete if it does
If((Test-Path -Path $Logfile))
{
    Remove-Item -Path $Logfile -Force
}
 
#Create file and start logging
New-Item -Path $LogPath -Value $LogName –ItemType File -ErrorAction SilentlyContinue

Function LogWrite
{
   Param ([string]$logstring)

   Add-content $Logfile -value $logstring

}

$tempHeader = "ID`tTitle`tList/Lib URL`tDoc/Item Name`tVersion URL`tVersion`tSize(KB)`tCreated Date`tCreated By`tAttachment`tAttachment Size"
LogWrite $tempHeader
    
$site = New-Object Microsoft.SharePoint.SPSite($SiteName)
$spWeb = $site.OpenWeb()
foreach($List in $spWeb.Lists)
{

if(($List.BaseType -eq "GenericList") -and ($List.Hidden -eq $false))
{
    write-host "Processing: " $List.BaseType - $List.Title
    foreach($Item in $List.Items)
    {
        Try
        {
            [long]$AttachmentSize = 0
            $listItemAttachments = $Item.Attachments 
            foreach($file in $listItemAttachments) 
            {            
                $AttachmentSize +=  $file.Length 
            }
        }
        Catch [System.Exception]
        {
            $msg = "Error in getting attachment. ID:" + $Item.ID.ToString()
            #Write-Host $msg
            LogWrite $msg
        }
        
        foreach($version in $Item.Versions)
        {
            Try
            {
                #$createdBy = $version.CreatedBy.LoginName.split("#")
                $createdBy = $version.CreatedBy
                $tempList = $Item.ID.ToString() + "`t" + $version.ListItem.Title + "`t" + $SiteName + "/" + $List.RootFolder.Url+ "`tDispForm.aspx?ID=" + $Item.ID +"`t"+ $SiteName +"/" + $version.Url + "`t" + $version.VersionLabel + "`t" + $AttachmentSize + "`t" + $version.Created + "`t" + $createdBy + "`t" + $version.ListItem.Attachments + "`t" + $AttachmentSize
                #write-host $tempList
                LogWrite $tempList
            }
            Catch [System.Exception]
            {
                $msg = "Error in getting version. ID:" + $Item.ID.ToString() + " URL: " +  $SiteName +"/" + $version.Url
                #Write-Host $msg
                LogWrite $msg
            }
        }
    }
}

if(($List.BaseType -eq "DocumentLibrary") -and ($List.Hidden -eq $false))
{
    write-host
    write-host "Processing: " $List.BaseType - $List.Title
    
    foreach($Item in $List.Items)
    {
        #Get Published Version
        Try
        {
            $tempLib = $Item.ID.ToString() + "`t" + $Item.File.Title + "`t" + $SiteName + "/" + $List.RootFolder.Url+ "`t" + $Item.Name +"`t"+ $SiteName +"/" + $Item.Url + "`t" + $Item.File.UIVersionLabel + "`t" + $Item.File.length/1KB + "`t" + $Item.File.TimeLastModified + "`t" + $Item.File.Author + "`t" + "NA" + "`t" + "NA"
            #Write-Host $tempLib
            LogWrite $tempLib
        }
        Catch [System.Exception]
        {
            $msg = "Error in getting version. ID:" + $Item.ID.ToString() + " URL: " + $SiteName +"/" + $version.Url
            #Write-Host $msg
            LogWrite $msg
        }

        foreach($version in $Item.File.Versions)
        {
            #Get All Historical Versions
            Try
            {
                #write-host $version.ID + "`t" + $version.File.Title + "`t" + $version.Url + "`t" + $version.VersionLabel + "`t" + $version.Size + "`t" + $version.Created + "`t" + $version.CreatedBy+ "`t" + NA + "`t" + NA 
                #$createdBy = $version.CreatedBy.LoginName.split("|")
                $createdBy = $version.CreatedBy
                $tempLib = $Item.ID.ToString() + "`t" + $version.File.Title + "`t" + $SiteName + "/" + $List.RootFolder.Url+ "`t" + $Item.Name +"`t"+ $SiteName +"/" + $version.Url + "`t" + $version.VersionLabel + "`t" + $version.Size/1KB + "`t" + $version.Created + "`t" + $createdBy + "`t" + "NA" + "`t" + "NA"
                #write-host $tempLib
                LogWrite $tempLib
            }
            Catch [System.Exception]
            {
                $msg = "Error in getting version. ID:" + $Item.ID.ToString() + " URL: " + $SiteName +"/" + $version.Url
                #Write-Host $msg
                LogWrite $msg
            }
        }
    }
}

}

$spWeb.Dispose()

Write-Host
Write-Host "Press any key to continue..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Tuesday, May 7, 2013

PowerShell - Saving Site and Sub-site in XML file

Scenario:
I had a requirement today to get all personal sites (site collections) and the blog sites (sub-sites) under MySite Host Site and save in an XML file. 

Following powershell script does the trick for a web application: 

PowerShell Script:
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

$webs =  Get-SPSite -webapplication "http://mysite.domain.com"
$FilePath = "C:\Temp\MySites.xml"

Write-Host Getting all MySites...

$xml = "<PersonalSite>"
Foreach ($oneweb in $webs)
{
    $web = $oneweb.RootWeb

    if ($web.WebTemplate -eq "SPSMSITEHOST" -Or $web.WebTemplate -eq "SPSPERS")
    {
        $xml = $xml + "<Site>"
        $xml = $xml + "<MySite>" + $oneweb.URL + "</MySite>"
        Write-Host "Processing:" $oneweb.URL
            
        $spWeb = Get-SPweb $oneweb.URL
        foreach($subSite in $spWeb.Webs)
        {
            if ($subSite.WebTemplate -eq "BLOG")
            {
                $xml = $xml + "<Blog>" + $subSite.URL + "</Blog>"
            }
        }
        $spWeb.Dispose()

        $xml = $xml + "</Site>"
    }    
}
$xml = $xml + "</PersonalSite>"
#Write-Host $xml

$xml | out-File -FilePath $FilePath

Write-Host "XML file has been generate."
Write-Host "Press anyke to continue..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Result (MySites.xml):
<PersonalSite>
  <Site>
    <MySite>http://mysite.domain.com/my</MySite>
  </Site>
  <Site>
    <MySite>http://mysite.domain.com/my/personal/mjackson</MySite>
    <Blog>http://mysite.domain.com/my/personal/mjackson/Blog</Blog>
  </Site>
  <Site>
    <MySite>http://mysite.domain.com/my/personal/jdoe</MySite>
    <Blog>http://mysite.domain.com/my/personal/jdoe/Blog</Blog>
  </Site>
  <Site>
    <MySite>http://mysite.domain.com/my/personal/sman</MySite>
    <Blog>http://mysite.domain.com/my/personal/sman/Blog</Blog>
  </Site>
</PersonalSite>

Tuesday, April 23, 2013

SharePoint 2013 - App Development - End User - NothingButSharePoint.com

SharePoint 2013 - App Development - End User - NothingButSharePoint.com

PowerShell Script - Get the size of the Sites

I have tested this script on SharePoint 2013 to get the size of the sub-sites with in a Site Collection.

#Get Size of all Sub-sites in a Site Collection
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
# Function to calculate folder size
Function CalculateFolderSize($Folder)
{
    [long]$FolderSize = 0
    foreach ($File in $Folder.Files)
    {
        #Get File Size
        $FolderSize += $file.TotalLength;
        #Get the Versions Size
        foreach ($FileVersion in $File.Versions)
        {
            $FolderSize += $FileVersion.Size
        }
    }

    #Iterate through all subfolders
    foreach ($SubFolder in $Folder.SubFolders)
    {
        #Call the function recursively
        $FolderSize += CalculateFolderSize $SubFolder
    }

    return $FolderSize
}

$SiteURL = "http://MySPSite/sites/portal"
$Site = new-object Microsoft.SharePoint.SPSite($SiteURL)
foreach($Web in $Site.AllWebs)
{ 
    #Call function to calculate Folder Size
    [long]$WebSize = CalculateFolderSize($Web.RootFolder)
    #Get Recycle Bin Size
    foreach($RecycleBinItem in $Web.RecycleBin)
    {
        $WebSize += $RecycleBinItem.Size
    }
    $Size = [Math]::Round($WebSize/1MB, 2)
    Write-Host $web.Url ":`t" $Size "MB"
}

Expected Output:

Note: I found it from a colleague and thought to share.

Thursday, April 4, 2013

SharePoint Online - Change Master Page through CSOM

Scenario:
I had a requirement where one of our clients have a Team Site in SharePoint Online (Office 365) environment and the master page of that Team Site needs to be changed. 

Now the problem is _layouts/15/ChangeSiteMasterPage.aspx is not available in the Team Sites through Site Settings and Server Side code is not an option in SharePoint Online environment because Microsoft does not allow any server side deployment.

Solution:
The amazing Client-Side Object Model (JavaScript Object Model to be exact) saved the day. Here is the code:
<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">
    function ChangeMasterPage() {

        var context;
        var web;
        var strMasterPageUrl = '/_catalogs/masterpage/my_custom.master';

        context = new SP.ClientContext.get_current();
        web = context.get_web();

        web.set_customMasterUrl(strMasterPageUrl);
        web.set_masterUrl(strMasterPageUrl);
        web.update();

        context.executeQueryAsync(function () {

            alert("Master Page has been set to \n" + strMasterPageUrl);

        }, function (sender, args) {

            alert("Error: " + args.get_message());

        });
    }

    ChangeMasterPage();
</script> ​​​​ ​​​​

Tuesday, April 2, 2013

PowerShell - Change Master Page

Scenario:
I had to write a quick PowerShell script to change the Master Page for a SharePoint 2013 site. Thought to share it with the world.

Solution:
cls;

[void][reflection.assembly]::Loadwithpartialname("Microsoft.SharePoint")

$SiteUrl = "http://mySite1919/sites/MasterTest";
$NewMasterPage = "/_catalogs/masterpage/MasterPage_custom.master";

$Site=[Microsoft.SharePoint.SPSite]($SiteUrl);
$SiteWeb = $Site.openweb();
$SiteRelativeUrl = $Site.ServerRelativeUrl.TrimEnd('/');

Write-Host "Site: " $SiteUrl;
Write-Host "Current MasterPage: " $SiteWeb.CustomMasterUrl;

#Site Master Page
$SiteWeb.CustomMasterUrl = $SiteRelativeUrl + $NewMasterPage;
#System Master Page
$SiteWeb.MasterUrl = $SiteRelativeUrl + $NewMasterPage;

$SiteWeb.Update();

Write-Host "New MasterPage: " $SiteWeb.CustomMasterUrl

$SiteWeb.Dispose();

Friday, March 29, 2013

PowerShell - List Data Migration

Scenario:
I had to migrate data from ListA to ListB with the condition that values in Created By, Create Date, Updated By and Update Date columns must not be changed in ListB.

So I wrote this little PowerShell script to do the job.

Solution:
cls;

[void][reflection.assembly]::Loadwithpartialname("Microsoft.SharePoint")

$Site=[Microsoft.SharePoint.SPSite]("http://sharepoint01:1100")
$SiteWeb = $Site.openWeb()
$SourceList = $SiteWeb.Lists["ListA"]
$DestinationList = $SiteWeb.Lists["ListB"]

$ItemsColl = $SourceList.items

write-host "Total items found: " $SourceList.items.count

foreach ($Item in $ItemsColl) 
{

    write-host "Copying Item: " $Item["Title"]

    $NewItem = $DestinationList.items.Add()
    $NewItem["Title"] = $Item["Title"]
    $NewItem["Author"] = $Item["Author"]
    $NewItem["Editor"] = $Item["Editor"]
    $NewItem["Modified"] = $Item["Modified"]
    $NewItem["Created"] = $Item["Created"]
    $NewItem.Update()

}

$Web.dispose
$Site.dispose

write-host "All items have been copied successfully."

Wednesday, March 6, 2013

SharePoint 2007 - Top 100 Versioned Documents via SQL Query

In our local SharePoint environment the Content Database's size was going out of control and we have to identify the documents/items with the highest number of versions so that we can delete them and apply some sort of versioning limit to the document libraries.

I came across a treasure of SQL Queries at this post where Syed Adnan Ahmed has already written few excellent queries to analyze the CDB. My fav is to view the Top 100 versioned documents. 
SELECT TOP 100
Webs.FullUrl As SiteUrl, 
Webs.Title 'Document/List Library Title', 
DirName + '/' + LeafName AS 'Document Name',
COUNT(Docversions.version)AS 'Total Version',
SUM(CAST((CAST(CAST(Docversions.Size as decimal(10,2))/1024 As 
   decimal(10,2))/1024) AS Decimal(10,2)) )  AS  'Total Document Size (MB)',
CAST((CAST(CAST(AVG(Docversions.Size) as decimal(10,2))/1024 As 
   decimal(10,2))/1024) AS Decimal(10,2))   AS  'Avg Document Size (MB)'
FROM Docs INNER JOIN DocVersions ON Docs.Id = DocVersions.Id 
   INNER JOIN Webs On Docs.WebId = Webs.Id
INNER JOIN Sites ON Webs.SiteId = SItes.Id
WHERE
Docs.Type <> 1 
AND (LeafName NOT LIKE '%.stp')  
AND (LeafName NOT LIKE '%.aspx')  
AND (LeafName NOT LIKE '%.xfp') 
AND (LeafName NOT LIKE '%.dwp') 
AND (LeafName NOT LIKE '%template%') 
AND (LeafName NOT LIKE '%.inf') 
AND (LeafName NOT LIKE '%.css') 
GROUP BY Webs.FullUrl, Webs.Title, DirName + '/' + LeafName
ORDER BY 'Total Version' desc, 'Total Document Size (MB)' desc

Tuesday, March 5, 2013

SharePoint 2010 - Security Trimming

I came across a requirement where I have to hide the Ribbon for the readers in SharePoint 2010.
Following is the snippit of the control to do the magic:

<Sharepoint:SPSecurityTrimmedControl runat="server" Permissions="ManageLists">
      Your ASP.NET control goes here
</SharePoint:SPSecurityTrimmedControl>

Permission values could be following:
  • ManageLists
  • ManageWeb

Tuesday, January 29, 2013

Friday, January 18, 2013

SharePoint 2013 - Administration Accounts

Multiple Server Farm

To manage SharePoint with multiple servers you need three types of roles/accounts:
Account Purpose
SQL Server service accountSQL Server prompts for this account during SQL Server Setup. This account is used as the service account for the following SQL Server services:
  • MSSQLSERVER
  • SQLSERVERAGENT
If you are not using the default instance, these services will be shown as:
  • MSSQL<InstanceName>
  • SQLAgent<InstanceName>
Setup user accountThe user account that is used to run:
If you run Windows PowerShell cmdlets that affect a database, this account must be a member of the db_owner fixed database role for the database.
  • Setup on each server computer
  • SharePoint Products Configuration Wizard
  • The Psconfig command-line tool
  • The Stsadm command-line tool
  • This account needs local admin access on the machine to run the SharePoint Setup.
Server farm accountThis account is also referred to as the database access account.
This account has the following properties:
  • It's the application pool identity for the SharePoint Central Administration website.
  • It's the process account for the Windows SharePoint Services Timer service.
  • This does not have to be the local account.


Start the installation with Setup user account and in SharePoint Configuration Wizard you will specify SQL Server service instance (because it will be on other server inside the farm) and Farm Account access.

Single Server Farm

To manage single server farm, all three roles can be handled by one account. So you need only local account (Setup user account) to do all the installation and configurations.

Start the installation with Setup user account and SharePoint Configuration Wizard will automatically pickup the SQL Server Instance and assign Setup user account as Farm account. 
See the single farm installation in here.

Ref: http://technet.microsoft.com/en-us/library/cc263445.aspx

SharePoint 2013 - Setup Development Environment

Pre-Requisite: Have your virtual machine ready with Microsoft Windows 2012 installed on it.

It will be a single server farm and following are the four steps to setup a SharePoint 2013 environment for development:
  1. Install Microsoft SQL Server 2012 (SP1)
    •  Select New SQL Server Stand-alone Installation
    • In the Installation wizard, under Feature Selection, select following features
  2. Install Microsoft SharePoint 2013
    • Install Pre-Requisite for SharePoint 2013
    • Launch SharePoint 2013 Setup and select Stand-alone installation on Server Type tab.
    • Launch SharePoint 2013 Product Configuration Wizard.
    • This wizard will perform configuration for SharePoint e.g. creating configuration database, registering features, provisioning Central Administration, creating sample data etc.
    • Launch Central Administration from Start menu
  3. Install Microsoft Visual Studio 2012
    • I am a developer so I will select all options to install
  4. Install Microsoft SharePoint Designer 2013

Official SharePoint Documentation

I have recently contributed to the official SharePoint documentation for developement. Check it out here: https://docs.microsoft.com/en-us...