December 10, 2013

Find All Checked-Out Files and Checked-In Files by Power Shell Script

Copy following code in power shell file and run it as administrator:-
   1:   [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
   2:  #Region MOSS2007-CmdLets
   3:  Function Get-SPWebApplication()
   4:  {  
   5:    Param( [Parameter(Mandatory=$true)] [string]$WebAppURL )
   6:    return [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($WebAppURL)
   7:  }
   8:  Function global:Get-SPSite()
   9:  {
  10:    Param( [Parameter(Mandatory=$true)] [string]$SiteCollURL )
  11:     if($SiteCollURL -ne '')
  12:      {
  13:      return new-Object Microsoft.SharePoint.SPSite($SiteCollURL)
  14:     }
  15:  }
  16:  Function global:Get-SPWeb()
  17:  {
  18:   Param( [Parameter(Mandatory=$true)] [string]$SiteURL )
  19:    $site = Get-SPSite($SiteURL)
  20:          if($site -ne $null)
  21:              {
  22:                $web=$site.OpenWeb();
  23:              }
  24:      return $web
  25:  }
  26:  #EndRegion
  27:   Function GetCheckedOutFiles()
  28:   {  
  29:      #Define 'Web Application URL' as Mandatory Parameter
  30:      Param( [Parameter(Mandatory=$true)] [string]$WebAppURL )
  31:      $WebApp=Get-SPWebApplication($WebAppURL)
  32:      #Write the CSV Header - Tab Separated
  33:   "Site Collection Name `t Site Name`t Library `t File Name `t File URL `t  Last Modified `t Checked-Out By" | out-file CheckedOutFiles.txt
  34:    write-host "start..."
  35:   #Arry to Skip System Lists and Libraries
  36:   $SystemLists =@("Converted Forms", "Master Page Gallery", "Customized Reports", "Form Templates", 
  37:                   "List Template Gallery", "Theme Gallery", "Reporting Templates",  "Solution Gallery",
  38:             "Style Library", "Web Part Gallery","Site Assets", "wfpub")
  39:     #Loop through each site collection
  40:    foreach($Site in $WebApp.Sites)
  41:     {
  42:      #Loop through each site in the site collection
  43:       foreach($Web in $Site.AllWebs)
  44:     {
  45:              #Loop through each document library
  46:              foreach ($List in $Web.GetListsOfType([Microsoft.SharePoint.SPBaseType]::DocumentLibrary))
  47:              {
  48:                  #Get only Document Libraries & Exclude Hidden System libraries
  49:                  if ( ($List.Hidden -eq $false) -and ($SystemLists -notcontains $List.Title) )
  50:                  {
  51:       #Loop through eadh Item
  52:        foreach ($ListItem in $List.Items)
  53:        {
  54:                    if( ($ListItem.File.CheckOutStatus -ne "None") -and ($ListItem.File.CheckedOutByUser -ne $null))
  55:        {
  56:                         #Log the data to a CSV file where versioning size > 0MB!
  57:                          "$($Site.RootWeb.Title) `t $($Web.Title) `t $($List.Title) `t $($ListItem.Name) `t $($Web.Url)/$($ListItem.Url) `t  $($ListItem['Modified'].ToString()) `t  $($ListItem.File.CheckedOutByUser)" | Out-File CheckedOutFiles.txt -Append
  58:         #*** Uncomment the below line to Check-in****#
  59:         $ListItem.File.Checkin("Checked in by Administrator")
  60:                 write-host $ListItem.Name
  61:        }
  62:                      }
  63:                  }
  64:              }
  65:     $Web.Dispose()         
  66:          }
  67:   $Site.Dispose()         
  68:      }
  69:      write-host "Checked out Files Report Generated Successfully!"
  70:  }
  71:  #Call the Function to Get Checked-Out Files
  72:  Write-Host "Enter the Web Application URL:"
  73:  $WebAppURL= Read-Host
  74:  GetCheckedOutFiles $WebAppURL 

If you have any questions you can reach out our SharePoint Consulting team here.

What Doesn’t Migrate with SharePoint Built in Import/Export and other known issues

​Item created by, created date, last modified date
Workflows (Definitions)
Workflow State & Tasks
Workflow History
Check in/check out state
Audit logs
Usage Logs that have not been processed
List configuration/app configuration
Site collection settings (Site Collection Ownership, Quota, email notification settings and a lot more)
Personalized views
Alerts
Recycle bin state/items including admin and user Recycle bin items
Lookup lists have issues due to remapping of object GUIDs
Object GUIDS are not preserved (This causes all sorts of weird things and can cause issues down the road. Empty folders may not migrate) This includes using import/export in STSADM or Windows Powershell, SOAP or Web services as well both result in loss of object id consistency including reparenting. The only way to avoid this is using the Content Migration object model.
Empty objects may not migrate (Discussion lists may have some problems related to this, and some folder structures may be remapped.)
Users that no longer exist are removed during import/export (related to ownership being re-written)
Surveys that are not completed will not be exported
Global Navigation inheritance issues (parenting challenges)
Known issues with conflicts when used with content deployment
No migration of features, solutions or assemblies associated with site/web (Must be manually migrated if separate farm and exist on destination)
Content overwritten if exists
Site dependencies on Site Collection Gallery lists (example if you migrate a web the parent site collection may have galleries that the web uses i.e. galleries include some look and feel, masterpages, images, features, and webparts.) known to have issues (Need more detail)
No list level migration (granularity is site level in 2007; Windows Powershell SharePoint Cmdlet in 2010 gives you list level) Thanks @toddklindt
Scale limitations (reliability goes down the larger the site <25gb add="" as="" best="" br="" case="" compression="" database="" databases="" dedicated="" exports="" fidelity="" higher="" if="" increases="" is="" it="" large="" likelihood="" migration="" no="" note:="" parameter="" that="" the="" will="" work.="" you=""> Portal Template Global Nav known to have issues (Need detail. Problem appears to be associated with site collection property loss)
Security remapping AD group challenges for groups between 2 untrusted forests
Versions of aspx pages (Need more detail)
Can’t change site template during migration
Can’t consolidate sites during migration
No good list of what fails to import
blocked file types
files over max file size
Objects that don’t contain objects may not be migrated (See comments in Gary LaPointe’s Export lists blog)
Post migration sync (No way to migrate again. If template already chosen or not blank)
No support between farms of different builds and versions. Have to be exact same version number (This may be different in 2010).
No ability to target a specific content without manual intervention (limiting all others or setting capacity high)
You can experience problems if you re-run Stsadm on site content that has already been imported. If that occurs, all list items that are not document libraries are duplicated on the target site.​


If you have any questions you can reach out our SharePoint Consulting team here.

November 13, 2013

“Value does not fall within expected range” Issue

Problem :- "Value does not fall within expected range”

Solution :-
​1.    Go to “Central Admin” 
2.    Click on “Manage Web Application” 
3.    Select your Web Application
4.    Click on “General Setting” in ribbon 
5.    Click on “Resource Throttling” (Refer Image1) 
6.    Edit the value of “List View Threshold”(Refer Image2)​ 
7.    Click on “Ok” button 
8.    Now check your application

Image 1



Image 2



If you have any questions you can reach out our SharePoint Consulting team here.

Power Shell script execution issue

​If you are getting this type of error "File C:\Projects\test.ps1 cannot be loaded because the execution of scripts is disabled on this system" then resolved it by following steps:-

Determine power cell script is enabled or not run below command
    get-executionpolicy
Enabled power cell script run below command
    set-executionpolicy unrestricted

To execute the Set-ExecutionPolicy command, you must have administrator permission and for Windows Vista / Windows Server 2008 and later versions you have to open the PowerShell command prompt with Run as Administrator. Otherwise you will get the below error



If you have any questions you can reach out our SharePoint Consulting team here.

Fix the issue of “This file type is blocked by Sharepoint due to security risk”

​If you are getting this type of error "File C:\Projects\test.ps1 cannot be loaded because the execution of scripts is disabled on this system" then resolved it by following steps:-

Determine power cell script is enabled or not run below command
    get-executionpolicy
Enabled power cell script run below command
    set-executionpolicy unrestricted

To execute the Set-ExecutionPolicy command, you must have administrator permission and for Windows Vista / Windows Server 2008 and later versions you have to open the PowerShell command prompt with Run as Administrator. Otherwise you will get the below error



If you have any questions you can reach out our SharePoint Consulting team here.

October 30, 2013

Solution of the issue “field type is not installed properly. go to the list settings page to delete this field”

Problem :- “field type is not installed properly. go to the list settings page to delete this field”
Solution
Problem :- “field type is not installed properly. go to the list settings page to delete this field”
Solution
1.   Log In in SQL Server
2.   Select your appropriate database
3.   Go to query window and run following query.it will display all record which field have blank type.

   1:  Select Definition,* from dbo.ContentTypes where ISNULL(Definition,'0')<>'0' 
   2:   and Definition like '<Field Type=""%'
4.   Now run following query in your query window.it will delete all the site columns which field type is blank.

   1:  delete from dbo.ContentTypes where ISNULL(Definition,'0')<>'0' 
   2:   and Definition like '<Field Type=""%'
5.   Now check your site columns page URL (../_layouts/mngfield.aspx). Error will disappear.​

If you have any questions you can reach out our SharePoint Consulting team here.

Export& Import Content Type by powershell script

Export Content Type by power cell script:-

clear

   1:  write-host "Start..."
   2:  $sourceWeb = Get-SPWeb -Identity "http://br53:3000/"
   3:  write-host $sourceWeb.ContentTypes
   4:  #
   5:  $xmlFilePath = "C:\Script-SiteContentTypes.xml"
   6:  #
   7:  #Create Export File
   8:  New-Item $xmlFilePath -type file -force
   9:  #Export Content Types to XML file
  10:  Add-Content $xmlFilePath "<?xml version=`"1.0`" encoding=`"utf-8`"?>"
  11:  Add-Content $xmlFilePath "`n<ContentTypes>"
  12:  $sourceWeb.ContentTypes | ForEach-Object {
  13:      if ($_.Group -eq "Custom Content Types") {
  14:          Add-Content $xmlFilePath $_.SchemaXml
  15:      }
  16:  }
  17:  Add-Content $xmlFilePath "</ContentTypes>"
  18:  $sourceWeb.Dispose()

Import Content Type by power cell script:-


   1:  #http://fazlulchowdhury.blogspot.in/2012/02/how-to-importexport-custom-content.html
   2:  clear 
   3:  $destWeb = Get-SPWeb -Identity "http://br53:1001/"
   4:  write-host $destWeb
   5:  $xmlFilePath = "C:\Script-SiteContentTypes.xml"
   6:  ##Create Site Content Types
   7:  $ctsXML = [xml](Get-Content($xmlFilePath))
   8:  $ctsXML.ContentTypes.ContentType | ForEach-Object {
   9:      #Create Content Type object inheriting from parent
  10:      $spContentType = New-Object Microsoft.SharePoint.SPContentType ($_.ID,$destWeb.ContentTypes,$_.Name)
  11:      #Set Content Type description and group
  12:      $spContentType.Description = $_.Description
  13:      $spContentType.Group = $_.Group
  14:      $_.Fields.Field  | ForEach-Object {
  15:          if(!$spContentType.FieldLinks[$_.DisplayName])
  16:          {
  17:              #Create a field link for the Content Type by getting an existing column
  18:  $spFieldLink = New-Object Microsoft.SharePoint.SPFieldLink ($destWeb.Fields[$_.DisplayName])
  19:              #Check to see if column should be Optional, Required or Hidden
  20:              if ($_.Required -eq "TRUE") {$spFieldLink.Required = $true}
  21:              if ($_.Hidden -eq "TRUE") {$spFieldLink.Hidden = $true}
  22:              #Add column to Content Type
  23:              $spContentType.FieldLinks.Add($spFieldLink)
  24:          }
  25:      }
  26:      #Create Content Type on the site and update Content Type object
  27:      $ct = $destWeb.ContentTypes.Add($spContentType)
  28:      $spContentType.Update()
  29:      write-host "Content type" $ct.Name "has been created"
  30:  }
  31:  $destWeb.Dispose()


If you have any questions you can reach out our SharePoint Consulting team here.

Export & Import Site Columns by power script

Export Site Columns by power script:


   1:  $sourceWeb = Get-SPWeb -Identity "http://br53:3000/"
   2:  $xmlFilePath = "C:\Script-SiteColumns.xml"
   3:  #Create Export Files
   4:  New-Item $xmlFilePath -type file -force
   5:  #Export Site Columns to XML file
   6:  Add-Content $xmlFilePath "<?xml version=`"1.0`" encoding=`"utf-8`"?>"
   7:  Add-Content $xmlFilePath "`n<Fields>"
   8:  $sourceWeb.Fields | ForEach-Object {
   9:      if ($_.Group -eq "Custom Columns") {
  10:          Add-Content $xmlFilePath $_.SchemaXml
  11:      }
  12:  }
  13:  Add-Content $xmlFilePath "</Fields>"
  14:  $sourceWeb.Dispose() 

Import Site Columns by power script:

clear

   1:  $destWeb = Get-SPWeb -Identity "http://br53:1001/"
   2:  $installPath = "C:"
   3:  #Get exported XML file
   4:  $fieldsXML = [xml](Get-Content($installPath + "\Script-SiteColumns.xml"))
   5:  $fieldsXML.Fields.Field | ForEach-Object {
   6:      #Configure core properties belonging to all column types
   7:      $fieldXML = '<Field Type="' + $_.Type + '"
   8:      Name="'
+ $_.Name + '"
   9:      ID="'
+ $_.ID + '"
  10:      Description="'
+ $_.Description + '"
  11:      DisplayName="'
+ $_.DisplayName + '"
  12:      StaticName="'
+ $_.StaticName + '"
  13:      Group="'
+ $_.Group + '"
  14:      Hidden="'
+ $_.Hidden + '"
  15:      Required="'
+ $_.Required + '"
  16:      Sealed="'
+ $_.Sealed + '"'
  17:      #Configure optional properties belonging to specific column types – you may need to add some extra properties here if present in your XML file
  18:      if ($_.ShowInDisplayForm) { $fieldXML = $fieldXML + "`n" + 'ShowInDisplayForm="' + $_.ShowInDisplayForm + '"'}
  19:      if ($_.ShowInEditForm) { $fieldXML = $fieldXML + "`n" + 'ShowInEditForm="' + $_.ShowInEditForm + '"'}
  20:      if ($_.ShowInListSettings) { $fieldXML = $fieldXML + "`n" + 'ShowInListSettings="' + $_.ShowInListSettings + '"'}
  21:      if ($_.ShowInNewForm) { $fieldXML = $fieldXML + "`n" + 'ShowInNewForm="' + $_.ShowInNewForm + '"'}
  22:      if ($_.EnforceUniqueValues) { $fieldXML = $fieldXML + "`n" + 'EnforceUniqueValues="' + $_.EnforceUniqueValues + '"'}
  23:      if ($_.Indexed) { $fieldXML = $fieldXML + "`n" + 'Indexed="' + $_.Indexed + '"'}
  24:      if ($_.Format) { $fieldXML = $fieldXML + "`n" + 'Format="' + $_.Format + '"'}
  25:      if ($_.MaxLength) { $fieldXML = $fieldXML + "`n" + 'MaxLength="' + $_.MaxLength + '"' }
  26:      if ($_.FillInChoice) { $fieldXML = $fieldXML + "`n" + 'FillInChoice="' + $_.FillInChoice + '"' }
  27:      if ($_.NumLines) { $fieldXML = $fieldXML + "`n" + 'NumLines="' + $_.NumLines + '"' }
  28:      if ($_.RichText) { $fieldXML = $fieldXML + "`n" + 'RichText="' + $_.RichText + '"' }
  29:      if ($_.RichTextMode) { $fieldXML = $fieldXML + "`n" + 'RichTextMode="' + $_.RichTextMode + '"' }
  30:      if ($_.IsolateStyles) { $fieldXML = $fieldXML + "`n" + 'IsolateStyles="' + $_.IsolateStyles + '"' }
  31:      if ($_.AppendOnly) { $fieldXML = $fieldXML + "`n" + 'AppendOnly="' + $_.AppendOnly + '"' }
  32:      if ($_.Sortable) { $fieldXML = $fieldXML + "`n" + 'Sortable="' + $_.Sortable + '"' }
  33:      if ($_.RestrictedMode) { $fieldXML = $fieldXML + "`n" + 'RestrictedMode="' + $_.RestrictedMode + '"' }
  34:      if ($_.UnlimitedLengthInDocumentLibrary) { $fieldXML = $fieldXML + "`n" + 'UnlimitedLengthInDocumentLibrary="' + $_.UnlimitedLengthInDocumentLibrary + '"' }
  35:      if ($_.CanToggleHidden) { $fieldXML = $fieldXML + "`n" + 'CanToggleHidden="' + $_.CanToggleHidden + '"' }
  36:      if ($_.List) { $fieldXML = $fieldXML + "`n" + 'List="' + $_.List + '"' }
  37:      if ($_.ShowField) { $fieldXML = $fieldXML + "`n" + 'ShowField="' + $_.ShowField + '"' }
  38:      if ($_.UserSelectionMode) { $fieldXML = $fieldXML + "`n" + 'UserSelectionMode="' + $_.UserSelectionMode + '"' }
  39:      if ($_.UserSelectionScope) { $fieldXML = $fieldXML + "`n" + 'UserSelectionScope="' + $_.UserSelectionScope + '"' }
  40:      if ($_.BaseType) { $fieldXML = $fieldXML + "`n" + 'BaseType="' + $_.BaseType + '"' }
  41:      if ($_.Mult) { $fieldXML = $fieldXML + "`n" + 'Mult="' + $_.Mult + '"' }
  42:      if ($_.ReadOnly) { $fieldXML = $fieldXML + "`n" + 'ReadOnly="' + $_.ReadOnly + '"' }
  43:      if ($_.FieldRef) { $fieldXML = $fieldXML + "`n" + 'FieldRef="' + $_.FieldRef + '"' }   
  44:      $fieldXML = $fieldXML + ">"
  45:      #Create choices if choice column
  46:      if ($_.Type -eq "Choice") {
  47:          $fieldXML = $fieldXML + "`n<CHOICES>"
  48:          $_.Choices.Choice | ForEach-Object {
  49:             $fieldXML = $fieldXML + "`n<CHOICE>" + $_ + "</CHOICE>"
  50:          }
  51:          $fieldXML = $fieldXML + "`n</CHOICES>"
  52:      }
  53:       #Set Default value, if specified  
  54:      if ($_.Default) { $fieldXML = $fieldXML + "`n<Default>" + $_.Default + "</Default>" }
  55:      #End XML tag specified for this field
  56:      $fieldXML = $fieldXML + "</Field>"
  57:       #Create column on the site
  58:      $destWeb.Fields.AddFieldAsXml($fieldXML.Replace("&","&amp;"))
  59:      write-host "Created site column" $_.DisplayName "on" $destWeb.Url
  60:      $destWeb.Dispose()
  61:  }​

If you have any questions you can reach out our SharePoint Consulting team here.

September 4, 2013

Add webpart to existing pages and add custom property meta data values to webparts through utility

Webparts adding to existing page and their custom property values which are meta data.
What i have done here is created powershell script to get taxonomy values like term store. powershell script will ask for central admin URL and Termstore name.
   1:  Add-PSSnapin Microsoft.SharePoint.PowerShell
   2:  #read parameters from command line
   3:  $CurrentDir= Split-Path -parent $MyInvocation.MyCommand.Definition
   4:  $timeStamp = (Get-Date).ToString("yyyyMMddhhmmss")
   5:  $logFile = $CurrentDir+ "\install_" + $timeStamp + ".log"
   6:  start-transcript -path $logFile -noclobber
   7:  $url = Read-Host "Enter Central admin url" 
   8:  #$url = "http://br66:14209/"
   9:  #$site = Get-SPSite -Identity "http://br66:14209/"
  10:  $web = Get-SPWeb $url
  11:  $taxonomySession = Get-SPTaxonomySession -Site $web.Site
  12:  $termStoreName = Read-Host "Enter TermStore Name"
  13:  $termStore = $taxonomySession.TermStores[$termStoreName];
  14:  Write-Host $termStore.Name $termStore.Id

   1:  foreach($item in $termStore.Groups)
   2:  {
   3:  Write-Host $item.Name
   4:  foreach($term in $item.TermSets)
   5:  {   
   6:   if($term.Name -eq "Site Section")
   7:   {
   8:    Write-Host $term.Name
   9:    $group = $term
  10:   Write-Host ": " $group.Name $group.Id 
  11:   foreach($termSetUnit in $term.Terms)
  12:   {
  13:    if($termSetUnit.Name -eq "Test and Measurement")
  14:    {
  15:     Write-Host $termSetUnit.Name   
  16:     foreach($termset1 in $termSetUnit.Terms)
  17:     {
  18:      Write-Host $termset1.Name
  19:      $TermName = $termset1
  20:      Write-Host ": " $TermName.Name $TermName.Id
  21:     }
  22:    }
  23:   }
  24:   
  25:   }
  26:  }
  27:  }
With this one text file will generate and copy and paste values in config file

   1:  <?xml version="1.0" encoding="utf-8" ?>
   2:  <ContentDeploymentConfig  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   3:   <SourceSite>http://br66:50001</SourceSite>
   4:   <LastRunTime>2013-01-01T12:00:00Z</LastRunTime>
   5:   <FeatureId>6717c859-64c8-4f7a-bfc0-873256087ac8</FeatureId>
   6:   <TaxonomyStoreID>0ded38c7-c349-4638-8ce8-e564fdd44922</TaxonomyStoreID>
   7:   <TaxonomySetID>ddb6225b-471c-4a6c-853f-bf4686dc88e6</TaxonomySetID>
   8:   <TaxonomyProductGUID>Products|9b34e73d-d4c2-4680-bd8c-5343f4b66463</TaxonomyProductGUID>
   9:   <TaxonomyServiceGuid>Services|bc612c4e-3267-4c6f-9ff1-0e99726e802f</TaxonomyServiceGuid>
  10:   <Countries>
  11:    <Japan>ja-jp</Japan>
  12:    <China>zh-cn</China>
  13:    <poland>pl-pl</poland>
  14:    <Russia>ru-ru</Russia>
  15:    <Germany>de-de</Germany>
  16:    <Spain>es-es</Spain>
  17:    <Brazil>pt-pr</Brazil>
  18:    <UnitedStates>en-us</UnitedStates>
  19:   </Countries>
  20:  </ContentDeploymentConfig>
Above red marked values i got from script.
After getting this values add webparts to existing pages of site.
Your page should be checked out above spmgr else it will not do checked out if it is written inside.

   1:  if (pageCategory.CheckOutType == SPFile.SPCheckOutType.None)
   2:                              {
   3:                                  pageCategory.CheckOut();
   4:                              }
   5:  SPLimitedWebPartManager spmgr = sourceProductsWeb.GetLimitedWebPartManager(pageCategory.Url.ToString(), PersonalizationScope.Shared);
   6:                              string exportedWebPartXml = string.Empty;
   7:                              if (WebpartTitle == "EngagementProductLinks")
   8:                              {
   9:                                  exportedWebPartXml = new StringReader(sourceSite.RootWeb.GetFileAsString(sourceSite.RootWeb.Url + "/_catalogs/wp/EngagementProductLinks.webpart")).ReadToEnd();
  10:                              }
  11:                              else if (WebpartTitle == "RightColumnPromotions")
  12:                              {
  13:                                  exportedWebPartXml = new StringReader(sourceSite.RootWeb.GetFileAsString(sourceSite.RootWeb.Url + "/_catalogs/wp/RightColumnPromotions.webpart")).ReadToEnd();
  14:                              }
  15:                              XmlTextReader reader = new XmlTextReader(new StringReader(exportedWebPartXml));
  16:                              System.Web.UI.WebControls.WebParts.WebPart importedWp = spmgr.ImportWebPart(reader, out outmessage);
  17:                              String spmgrWebPartTitle = string.Empty;
  18:                              if (spmgr != null)
  19:                              {                                
  20:                                  for (int j = 0; j < spmgr.WebParts.Count; j++)
  21:                                  {
  22:                                      spmgrWebPartTitle = spmgr.WebParts[j].Title;
  23:                                      if (spmgrWebPartTitle != WebpartTitle)
  24:                                      {
  25:                                          if (spmgr.GetZoneID(spmgr.WebParts[j]) == "ContactsZone")
  26:                                          {
  27:                                              countwebparts++;
  28:                                          }
  29:                                      }
  30:                                      if (spmgrWebPartTitle == WebpartTitle)
  31:                                      {
  32:                                          if (spmgr.GetZoneID(spmgr.WebParts[j]) == "ContactsZone")
  33:                                          {
  34:                                              sourceProductsWeb.AllowUnsafeUpdates = true;
  35:                                              spmgr.DeleteWebPart(spmgr.WebParts[j]);
  36:                                              pageCategory.Update();
  37:                                              sourceProductsWeb.AllowUnsafeUpdates = false;                                            
  38:                                          }
  39:                                      }
  40:                                      
  41:                                      if (spmgrWebPartTitle.Equals("Promotion Right Column"))
  42:                                      {
  43:                                          if (spmgr.GetZoneID(spmgr.WebParts[j]) == "ContactsZone")
  44:                                          {
  45:                                              sourceProductsWeb.AllowUnsafeUpdates = true;
  46:                                              WriteLog("found");
  47:                                              spmgr.DeleteWebPart(spmgr.WebParts[j]);
  48:                                              pageCategory.Update();                                                                                      
  49:                                              sourceProductsWeb.AllowUnsafeUpdates = false;                                           
  50:                                          }                                        
  51:                                      }
  52:                                  }
  53:                              } 
  54:  sourceProductsWeb.AllowUnsafeUpdates = true;                             
  55:  try
  56:              {
  57:                  if (pageCategory.CheckOutType == SPFile.SPCheckOutType.None)
  58:                  {
  59:                      pageCategory.CheckOut();                }               
  60:                  
  61:                  importedWp.ChromeType = PartChromeType.None;
  62:                  spmgr.AddWebPart(importedWp, "ContactsZone", index);
  63:                  spmgr.SaveChanges(importedWp);
  64:                  PropertyInfo[] SiteSecitonProperty = importedWp.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
  65:                  foreach (PropertyInfo sitesection in SiteSecitonProperty)
  66:                  {
  67:                      if (sitesection.Name == "SiteSectionTaxonomy")
  68:                      {
  69:                          sitesection.SetValue(importedWp, GUID, null);
  70:                          spmgr.SaveChanges(importedWp);
  71:                      }
  72:                      else if (sitesection.Name == "TermStoreID")
  73:                      {
  74:                          string TermStoreguid = ContentDeploymentConfigObj.TaxonomyStoreID;
  75:                          System.Guid guid = new Guid(TermStoreguid);
  76:                          sitesection.SetValue(importedWp, guid, null);
  77:                          spmgr.SaveChanges(importedWp);
  78:                      }
  79:                      else if (sitesection.Name == "TermSetID")
  80:                      {
  81:                          string TermSetguid = ContentDeploymentConfigObj.TaxonomySetID;
  82:                          System.Guid guid = new Guid(TermSetguid);
  83:                          sitesection.SetValue(importedWp, guid, null);
  84:                          spmgr.SaveChanges(importedWp);
  85:                      }
  86:                      else if (sitesection.Name == "Text")
  87:                      {
  88:                          sitesection.SetValue(importedWp, GUID, null);
  89:                          spmgr.SaveChanges(importedWp);
  90:                      }
  91:                  }                
  92:                  pageCategory.CheckIn(" Added Web Part " + importedWp.Title);                               
  93:              }
  94:              catch (Exception ex)
  95:              {
  96:                  WriteLog("Error " + ex.Message + "Page is " + pageCategory.Title);
  97:                  WriteLogFile(false, ex.Message + sourceProductsWeb.Url.ToString() + "/" + pageCategory.Url.ToString() + " giving error in site ");
  98:                  if (pageCategory.CheckOutType == SPFile.SPCheckOutType.Online)
  99:                  {                    
 100:                      pageCategory.CheckIn("Checkin");
 101:                  }               
 102:              }
 103:                              sourceProductsWeb.AllowUnsafeUpdates = false;

Above code is to add webparts and properties value to webparts.
If you have any questions you can reach out our SharePoint Consulting team here.

Get User's Properties from Active Directory through profile synchronization.

​User's Property in Active directory are there like City, Job, Birthday, Hire Date etc.
what i have done here is displaying current week's birthday(i.e Sunday to satureday) and hire date with total years of joining from active directory through userprofile synchronization.
Before i write code here, make sure that user profile does contains properties which you need, If it is not there than add that property. Also user must be there, user profile synchronization service must be started

   1:  SPSecurity.RunWithElevatedPrivileges(delegate()
   2:              {
   3:                  using (SPSite site = new SPSite(SPContext.Current.Site.RootWeb.Url))
   4:                  {
   5:                      using (SPWeb web = site.OpenWeb())
   6:                      {
   7:                          try
   8:                          {
   9:   
  10:   
  11:                              SPServiceContext spServiceContext = SPServiceContext.GetContext(site);
  12:                                                                                  
  13:   
  14:   
  15:                              UserProfileManager profileManager = new UserProfileManager(spServiceContext);
  16:                              if (profileManager == null)
  17:                                  return;
  18:                              
  19:                              startDate = DateTime.Now;
  20:                              while (startDate.DayOfWeek != DayOfWeek.Sunday)
  21:                              {
  22:                                  startDate = startDate.AddDays(-1);
  23:                              }
  24:                              endDate = startDate.AddDays(6);                            
  25:                              startdate = startDate.Day;
  26:                              startmonth = startDate.Month;
  27:                              enddate = endDate.Day;
  28:                              endmonth = endDate.Month;
  29:                              IEnumerator profileEnumerator = profileManager.GetEnumerator();
  30:                              while (profileEnumerator.MoveNext())
  31:                             
  32:                              {
  33:                                  UserProfile userProfile = profileEnumerator.Current as UserProfile;
  34:                                  if (SPContext.Current != null)
  35:                                  {
  36:                                      string userLoginName = userProfile["AccountName"].ToString();
  37:                                                                                               
  38:                                  }
  39:                                  if (userProfile == null)
  40:                                      return;
  41:                                  DataRow drbirthday = dtBirthday.NewRow();
  42:                                  DataRow drAnniversary = dtAnniversary.NewRow();
  43:                                  if (userProfile[PropertyConstants.Birthday].Value != null)
  44:                                  {
  45:                                      BirthdayDate = (DateTime)userProfile[PropertyConstants.Birthday].Value;
  46:                                      if ((BirthdayDate.Day >= startdate && BirthdayDate.Month == startmonth) && (BirthdayDate.Day <= enddate && BirthdayDate.Month == endmonth))
  47:                                      {
  48:                                          drbirthday["Name"] = userProfile[PropertyConstants.PreferredName].Value.ToString();
  49:                                          drbirthday["Date"] = BirthdayDate.Month + "/" + BirthdayDate.Day;
  50:                                          drbirthday["fullstring"] = Convert.ToString( drbirthday["Date"]) + "-" + Convert.ToString( drbirthday["Name"]);
  51:                                          dtBirthday.Rows.Add(drbirthday);
  52:                                          birthDayData.Text = birthDayData.Text + (birthDayData.Text == string.Empty? string.Empty: "; ") +Convert.ToString(drbirthday["fullstring"]);
  53:                                      }                                   
  54:                                  }
  55:                                  if (userProfile[PropertyConstants.HireDate].Value != null)
  56:                                  {
  57:                                      AnniversaryDate = (DateTime)userProfile[PropertyConstants.HireDate].Value;
  58:                                      if ((AnniversaryDate.Day == date && AnniversaryDate.Month == month ))
  59:                                      {
  60:                                          int todayyear = DateTime.Today.Year;
  61:                                          int Anniyear = AnniversaryDate.Year;
  62:                                          int totalAnniYear = todayyear - Anniyear;
  63:                                          drAnniversary["Name"] = userProfile[PropertyConstants.PreferredName].Value.ToString();
  64:                                          drAnniversary["Years"] = totalAnniYear;
  65:                                          drAnniversary["fullstring"] = Convert.ToString(drAnniversary["Name"]) + "-" + Convert.ToString(drAnniversary["Years"] + " years");
  66:                                          dtAnniversary.Rows.Add(drAnniversary);
  67:                                          AnniDayData.Text = AnniDayData.Text + (AnniDayData.Text == string.Empty? string.Empty: ", ") + Convert.ToString(drAnniversary["fullstring"]);
  68:                                      }                                    
  69:                                  }
  70:                              }
  71:   
  72:   
  73:                          }
  74:                          catch (Exception ex)
  75:                          {
  76:                              Common.ErrorLog(ex.Message + Environment.NewLine + ex.StackTrace, "GetUserBirthdayAnniversary", Microsoft.SharePoint.Administration.TraceSeverity.Unexpected);
  77:                          }
  78:   
  79:   
  80:                      }
  81:                  }
  82:              });
This will helps to get user's properties from Active Directory.

If you have any questions you can reach out our SharePoint Consulting team here.

Unable to load workflow actions from server SharePoint Designer 2010

Problem:

When trying to open any workflow in SharePoint Designer, Error gets fired like:

Unable to load workflow actions from the server….

While checking ULS logs, below exception was found:

SOAP exception: System.ArgumentException: An item with the same key has already been added. at
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at
System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value) at
Microsoft.SharePoint.SoapServer.WebPartPagesWebService.GetWorkflowActionsFromFeatureElements(UInt32 currentLcid) at
Microsoft.SharePoint.SoapServer.WebPartPagesWebService.FetchLegalWorkflowActions()

Looking to exception details it becomes clear that this error is something related with duplication.

Solution:

Check Farm Level Solutions:
Browse to Central administration ->Click System Settings ->Click Manage Farm Solutions.

Then,

Check Site Collection Level Solutions:
Browse to Site collection ->Click Site Actions ->Site Settings ->Solutions (under Gallery).

Put both of the browser windows side-by-side and see if you have anything activated at both scopes, means there is any solution which is deployed at farm level and the same solution is also uploaded and activated to solutions gallery at site collection level. If you find this, deactivating the particular solution at site collection level should do the trick to open workflows in SharePoint Designer.


If you have any questions you can reach out our SharePoint Consulting team here.

August 28, 2013

List all pages using specific Page Layout

clear
   1:  Add-PsSnapin Microsoft.SharePoint.PowerShell
   2:  filter Get-PublishingPages
   3:  {
   4:                  $pubweb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($_)
   5:      $query = new-object Microsoft.SharePoint.SPQuery
   6:                  $query.Query = "<Where><In><FieldRef Name='PublishingPageLayout' /><Values><Value Type='URL'>/_catalogs/masterpage/<Layout1.aspx></Value><Value Type='URL'>/_catalogs/masterpage/<Layout2.aspx></Value><Value Type='URL'>/_catalogs/masterpage/<Layout3.aspx></Value></Values></In></Where>"
   7:     
   8:                  $query.ViewAttributes = "Scope='Recursive'"
   9:      $pubweb.GetPublishingPages($query)   
  10:  }
  11:   
  12:  $str = Read-Host "Enter Site URL: "
  13:   
  14:  if($str -eq $null )
  15:  {
  16:                  Write-Host "Enter a valid URL"
  17:                  return
  18:  }
  19:   
  20:  $site = Get-SPSite -Identity $str
  21:  if($site -eq $null)
  22:  {
  23:                  Write-Host "Enter a valid URL"
  24:                  return
  25:  }
  26:   
  27:  $allweb = $site.Allwebs
  28:  foreach($web in $allweb )
  29:  {
  30:      $web | Get-PublishingPages | select Uri, Title, @{Name='PageLayout';Expression={$_.Layout.ServerRelativeUrl}}| Format-List
  31:  }

If you have any questions you can reach out our SharePoint Consulting team here.

Powershell Script Block To List ALL/Unused/Used Content Database


   1:  #Import Localized Data
   2:  #Import-LocalizedData -BindingVariable Message
   3:  Add-PsSnapin Microsoft.SharePoint.PowerShell
   4:  #This function is used to get standard content database list for Get-OSCContentDatabase
   5:  function Export-OSCContentDatabase
   6:  {
   7:  PARAM
   8:      (   
   9:          $ContentDatabases
  10:      )
  11:          $ContentDatabases | Select-Object -Property `
  12:                              @{Name="Url";Expression={
  13:                                  $_.WebApplication.Url
  14:                                                     }},`
  15:                              @{Name="ID";Expression={
  16:                                   $_.Id
  17:                                                     }},`
  18:                              @{Name="Name";Expression={
  19:                                   $_.Name
  20:                                                      }},`
  21:                              @{Name="WebApplication";Expression={
  22:                                   $_.WebApplication
  23:                                                      }},`
  24:                              @{Name="Server";Expression={
  25:                                   $_.Server
  26:                                                      }},`
  27:                              @{Name="CurrentSiteCount";Expression={
  28:                                   $_.CurrentSiteCount
  29:                                                      }},`
  30:                              @{Name="Status";Expression={
  31:                                   $_.Status
  32:                                   }} | Sort-Object -Property Name
  33:  }
  34:   
  35:  function Get-OSCContentDatabase
  36:  {          
  37:      [CmdletBinding(DefaultParameterSetName="UnUsedDatabase")]
  38:      PARAM
  39:          (
  40:              [Parameter(Mandatory=$false,Position=0,ParameterSetName='UsedDatabase')]
  41:              [switch]$UsedDatabase,
  42:              [Parameter(Mandatory=$false,Position=0,ParameterSetName='UnUsedDatabase')]
  43:              [switch]$UnUsedDatabase
  44:           )
  45:              [array]$arrContentDB = @()
  46:              try
  47:                  {
  48:                       Get-SPWebApplication -IncludeCentralAdministration | ForEach-Object{
  49:                       $arrContentDB += $_.ContentDatabases
  50:                                  }
  51:                  }
  52:                  catch [Exception]
  53:                  {
  54:                       #Catch and throw the terminating exception
  55:                       throw $Error[0].Exception.Message
  56:                  }
  57:                 
  58:                  #Check if content databases exist
  59:                  if($arrContentDB.Count -eq 0)
  60:                  {
  61:                       Write-Error $Message.NoContentDB
  62:                       return $null
  63:                  }
  64:                 
  65:                  $scriptContentDBOutput = @()
  66:                  $scriptContentDBOutput += Export-OSCContentDatabase $arrContentDB
  67:                 
  68:                  #List the content databases which are in use currently
  69:                  if($UsedDatabase)
  70:                  {
  71:                        Write-Host $Message.UsedDatabase
  72:                        $scriptContentDBOutput = $scriptContentDBOutput | Where-Object{$_.Status -eq "Online"}
  73:                        if($scriptContentDBOutput.Count -eq 0)
  74:                         {
  75:                            Write-Host $Message.ZeroUsedContentDB
  76:                            return $null
  77:                         }
  78:                  }
  79:                  #List the content databases which are not in use currently
  80:                  elseif($UnUsedDatabase)
  81:                  {
  82:                          Write-Host $Message.UnUsedDatabase
  83:                          $scriptContentDBOutput = $scriptContentDBOutput | Where-Object{$_.Status -ne "Online"}
  84:                          if($scriptContentDBOutput.Count -eq 0)
  85:                              {
  86:                                Write-Host $Message.ZeroUnusedContentDB
  87:                                return $null
  88:                               }
  89:                  }
  90:                  #List all content databases
  91:                  else
  92:                  {
  93:                          Write-Host $Message.AllDatabase
  94:                          if($scriptContentDBOutput.Count -eq 0)
  95:                            {
  96:                                Write-Host $Message.ZeroContentDB
  97:                                return $null
  98:                            }
  99:                  }
 100:                 
 101:                  $scriptContentDBOutput
 102:  }
 103:   
 104:  ##Uncomment Following Line to List Out All Content Database
 105:  Get-OSCContentDatabase
 106:   
 107:  ##Uncomment Following Line to List the content databases which are in use currently.
 108:  Get-OSCContentDatabase -UsedDatabase
 109:   
 110:  ##Uncomment Following Line to List the content databases which are not in use currently.
 111:  Get-OSCContentDatabase -UnUsedDatabase

If you have any questions you can reach out our SharePoint Consulting team here.

Add Empty option in SharePoint drop down (Choice) column

Issue:You would like to have a blank/null option in the drop down. But SharePoint won't take SPACE as a valid option. You could specify the field to "not required" and initially it will be blank. But once some value has been specified there is no way to go back to blank. So what is the solution?
Solution:Use ASCII code 0129. It is an empty character that SharePoint will accept as a valid option but it appears empty on the drop down. To enter the character,hold down the ALT key and type the number 0129.

If you have any questions you can reach out our SharePoint Consulting team here.

July 1, 2013

Nintex workflow menu not visible in site actions

It was resolved by following:
The following entries were missing and I added them manually and the world got peace!

   1:  <SafeControl Assembly="Nintex.Workflow.ProjectServer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=913f6bae0ca5ae12" Namespace="Nintex.Workflow.ProjectServer.ServerControls" TypeName="*" Safe="True" SafeAgainstScript="False" />
   2:  <SafeControl Assembly="Nintex.Workflow.ServerControls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=913f6bae0ca5ae12" Namespace="Nintex.Workflow.ServerControls" TypeName="*" Safe="True" />
   3:  <SafeControl Assembly="Nintex.Workflow.ServerControls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=913f6bae0ca5ae12" Namespace="Nintex.Workflow.ServerControls.WebParts" TypeName="*" Safe="True" />
Solution is taken from here: http://connect.nintex.com/forums/thread/21125.aspx

If you have any questions you can reach out our SharePoint Consulting team here.