Sunday, October 21, 2012

SharePoint 2010: Attach Disposition Workflow To Content Type using PowerShell

Hi Friends,

Many times we are needed to attach a "Disposition Workflow" with a Content Type in SharePoint 2010. This is pretty easy to accoplish. Please find the PowerShell to do this.

# Method Calling
AddWorkflowToContentType $site $ContentTypeName "Disposition Approval" "WFA" $TaskListName

#Method Definition
function AddWorkflowToContentType($site, $ctName, $WfName, $WfAssociationName, $TaxTaskList)
   {
    [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SharePoint')
    [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Office.Policy')
  
    [Guid]$wfTemplateId = New-Object Guid
    $web = $site.RootWeb
       $ct = $web.ContentTypes[$ctName]
       $culture = New-Object System.Globalization.CultureInfo("en-US")
       $template = $site.RootWeb.WorkflowTemplates.GetTemplateByName($WfName, $culture)
   
       if($template -ne $null)
       {                       
      $tasklist = $TaxTaskList
                     $historylist = "Workflow History"
                    
                        # Checking For WorkFlow History List; If not exists then create it
                        if(!$web.Lists[$historylist])
                        {
                            $web.Lists.Add($historylist, "A system library used to store workflow history information that is created in this site.  It is created by the Publishing feature.",
                            "WorkflowHistory", "00BFEA71-4EA5-48D4-A4AD-305CF7030140", 140, "100")
                           
       if (!$web.Features["00BFEA71-4EA5-48D4-A4AD-305CF7030140"]) {
                                Enable-SPFeature -Identity WorkflowHistoryList -Url $web.Url
                            }
      
                            $wfHistory = $web.Lists[$historylist]
                            $wfHistory.Hidden = $true
                            $wfHistory.Update()
                        }

                        # Checking For WorkFlow Task List; If not exists then create it
                        if(!$web.Lists[$tasklist])
                        {
                            $web.Lists.Add($tasklist, "This system library was created by the Publishing feature to store workflow tasks that are created in this site.", "WorkflowTasks", "00BFEA71-A83E-497E-9BA0-7A5C597D0107", 107, "100")
                        }
     
                        # Creating Workflow Association with Content Type
                        $association = [Microsoft.SharePoint.Workflow.SPWorkflowAssociation]::CreateSiteContentTypeAssociation($template, $WfAssociationName, $web.Lists[$tasklist], $web.Lists[$historylist])
                       
      $association.AllowManual = $false
                        #$association.AutoStartCreate = $true
                        $ct.AddWorkflowAssociation($association)
                        $ct.UpdateWorkflowAssociationsOnChildren($true, $true, $true, $false)
                        $association.Enabled=$true
                        $ct.Update()
                        $web.Update()
                        #$ct.WorkflowAssociations[0]           
       }
       else
       {
        Write-Error "Workflow Template not found"
                    Add-Content $logFileName "Workflow Template not found."
       }
   }

Happy Coding!!!

Prabhat

Monday, October 1, 2012

Mobile Entree For SharePoint 2010

Hi Friends,

This week I was involved in one POC on Mobile Development of SharePoint 2010. There I came around Mobile Entree Server(ME). Please check ME details:

Mobile Entree is a SharePoint solution for developing mobile solutions within SharePoint features and allow access to SharePoint APIs. Just install ME(Mobile Entree) on a SharePoint Farm and start using its power to create Mobile Apps instantly. Its allows number of great features to work with.

Refer below links:

1. http://blogs.msdn.com/b/seanpirtle/archive/2010/03/04/mobile-entree-s-mobile-sharepoint-solution.aspx
2. http://www.h3s-inc.com/services/Pages/Mobile-Entree-Development.aspx

Thanks
Prabhat

Tuesday, September 4, 2012

PowerShell To Change Set Default Page

PowerShell Script To Set a New Default Page:

$site = Get-SPSite http://server/sites/sitename
$web = $site.RootWeb
$folder = $web.RootFolder
$folder.WelcomePage = "Shared%20DocumentLibrary/CustomPage.aspx")
$folder.update()
$web.Dispose()
$site.Dispose()
 
Thanks 

Enable “Audit Log Reports” in Site Settings Page

Hello Friends,

Many times we need to generate Audit Reports in SharePoint Sites. To enable this link in Site Settings we need to activate "Reporting" Site Collection Level Feature.

PowerShell Script To Enable  “Audit Log Reports”:

Enable-SPFeature –identity "Reporting" -URL $url -ErrorAction SilentlyContinue

This way we can create number of scripts including Custom one.

Happy Reading!!!

Monday, September 3, 2012

PowerShell To create Retention Policies for Content Types

Hi Friends,

PowerShell is really a very powerful tool. Its not just a command prompt, we can also do coding into this.
Here I am using Powershell to create Policies on Content Types. I am creating Retention Policies and Auding Policy on Content Types. I am using One file "D:\Test\ContentTypes.txt" which contains data(content types) description according which we are applying Policies on those.

Data in the "D:\Test\ContentTypes.txt" will be in following format:

Name,Property,Period,PeriodType
One CTypeName,Created,15,Years
Two CTypeName,Created,25,Years
Three CTypeName,Created,Permanent,Years

function  abc()
{
$url = "http://server:1717/sites/TestTopLevelSite/"

$site = get-spsite $url
$web = $site.openweb()

Enable-SPFeature –identity "LocationBasedPolicy" -URL $url -ErrorAction SilentlyContinue

$CTList = Import-Csv D:\Test\ContentTypes.txt

echo "Processing Content Types"

ForEach ($item in $CTList){

$Name = $($item.Name)
$Property = $($item.Property)
$Period = $($item.Period)
$PeriodType = $($item.PeriodType)

$contentType = $web.ContentTypes[$Name]

if (($Period -ne "IND") -or ($Period -notcontains "MAX")) {

if($contentType){

[Microsoft.Office.RecordsManagement.InformationPolicy.Policy]::CreatePolicy($contentType, $null);

$newPolicy = [Microsoft.Office.RecordsManagement.InformationPolicy.Policy]::GetPolicy($contentType);

$newPolicy.Items.Add("Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration",
 "<Schedules nextStageId='3'>"+
 "<Schedule type='Default'>"+
 "<stages>"+
 "<data stageId='1' stageDeleted='true'></data>"+
 "<data stageId='2'>"+
 "<formula id='Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration.Formula.BuiltIn'>"+
 "<number>"+$Period+"</number>"+"<property>"+$Property+"</property>"+
 "<period>"+$PeriodType+"</period>"+
 "</formula>"+
 "<action type='action' id='Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration.Action.MoveToRecycleBin' />"+
 "</data>"+
 "</stages>"+
 "</Schedule>"+
 "</Schedules>");

$newPolicy.Items.Add("Microsoft.Office.RecordsManagement.PolicyFeatures.PolicyAudit",
 "<Audit>"+
 "<Update />"+
 "<View />"+
 "<CheckInOut />"+
 "<MoveCopy />"+
 "<DeleteRestore />"+
 "</Audit>");

$newPolicy.Update();

}
}
}

$web.Dispose()
$site.Dispose()

echo "Finished!!!"

}

Happy Reading!!!

SharePoint 2010 Solution Deployment Gets Hanged

Hi Friends,

During a SharePoint 2010 Solution Deployment its gets hanged and its hanged in "solution-deployment-solutionName.wsp-0".

To resolve this issue we should try the below steps:
1. Stop SPAdminV4
2. Start-SPAdminJob
3. Start SPAdminV4

Example :

$spAdminServiceName = "SPAdminV4"
Stop-Service -Name $spAdminServiceName
Start-SPAdminJob -Verbose
Start-Service -Name $spAdminServiceName

Thanks
Prabhat

Thursday, August 30, 2012

Use Powershell To Create Taxonomy Group, TermSet and Term in SharePoint 2010

Hi Friends,

Many times we are required to create Terms and TermSets in Managed Metadata Service Term Store using PowerShell. So here are cmdlets for that purpose.

$SPtaxonomySession=Get-SPTaxonomySession -Site "http://servername:11/"
$termStore=$SPtaxonomySession.TermStores["ManagedMetadataService"]
$temGroup=$termStore.CreateGroup("MMS Group")
$termSet=$temGroup.TermSets["Legal"]
$termOne=$termSet.CreateTerm("Legal Document",1033)
$termStore.CommitAll()

Thanks

Sunday, April 22, 2012

Bulk Delete in SharePoint List

Hi Friends,

I came through some requirement where I need to delete number of rows on the basis of some condition. Here we have choice of iterating all the list items and match the required condition if matched delete that list record. This is fine when we say its meeting the requirement. But when we look into its performance its not really a good solution. So here we have another very efficient solution of using ProcessBatchData of SPWeb. This batch technique is 10 times faster than list.Delete(i) technique and it minimizes the round trips to DB. Please find a very simple implementation of this you can alter this as per your requirement.


private void button1_Click(object sender, EventArgs e)
        {
            String strSourceList = "Bulk Delete List";//textBox2.Text.Trim();
            String strSite = "http://demunmmwb01d:9000/sites/uk/";//textBox1.Text.Trim();
            String strIds = String.Empty;
            try
            {
                if (!String.IsNullOrEmpty(strSite))
                {
                    if (!String.IsNullOrEmpty(strSourceList))
                    {
                        try
                        {
                            SPSite sourceSite = null;
                            try
                            {
                                sourceSite = new SPSite(strSite);
                            }
                            catch { }

                            if (sourceSite != null)
                            {
                                SPWeb sourceWeb = sourceSite.RootWeb;
                                if (sourceWeb != null)
                                {
                                    sourceWeb.AllowUnsafeUpdates = true;

                                    SPList sourceList = sourceWeb.Lists[strSourceList];
                                    StringBuilder sbDelete = new StringBuilder();
                                    sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

                                    if (sourceList != null)
                                    {
                                        string command = "<Method>" +
                                                         "<SetList Scope=\"Request\">" + sourceList.ID + "</SetList>" +
                                                         "<SetVar Name=\"ID\">{0}</SetVar>" +
                                                         "<SetVar Name=\"Cmd\">Delete</SetVar>" +
                                                         "</Method>";

                                        foreach (SPListItem objListItem in sourceList.Items)
                                        {
                                            sbDelete.Append(string.Format(command, objListItem.ID.ToString()));
                                        }
                                        sbDelete.Append("</Batch>");

                                        string retVal = sourceWeb.ProcessBatchData(sbDelete.ToString());

                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

Thanks
Prabhat