Friday, December 28, 2012

SharePoint Object model code to delete items from large lists

Scenario: You have thousands of items in a SharePoint list and you want to delete them, in a way that query should not take longer to execute.

Solution:
1. Construct a CAML query for each item in a list you want to delete
2.  You can then pass on the aggregated CAML query for all the items to OOB ProcessBatchData() function as below:-
private static StringBuilder BuildBatchDeleteCommand(SPList list)
{
StringBuilder sbDelete = new StringBuilder();
 
                sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

                string command = "<Method><SetList Scope=\"Request\">" + list.ID +

                    "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";
  
foreach (SPListItem item in list.Items)
{
 sbDelete.Append(string.Format(command, item.ID.ToString())); 

 sbDelete.Append("</Batch>");
 return sbDelete;
}


  string strBatchDelete = BuildBatchDeleteCommand(list).ToString();
string strProcessBatch = site.RootWeb.ProcessBatchData(strBatchDelete);

This will place the items in a recycle bin. So to delete items from the recycle bin use
web.RecycleBin.Delete()

 Refer to below form post to do it using powershell:-

http://sharepoint.stackexchange.com/questions/26542/deleting-all-the-items-from-a-large-list-in-sharepoint

Wednesday, December 19, 2012

SharePoint: Finding assembly public key token value

Scenario: Sometimes when you are working with building custom solutions in SharePoint, before you deploy the solution binaries to GAC. You need to know the public key token.

Solution: To find public key token follow below steps:
1. Open visual studio command prompt
2. Navigate to "bin\debug" directory of the current solution
3. Type :-
    Sn  -T  Yourdllname.dll

SharePoint2010: Modify BreadCrumb links on a page

Scenario: How to modify/change breadcrumb navigation links on a specific page

Solution: In a Content editor webpart add below code
<script type=text/javascript>
document.getElementById('PlaceHolderTitleBreadCrumb').innerHTML =
"<a href='/pages/default.aspx'>HomePage</a> > 
<a href='/Departments'>Departments</a> >    
<a href='/Departments/IT'>IT</a> > IT News";
</script>
 
    

SharePoint2010: Hide BreadCrumb on a specific page

Scenario: How to hide a breadcrumb on a specific page

Solution: Place a Content Editor webpart on a page. and paste below code
<script type=text/javascript>
document.getElementById('PlaceHolderTitleBreadCrumb').innerHTML = "";
</script>

SharePoint2010:Delete\Remove masterpages, css files, themes on feature deactivation

Scenario: How to delete Masterpages, css files and themes from the respective galleries on feature deactivation

Solution: Write following code on feature deactivation event
SPFile myTheme = System.Web.GetFile("_catalogs/theme/MyCustom.thmx");
if (myTheme.Exists)
{  
  myTheme.Delete("_catalogs/theme/MyCustom.thmx");
}


 

Thursday, December 13, 2012

How to call\launch an exe and pass arguments to it using powershell

Scenario: How to launch an exe and pass arguments to it using powershell?

Solution:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction "SilentlyContinue"
$webApp = read-host "Enter the URL of the SharePoint Web app"
$contentDBs = Get-SPContentDatabase -WebApplication $webApp
foreach($cdb in $contentDBs)
{
& 'C:\test\test.exe' -webappurl $webApp -Dbname $cdb.Name
}

Wednesday, December 12, 2012

Sharepoint 2010: Stop Re-direction to Mysite person.aspx page

Scenario: On a multi-auth enabled SAML webapp, If you click under welcome sign-in control "About Me" it will re-direct user to My-Site person.aspx page. Its all good as long as, that logged in user has a mysite. But, in scenario were the users doesn't have a mysite created, It will prompt for user credentials, which might be annoying. But this is OOB SharePoint behavior.How can you stop this re-direction?

Solution: Actually, as soon as a user profile gets created for that logged in user, it will start re-directing user to person.aspx page. But, instead clients want to get re-directed to "userdisp.aspx" page.

Well,This can be done by deleting the user profile so that it will always gets re-directed to "userdisp.aspx". But, the profile gets re-created again. And in a scenario were there are thousands of user this solution is not viable.

Actually, behind the scenes, there is a OOB user control called "MySiteRedirection.ascx" that is tied to a delegate control "DelctlProfileRedirection" on userdisp.aspx page that does this re-direction. That control is tied to this userdip.aspx page via OOB feature named "MySite".

So the custom solution to stop the mysite re-direction will be to create your own custom user control, with no code (just empty default usercontrol) and place it under "_controltemplates" . Then create a feature.xml and elements.xml file to load your custom user control inside the "ProfileRedirection" delegate control, with a sequence number less than "100". If the sequence number is not set to less than 100, your custom control will not be loaded.

For more info about understanding OOB delegate controls refer to:-
http://www.helpmeonsharepoint.com/2012/04/sharepoint-delegate-controls.html

And to know how to customize and load your own controls refer to:-
http://panvega.wordpress.com/2008/10/12/sharepoint-delegate-controls/
http://sharepointmagazine.net/articles/custom-page-security-using-sharepoint-delegate-controls
http://blogs.msdn.com/b/sowmyancs/archive/2009/02/01/how-to-create-a-custom-delegate-control-with-vsewss-1-3.aspx

Wednesday, November 28, 2012

SAML webapp and rtfa cookie Log out issue SharePoint 2010

Scenario: Today I came across an issue on SAML enable multi-auth webapp on SharePoint 2010. The issue is that when I login as SAML user and then try to Log-out or Sign as different user. It doesn't log me out, meaning it doesn't redirect to appropriate STS login page.

Solution: The fix for this is two fold . One has to be done on ADFS by running below script

Set-ADFSRelyingPartyTrust -TargetName "SPS 2010 ADFS" -TokenLifetime 5

and the other script must be run on SharePoint Farm as below:-

$sts = Get-SPSecurityTokenServiceConfig

$sts.LogonTokenCacheExpirationWindow = (New-TimeSpan –minutes 1)
$sts.Update()
Iisreset
 
 
Detailed information can be found in Steve Peschka's blog:-
 
Note: "TokenLifeTime" value must be greater than "LogonTokenCacheExpirationWindow".

 

Wednesday, November 21, 2012

PowerShell Script to uninstall SharePoint solution pkg

Scenario: More often than not when I deliver solution pkg to test team or production, I create a quick PowerShell script that does the installation\uninstallation automatically. Having it here so that it can help me and others to quickly garb it.

Solution: Uninstall script:-

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

# assume the SolutionName.wsp is in the same directory as this script.

$ScriptDir = split-path -parent $MyInvocation.MyCommand.Path

$releaseDir = $ScriptDir + "\"

 

$SolutionID = "00000000-0000-00000-0000-000000000"

$Solution = get-spsolution | Where { ($SolutionID -eq $_.SolutionId) }

 

If($Solution -eq $null)

{ 

    Write-Host "Solution is not installed."

}

else

{

  #Check if solution is deployed in the farm

    If ($Solution.Deployed -match "True")

    {

        #Retract the  solution

        Write-Host "Retract Solution..."

        Uninstall-SPSolution -Identity $Solution

       

        # tell user to wait a few seconds for the retract to complete

        Read-Host "Wait 30 seconds for the solution to retract, then press Ok."

       

        # Remove the solution

        Write-Host "Remove Solution..."

        Remove-SPSolution -Identity $Solution

             

    }

    ElseIf($Solution.Deployed -match "False")

    {

        #retract the solution

        Write-Host "Removing Solution..."

        Remove-SPSolution -Identity $Solution       

    }
}
Install script:-

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

# assume the Solution.wsp is in the same directory as this script.

$ScriptDir = split-path -parent $MyInvocation.MyCommand.Path

$releaseDir = $ScriptDir + "\"

$SolutionId = "000000000-0000-0000-0000-00000000"

$Solution = Get-SPSolution | Where { ($SolutionId -eq $_.SolutionId) }

$wspFileName = "Solution.wsp"

$solutionFilePath   = $releaseDir + $wspFileName    

If($Solution -eq $null)

{

   # Add solution to the farm

    Write-Host "Adding solution to the farm"

    Add-SPSolution  $solutionFilePath

   

     #Deploy solution to the farm

    Write-Host "Deploying solution from " $solutionFilePath

    Install-SPSolution -Identity $wspFileName -GACDeployment 

}

PowerShell check if SharePoint feature is activated at farm scope

Scenario: Most of the times when you ship solution package you deliver PowerShell installation scripts, part of which would be activating the features. But before activating you may want to check if its already activated at a given scope. And if activated already skip it. How to preform this check?

Solution:
$featureGuid = "11075dtfg-cb48-48a0-8b21-001ac2d"

$feature=(Get-SPFeature -Identity $featureGuid -ErrorAction SilentlyContinue -Farm) -ne $null

if($feature -ne $true)
{
  #feature is not activated at the given scope so activate it
}

In the above you can replace "-Farm" with any of the other valid scopes.


Other way to do this and only works for Webapp,Site, and web scoped features.
$webApp = read-host "Enter the URL of the SharePoint Web app"    
$webApp2 = Get-SPWebApplication $webApp
$UpdateFeature = $webApp2.Features[$UpdateFeatureGuid]

if($UpdateFeature -eq $null)
{
#Feature is currently deactivated,Activate Feature #Update

Wednesday, November 7, 2012

How to delete webparts from webpart gallery using powershell

Scenario: Deleting multiple WebParts from WebPart gallery using PowerShell

Solution:
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | Out-null

$Url = 'http://portal.sharepoint.com'

$site = Get-SPSite $Url

$wpCatlog =[Microsoft.SharePoint.SPListTemplateType]::WebPartCatalog

$list = $site.GetCatalog($wpCatlog)

$wpID = New-Object System.Collections.ObjectModel.Collection[System.Int32]

foreach ($item in $list.Items)
{
  if($item.DisplayName.ToLower().Equals("webpartname1"))
  {   $wpID.Add($item.ID) }
}

foreach($wp in $wpID)

   $wpItem = $list.GetItemById($wp)
   $wpItem.Delete()
}
$list.Update()