Tuesday, December 30, 2014

SharePoint 2013 Composed Looks Feature

Themes are the quick and easiest way to apply branding to SharePoint sites. Themes got changed over time in SharePoint's history. Now in SharePoint 2013, Themes are redesigned as "Composed Look" feature. As it sounds "Composed" look, it simply defines theming by combining design elements: Master page - AKA site layout, Color theme, Font schemes and background images.

No more thmx - PowerPoint themes which was introduced in SharePoint 2010, these themes can't be used in SharePoint 2013.

How to Apply composed look in SharePoint 2013? :
You can get the option to change SharePoint 2013 themes via "Change the Look" link from the Site Settings menu. Same is available under Look and Feel group of Site settings page.
 Change the look wizard and shows a thumbnail view of available designs. These designs are defined in a special list: "Composed Looks".
 

SharePoint 2013 Apply composed look:
To apply a composed look, Click on:
  • Site Settings >> Change the Look 
  • Select the new look to apply
  • Click on "Try it out" link >> SharePoint will give you the preview of your SharePoint site with the new theme 
  • Once you confirm by "Yes, Keep it", the new look and feel is applied to your SharePoint 2013 site.

Create composed look in SharePoint 2013:

In Short: To Create and Apply your custom theme in SharePoint 2013, There are three steps: 
Step 1: Create and upload theme elements: Master Pages, spcolor, spfonts, etc. to SharePoint.

Step 2: Register your Theme: Create a list item in "Composed Looks" list populating your theme artifacts. This will make your theme available in the design gallery at http://your-site-url/_layouts/15/designgallery.aspx

Step 3: Apply theme: You can apply theme from Site settings - Change the Look. You can also apply theme programmatically.
As illustrated above image, To create a custom composed look in SharePoint 2013, We need these artifacts ready. BTW, These design elements are reusable - Meaning can be used in any number of custom theme (or call it "Composed Look")!
  • Master Page - AKA - Site Layout
  • Color palette - AKA - Theme
  • Font scheme  - Optional
  • Background image  - Optional
Master Page URL - A reference to either a default or custom master page which is already uploaded to the master page gallery. This master page must accompanying a .preview file with the exact name - (with the .preview extension instead of .master). Otherwise, you won't get composed look preview.

Color Palette:
Color palette is nothing more than an normal XML file with a .spcolor extension. By default, color palette contains 89 Color slots of Key-Value pair.
E.g.
<s:color name="FooterBackground" value="7F333333" />
Where the first two digits: 7F represents the Transparency (optional) and rest for HEX value of the color.
  
SharePoint 2013 Color Palette Tool:
While editing the .spcolor file can be done with SharePoint Designer or notepad, Microsoft offers a nifty tool to make it simple. You can download color palette tool for SharePoint 2013 from Microsoft: http://www.microsoft.com/en-us/download/details.aspx?id=38182
This tool also lets you open a OOTB color palette and modify the colors. Once you built your customized color palette, You can upload it to the Theme Gallery (Site settings >> Themes >> 15 (Shortcut:  /_catalogs/theme/15/ ) and use it in a composed look. This gallery generally resides on the root web level and has theme files, Color palette and font schema inside 15 folder.

Font scheme:  (Optional)
SPFont File - This file contains all the font definitions for the Composed Look. The font scheme is also an XML file with a .spfont extension. There are 7 font slots with names such as title, navigation, and small-
heading. Font schemes can be easily edited with any Text editor or SharePoint designer.(Download any existing font scheme and do your changes)

Upload your .spfont file under: Site Settings > Themes > 15 > add new document then use that link to
the .spfont file in your Composed Look item.
Please note: The .spfont and .spcolor files must be in the /_catalogs/theme/15 folder, NOT in a sub-folder!
Color Pallette and Font Scheme reference: http://msdn.microsoft.com/en-us/library/office/jj945889.aspx

Background Image (Optional) - The image that will cover the entire background of your SharePoint pages.

Once you have all these artifacts ready, The next step is: Making an entry in Composed Looks list to pack it as a theme!

The "Composed Looks" List:

As the name suggests, This library contains all composed looks. This list actually contains master page URL, image URL, theme(color palette) URL, Font Scheme URL and Display Order. So, all of them together is a theme.

You can launch this list by: Site settings >> under "Web Designer Galleries" Group >> Composed looks:
Once you have the above artifacts ready and uploaded to respective folders, To make your own Composed Look, go to:
  • Site Settings > Composed looks under the Web Designer Galleries heading 
  • Click on add new item.  
  • From there you simply fill out the form giving the title, name and URLs to your custom Master Page (which may have custom CSS files linked inside) and other artifacts.
Once you have the entry for your theme in this list you can see your composed look/theme available on "Change Look" page.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, December 27, 2014

Delete Unique Permissions (Reset Broken Inheritance) In SharePoint 2013 using PowerShell

Got a requirement to reset customized permissions of a large set of SharePoint libraries and documents.You can reset the permission inheritance and delete unique permissions for a site/web/folder/item level where the inheritance was previously broken. E.g. for a library:
  1. Go to your library, Click on Library settings.
  2. In the settings page, under users and permissions, click on "Permissions for this document library"
  3. Click on "Delete Unique permissions" button in ribbon from Inheritance group.
For site level, You have to do this from: Site settings >> Site Permissions Link. And for folder/list item/file level, You can do the same by: Click on "Shared with" button from the ribbon (you can get the same from items context menu) >> Click on Advanced >> and click on "Delete unique permissions".
sharepoint remove unique permissions

The permission levels are set to Inherited from the parent and the permission level is updated to reflect the changes.Alright!

Needless to say, picking up each and every individual library and file to remove unique permissions is tedious, I wrote this PowerShell script to do the magic! Here is my PowerShell scripts to delete unique permissions at web, list, folder and list item levels.
Important: SharePoint 2013 permissions are inherited from Web level. So, If you break or reset inheritance at top level - All lists, libraries, folders and files will inherit permissions as in the parent web - customized permissions on list/folder/item level will go lost!

Reset Inheritance at site level using PowerShell:
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

#Variables for Web URL, List Name
$WebURL ="https://intranet.crescent.com/marketing"

#get the list object
$web = Get-SPWeb $WebURL

# Check if web has Unique permission - Root webs always uses Unique permission
if ( ($web.HasUniqueRoleAssignments) -and ($web.IsRootWeb -eq $false ) )
 {
      #Reset broken inheritance
      $web.ResetRoleInheritance()
      Write-host "Broken Inheritance Reset on web:" $web.URL
 }

SharePoint reset broken permissions on a list:
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

#Variables for Web URL, List Name
$WebURL ="https://intranet.crescent.com/marketing/"
$ListName ="Invoices" 

#get the list object
$List = (Get-SPweb $WebURL).lists.TryGetList($ListName)

# If List Exists with Unique permission
if ( ($list -ne $null) -and ($list.HasUniqueRoleAssignments) )
 {
      #Reset broken list inheritance
      $list.ResetRoleInheritance()
      Write-host "Broken Inheritance Reset on List:" $list.Title
 }

 <#To Reset Folder level inheritance, Use:
 foreach ($folder in $list.Folders) 
   {  
        if ($folder.HasUniqueRoleAssignments) 
        { 
            Write-Host "Resetting Folder inheritance at:" $folder.Url   
            $folder.ResetRoleInheritance()  
            $folder.Update() 
        } 
   }
 #>

Delete Unique permissions on all lists:
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

#Variable for Web URL
$WebURL ="https://intranet.crescent.com/marketing/"

#get Web object
$Web = Get-SPWeb $WebURL

#Get Lists with Unique permissions - Exclude Hidden lists
$ListColl =  $web.lists | Where-Object  {  ($_.HasUniqueRoleAssignments -eq $true)  -and ($_.hidden -eq $false) }

#Enumerate through each list and reset permission inheritance
foreach($list in $ListColl) #if($list) #Exists
 {
      #Reset list inheritance
      $list.ResetRoleInheritance()
      Write-host "Broken Inheritance Reset on List:" $list.Title
 }

Remove unique permissions on List Items:
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

#Variables for Web URL, List Name
$WebURL ="https://intranet.crescent.com/marketing/"
$ListName ="Invoices" 

#Get the list items with Unique permissions
$ListItems = (Get-SPweb $WebURL).lists.TryGetList($ListName).Items | Where {$_.HasUniqueRoleAssignments}

# If List Exists with Unique permission
Foreach($ListItem in $ListItems)
 {
      #Reset broken list item inheritance
       $ListItem.ResetRoleInheritance()
      Write-host "Broken Inheritance Reset on List Item:" $ListItem.URL
 }
We can also delete unique permissions of all list items in a single line as:
(Get-SPweb "https://intranet.crescent.com/marketing/").Lists["Invoices"].Items | Foreach-Object{ $_.ResetRoleInheritance() }
Related Posts:
Unique permissions are performance killers, in general! So, Avoid wherever possible!!


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, December 24, 2014

How to Create Federated Search Results in SharePoint 2013

What is Federated Search in SharePoint 2013:
As its name suggests, Federated search combines search results from multiple search engines. Federated search allows you to consume search indexes created by search engines outside of SharePoint.

How Federated Search works in SharePoint 2013?
Federated Search basically uses the index created by an another search engine. When a search query  triggered from SharePoint, it is forwarded to an external search engine and SharePoint gets the result from that index, displays the results from all configured federated sources in a single page to allow users to view results from different sources. E.g. you can set up federated search to return content indexed by an external search engine like Bing, twitter, etc.  

When to use Federated search?
Federation comes to play when you can not crawl the data source. Federated Search only works with indexes compatible with OpenSearch 1.0/1.1. So, its compatible with other SharePoint farms - You can federate search across farms, YouTube, Bing, Twitter, Flickr, Technet, Wikipedia, etc. (Federated search is not compatible with Google yet - There are some workarounds however!)

How to Create Federated Search in SharePoint 2013 :

There are two steps involved in creating federated search in SharePoint 2013.
  1. Create a Result source for federated content source
  2. Create a query rule to include federated search results in SharePoint search results page
Step 1: Create a Result source for federated content source
Search Scopes are replaced with "Result Sources" in SharePoint 2013. It just defines where to look for results. E.g. Search for only documents, people, etc. at specific source such as farm, site collection or site level.

How to Setup Federated Search in SharePoint 2013:
Federated search can be configured either at site level or centrally from SharePoint central administration site. Its a good idea to configure federated search in SharePoint 2013 at Central Admin, so that it can be utilized globally.
  • Go to Central Administration >>  Application Management >> Manage service applications >> Select your  Search Service Application.
  • You'll be presented with the Search Administration page.
But wait! Here, I'm creating a result source at site level from search center site. Below steps are similar whether you are configuring federated search from Central admin or from a local SharePoint site. Lets configure SharePoint 2013 federated search with Bing at site level.
  • To start with federated search in SharePoint 2013, Navigate to Site settings >> Click on  "Result Sources" link under Search group.
  • From the Manage result sources page, click "New Result Source" link. SharePoint 2013 Federated Search Configuration
  • Enter the name for your result source:
    •  I've entered "Bing Search Results" 
    • Choose the Protocol as "OpenSearch 1.0/1.1
    • Source URL - This is important. Source URL specifies our source for Federation.
      • For Bing - Enter: http://www.bing.com/search?q={?searchterms}&format=rss&Market=en-US
      • For Twitter - http://search.twitter.com/search.atom?q={searchTerms}
    • Specify the credentials. I've specified "Anonymous". Click on "Save" button to create result source.
      sharepoint 2013 federated search results

Step 2: Create a query rule to include federated search results in SharePoint search results page
Query rules defines the outcome (Such as Promoted Result, Result block, etc) of search query.
  • From site settings page, Click on "Query Rules" link this time.
  • Choose Result source as "Local SharePoint Results" and click on "New Query Rule" link.
    configure federated search in sharepoint 2013
  • In "Add Query Rule" page, Give a name to your query rule. Click on "Remove Condition" link under Query conditions. In "Actions" section, click on "Add Result Block" link, You'll be prompted with the "Add Result Block" dialog box.
    sharepoint 2013 create federated search
  • In Add Result block page:
    • Enter the title for your result block. I've entered "Bing Search Results for "{subjectTerms}" 
    • In Query section, Choose the search source as "Bing Search Results" we created in step 1.
    • Choose Number of items to show in search results.
    • Under Settings, Choose "This block is always shown above core results"option. Click "Ok" to create a result block.
  • Click Save to save your query rule.
sharepoint 2013 federated search bing

That's all. We've done with SharePoint 2013 federated search configuration. Lets see the Federated search results in action:
sharepoint 2013 federated search results



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sorry, something went wrong - The file FILENAME is locked for exclusive use by USER

Problem:  End-Users receives error when trying to edit a file. "Sorry, something went wrong - The file FILE-URL is locked for exclusive use by USER-NAME"
Root Cause:
When users edit the document in client applications such as Microsoft Office, SharePoint places a locks and renews it for every 10 minutes to prevent other users from modifying it. This lock is released automatically when the client application is closed, or after 10 minutes.

Solution: 
But in some scenarios, lock retains due to reasons like: Client application crash, Network connectivity issues, etc.  So, the simplest solution would be wait for 10 minutes for the lock to expire. But if you want the lock to be released immediately, You can unlock it programmatically!

There is no UI to unlock the locked files - as we do have for Check-in Checked-out files. So, Here is my solution to unlock the locked files using PowerShell.
 Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

#Variables for Web and File URLs
$WebURL ="http://intranet.crescent.com/support/"
$FileURL ="http://intranet.crescent.com/support/T1Support/Reports/ServiceTickets.xlsx" 

#Get Web and File Objects
$web = Get-SPWeb $WebURL
$File = $web.GetFile($FileURL)

#Check if File is Checked-out
if ($File.CheckOutType -ne "None")
 {
    Write-host "File is Checked Out to user: " $File.CheckedOutByUser.LoginName
    Write-host "Checked Out Type: " $File.CheckOutType
    Write-host "Checked Out On: "  $File.CheckedOutDate

    #To Release from Checkout, Ask the checked out user to Checkin
    #$File.Checkin("Checked in by Administrator")
    #Write-host "File has been Checked-In"
 }
 
 #Check if File is locked
 if ($File.LockId -ne $null)
 {
     Write-host "File is Loked out by:" $File.LockedByUser.LoginName
     Write-host "File Lock Type: "$file.LockType
     Write-host "File Locked On: "$file.LockedDate
     Write-host "File Lock Expires on: "$file.LockExpires

     #To Release the lock, use:
     #$File.ReleaseLock($File.LockId)
     #Write-host "Released the lock!" 
 }
Don't forget to un-comment the lines 32-33 if you find your files are locked out.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, December 23, 2014

Reset to Site Definition via PowerShell in SharePoint

To Re-ghost customized SharePoint sites and pages, We use "Revert to Site definition" via
  • Site Settings >> under Site Actions section, click on Reset to site definition 
  • Choose a specific page or entire site. Click on Reset! .
Reset to site definition - what does it do?
Reset to Site Definition removes any customizations and reverts the file back to the version originally deployed via the Site Definition. Customized pages are stored in the Content Database (a copy with changes) and are called unghosted. When you reset, the customized copy gets deleted and the version on the file system (the Site Definition version) is used.

Reset to Site Definition via PowerShell
When you have to reset a Site or List to its definition in bulk, PowerShell can be utilized.
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

$WebURL ="https://intranet.crescent.com/sites/operations/us"

$web =  Get-SPWeb $SiteURL
$web.RevertAllDocumentContentStreams();
$web.Update()
Lets do it for All sites under the site collection:
$SiteURL ="https://intranet.crescent.com"

#Revert all webs to site definition
Get-SPSite $SiteURL | Get-SPWeb | foreach-object {
 $_.RevertAllDocumentContentStreams()
 Write-Debug "Site Resetted: $($web.Url)"
 } 
 All customizations will be reverted once the operation completed.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, December 18, 2014

Configure SharePoint 2013 Object Cache Super User, Super Reader Accounts

SharePoint 2013 object cache stores metadata about SharePoint Server objects like SPSite, SPWeb, SPList, etc. on the Web Front Ends. SharePoint features such as publishing, content query web part, navigation, search query box , metadata navigation, etc fetches data from object cache, instead of hitting SQL Server when data needs to be retrieved from SharePoint objects to optimize page rendering.

For the object caching to work properly in SharePoint, We need to perform below tasks:
  • Create user accounts for "Portal Super Reader" and "Portal Super User" in your active directory
  • Grant web application policy on these user accounts on web applications.
  • Associate super user and super reader user accounts to web applications
These accounts simulates a reader and high-privileged users. If these accounts are not configured, you’ll see entries in the Windows event log with ids: 7362, 7363:
Object Cache: The super user account utilized by the cache is not configured. This can increase the number of cache misses, which causes the page requests to consume unnecessary system resources.

Event ID: 7362: The super user account utilized by the cache is not configured

Step 1: Create user accounts for "Portal Super Reader" and "Portal Super User" in your active directory
Go to your active directory, create two user accounts. In my case, I've created these accounts in my domain: "Crescent" as:
  • SPS_SuperUser
  • SPS_SuperReader
I've used the below PowerShell script to create these accounts in  Active directory:
Import-Module ActiveDirectory -ErrorAction SilentlyContinue
 
#Set configurations
$AccountPassword = "Password1"
#Convert to Secure string
$Password = ConvertTo-SecureString -AsPlainText $AccountPassword -Force
 
$Domain = "YourDomain.com"
#Specify the OU
$AccountPath= "ou=SharePoint,DC=YourDomain,DC=com"
 
#Create Super Reader Account
$Account="SPS_SuperReader"
New-ADUser -SamAccountName $Account -name $Account -UserPrincipalName $Account@$domain -Accountpassword $Password -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description="SharePoint 2013 Super Reader Account for object cache."}

#Create Super User Account 
$Account="SPS_SuperUser"
New-ADUser -SamAccountName $Account -name $Account -UserPrincipalName $Account@$domain -Accountpassword $Password -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description="SharePoint 2013 Super User Account for object cache."} 

Step 2: Grant web application policy on Super User, Super Reader accounts on all web applications
After account are created, we have to grant permissions at web application level. Navigate to
  1. SharePoint Central administration >> Application Management >> Manage web applications.
  2. Select your web application >> From the ribbon, click on User Policy button.
  3. Click on "Add" button from the User policies page.
  4. From the zones list, select "All zones" and click on next.
  5. In the Add users page, Enter the Super Reader user name. Under Permissions, Select "Full Read" option and Click on Finish button.
Repeat these steps for Super user account as well. In the 5th step, Enter the Super User account and choose "Full Control" permission. We got to repeat this procedure for all of our web applications. So, lets automate with PowerShell.

PowerShell script to grant web application user policy on all web applications:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Function Grant-UserPolicy($UserID, $WebAppURL, $Role)
{
    #Get the Web Application
    $WebApp = Get-SPWebApplication $WebAppURL
 
    #Convert UserID to Claims - If Web App is claims based! Domain\SPS_SuperReader to i:0#.w|Domain\SPS_SuperReader
    if($WebApp.UseClaimsAuthentication)
    {
        $UserAccount = (New-SPClaimsPrincipal -identity $UserID -identitytype 1).ToEncodedString()
    }
 
    #Crate FULL Access Web Application User Policy
    $ZonePolicies = $WebApp.ZonePolicies("Default")
    #Add sharepoint 2013 web application user policy with powershell
    $Policy = $ZonePolicies.Add($UserAccount ,$UserAccount)
    #Policy Role such as "FullControl", "FullRead"
    $PolicyRole =$WebApp.PolicyRoles.GetSpecialRole($Role)
    $Policy.PolicyRoleBindings.Add($PolicyRole)
    $WebApp.Update()
 
    Write-Host "Web Application Policy for $($UserID) has been Granted!"
}

#Get all Web Applications
$WebAppsColl = Get-SPWebApplication
foreach($webApp in $WebAppsColl)
{
    #Call function to grant web application user policy
    Grant-UserPolicy "Crescent\SPS_SuperReader" $webapp.URL "FullRead"
    Grant-UserPolicy "Crescent\SPS_SuperUser" $webapp.URL "FullControl"
}

This adds "Full Control" user policy to all of your web applications for the Super User account and "Full Read" user policy to Super Reader account. You can go back to Web application user policies page to verify that these accounts are added to web applications.

Step 3: Associate super user and super reader accounts to web applications
Once web application policies are created, We've to associate Super User and Super Reader accounts with Web applications either with classic STSADM or using PowerShell commands.

stsadm -o setproperty -propertyname portalsuperuseraccount -propertyvalue Crescent\sps_superuser -url "Web-app-url"

Same can be done with PowerShell as,
$WebApp = Get-SPWebApplication "http://web-app-url/"

$webApp.Properties["portalsuperuseraccount"] = "i:0#.w|Crescent\SPS_superuser"
$webApp.Properties["portalsuperreaderaccount"] = "i:0#.w|Crescent\SPS_superreader"

$WebApp.Update()
Lets use PowerShell to Add object cache accounts with all web applications:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get all Web Applications
$WebAppsColl = Get-SPWebApplication

foreach($webApp in $WebAppsColl)
{
    #Update with your SuperUser and Super Reader Ids
    $SuperReader = "Crescent\SPS_SuperReader" 
    #Convert to Claims ID
    $SuperReaderID = (New-SPClaimsPrincipal -identity $SuperReader -identitytype 1).ToEncodedString() 

    $SuperUser = "Crescent\SPS_SuperUser" 
    $SuperUserID = (New-SPClaimsPrincipal -identity $SuperUser -identitytype 1).ToEncodedString()

    #Set Super User and Super Reader accounts 
    $webApp.Properties["portalsuperreaderaccount"] = $SuperReaderID 
    $webApp.Properties["portalsuperuseraccount"] = $SuperUserID 

    $webApp.Update() 
    Write-host Object cache accounts updated for $WebApp.URL
}
On Publishing sites, object cache is turned ON automatically. Once its enabled at web application level, you can adjust object caching settings from "Site collection object cache " link under site collection administration settings .
Technet reference: Configure object cache user accounts in SharePoint Server 2013

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, December 17, 2014

The document could not be opened for editing. A Microsoft SharePoint foundation compatible application could not be found to edit the document

Problem: 
When trying to edit an Excel sheet from SharePoint 2010 document library, user received this error message - "The document could not be opened for editing. A Microsoft SharePoint foundation compatible application could not be found to edit the document"
The document could not be opened for editing. A Microsoft SharePoint foundation compatible application could not be found to edit the document
Troubleshooting Check List:
As the error message says, You must have Microsoft Excel installed in your client machine first! Follow this check list if you still getting this issue:
  • Download and install the Hotfix as in Microsoft KB: https://support.microsoft.com/en-us/kb/2823322, applicable when SharePoint 2010 with Office 2013 installed in client machines.
  • Make sure you are using 32 bit of "Internet Explorer" (c:\Program Files (x86)\Internet Explorer\iexplore.exe) browser (not Google chrome or Firefox!)
  • Make sure "SharePoint OpenDocuments Class" add-on is enabled in Internet Explorer's manage Addons page! Also under the "SharePoint open document class", click on "More information" then click "Allow on all sites" button.
  • Try re-registering "owssupp.dll" file  - run "Regsvr32 owssupp.dll"


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, December 16, 2014

Migrate SharePoint Users from One Domain To Another using Move-SPUser

Requirement:
During a acquisition, Our company decided to merge with an acquired company's AD by re-creating their user Ids in our AD. Also, the acquired company had a bunch SharePoint sites and we wanted to migrate them to our SharePoint environment.

That brought an another challenge of re-mapping user Ids with permission between domains. How do we migrate SharePoint users from one domain to another domain?

Solution: 
Well, In SharePoint 2007 days, I used STSADM to migrate users between domains:
Stsadm -o migrateuser -oldlogin domain\OldUserID -newlogin domain\NewUserID -ignoresidhistory 

Now with SharePoint 2013, Its replaced with the PowerShell cmdlet: Move-SPUser.
$WebURL="http://intranet.crescent.com"
$Web = Get-SPWeb $WebURL

$OldID="i:0#.w|Crescent\Opera1"
$NewID="i:0#.w|Crescent\Opera2"

$OldUser = $Web.EnsureUser($OldID)
Move-SPUser –Identity $OldUser -NewAlias $NewID -ignoresid -Confirm:$false

Rather moving users one by one, we prepared a CSV file, mapping users from one domain to new domain and used PowerShell script to migrate users in bulk.

Here is my CSV file structure:
sharepoint migrate users between domains

The csv file just maps old SAMAccountName with the new one.

PowerShell script to Migrate Users from one domain to another:
Add-PSSnapin Microsoft.SharePoint.PowerShell

#Import data from CSV file
$UserData = Import-CSV -path "C:\Accounts.csv"

#Iterate through each Row in the CSV
foreach ($Row in $UserData)
 {
    write-host "Processing user:" $row.Email

    #Site collection URL
    $siteURL ="https://intranet.crescent.com"
    $site = Get-SPSite $siteURL

    foreach($web in $site.AllWebs)
     {
        #Get All Users
        $UserColl = Get-SPUser -web $web.Url

        foreach ($User in $UserColl)
        {
            #Get values from CSV File
            $OldUserID= $Row.OldUserID.Trim()
            $NewUserID =$Row.NewUserID.Trim()
            $Email = $Row.Email.Trim()

            #Search for Old User Accounts
            if($User.UserLogin.Contains($OldUserID))
             {
                #Update the User E-mail
                Set-SPUser -Identity $User.UserLogin -Email $Email -Web $web.URL

                $NewUser = $User.UserLogin.replace($OldUserID, $NewUserID)

                #Migrate user from Old account to new account - migrate users to new domain
                Move-SPUser -Identity $User -NewAlias $NewUser -IgnoreSID -confirm:$false
                write-host "User Migrated: $($User.userlogin) at site $($web.Url)"
             }        
        
        } 
    }
}
This PowerShell script migrates users to new domain programmatically.

You can use Move-SPUser cmdlet in situations like:
  1. User Account deleted and Recreated in AD (with new Sid)
  2. User Account changed from One Domain to another domain
  3. User Account's Login ID is changed (such as due to last name change).

Migrate AD Groups in SharePoint from Old Domain to New Domain:
Use this PowerShell script to migrate active directory security groups from one domain to another domain.
#Old and New Groups
$OldLogin="OldDomain\Group"
$NewLogin="NewDomain\Group"

#Migrate AD Group
$Farm = Get-SPFarm
$Farm.MigrateGroup($OldLogin, $NewLogin)

Ok. Now, How to get all unique users and AD Groups to CSV file at site collection-web application or Farm level ? Well, use these PowerShell scripts:


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, December 15, 2014

Fix "This workbook cannot be opened because it is not stored in an excel services application trusted location" Error in SharePoint 2010

Problem: Got this error when trying to open a Excel Sheet stored in a SharePoint 2010 document library: "This workbook cannot be opened because it is not stored in an excel services application trusted location. To create an Excel Services Application trusted location, contact your system administrator"
This workbook cannot be opened because it is not stored in an excel services application trusted location

Solution: By default, Excel Services allows browser rendering on Workbooks that are in "Trusted location". Add your SharePoint library/site/webapp URL to Excel services trusted file location to get rid of this issue. Here is how to create excel services trusted location:
  • Navigate to SharePoint 2010 Central Administration site
  • Under Application Management, Click on Manage Service applications
  • Select "Excel Services Application" and click on "Manage" 
  • Click on "Trusted File Locations" and then Click on "Add Trusted File Location"
    add excel services trusted location in sharepoint 2010
  • Enter the URL of your SharePoint web app/site/library and choose "Trust Children"
    configure excel services trusted location
  • Click "OK" to save your configuration changes.
Now, your Excel sheet should render without any issue.

Technet Reference: Manage Excel Services trusted location - https://technet.microsoft.com/en-us/library/ff191194.aspx. Its also possible to manage trusted locations using PowerShell. Here is the reference: Excel Services cmdlets

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, December 11, 2014

Get All Users of SharePoint Farm-Web Application-Site Collection-Site using PowerShell

Requirement: Get all users of SharePoint environment.

PowerShell script to get all SharePoint users at Farm-Web Application-Site Collection-Web levels:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Output Report File
$currentLocation = (Get-Location).Path
$outputReport = $currentLocation + "\" + "SharePointUsers.csv" 
#Write CSV File Header

#Array to hold user data
$UserDataCollection = @() 

#Get All Web Applications and iterate through
$WebAppsColl = Get-SPWebApplication 
#To Get all Users from specific web application, Use: $WeAppsColl = Get-SPWebApplication "web-app-url"
#and remove line #12
 
foreach($WebApp in $WebAppsColl)
{
    Write-host "Scanning Web Application:"$WebApp.Name
    #Get All site collections and iterate through
    $SitesColl = $WebApp.Sites
    #To Get all Users from site collection, Use: $SitesColl = Get-SPSite "site-collection-url"
    #and remove lines between #11 to #20 and Line #55 "}"
    #get all users from site collection PowerShell
    foreach ($Site in $SitesColl) 
    {
        Write-host "Scanning Site Collection:"$Site.URL
        #Get All Webs and iterate through
        $WebsColl = $Site.AllWebs
        #To Get all Users from aq site, Use: $WebsColl = Get-SPWeb "web-url"
         #and remove lines between #11 to #28 and Lines #53, #54, #55 "}"

            foreach ($web in $WebsColl) 
            {
                Write-host "Scanning Web:"$Web.URL
                #Get All Users of the Web
                $UsersColl = $web.AllUsers  #get all users programmatically 
                    #list all users 
                    foreach ($user in $UsersColl) 
                    {
                           if($User.IsDomainGroup -eq $false) 
                            {
                                $UserData = New-Object PSObject
              
                                $UserData | Add-Member -type NoteProperty -name "UserLogin" -value $user.UserLogin.ToString()
                                $UserData | Add-Member -type NoteProperty -name "DisplayName" -value $user.displayName.ToString()
                                $UserData | Add-Member -type NoteProperty -name "E-mailID" -value $user.Email.ToString()

                                $UserDataCollection += $UserData
                            }
                    }
            $Web.dispose()
            }
         $site.dispose()
        }
    }    
    #Remove duplicates
    $UserDataCollection = $UserDataCollection | sort-object -Property  {$_.UserLogin } -Unique 

    #Remove duplicates and export all users to excel
    $UserDataCollection | Export-Csv -LiteralPath $OutputReport -NoTypeInformation
         
    Write-host "Total Number of Unique Users found:"$UserDataCollection.Length

This script can be used to get all users in site collection and export all users to excel.

Get All Unique Users in SharePoint Farm using PowerShell:
One liner PowerShell script to get unique users of the SharePoint Farm:
Get-SPSite -Limit All | Select -ExpandProperty AllWebs | select -ExpandProperty AllUsers | ? {$_.IsDomainGroup -ne $true} |  select -Unique LoginName


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, December 8, 2014

The installation of this package failed - Error in SharePoint 2013 Hotfix Installation

During a planned quarterly maintenance window, wanted to patch SharePoint 2013 servers with available hot fixes and cumulative updates (CU). As the first step, From Microsoft site http://technet.microsoft.com/library/dn789211%28v=office.14%29, requested hot fixes, Received an E-mail with hot fix links, downloaded those hot fixes and extracted to individual folders as in the below screen.
sharepoint cu the installation of this package failed
When trying to patch SharePoint 2013 servers with those hot fixes, installation failed suddenly with an error "The installation of this package failed".
sharepoint 2013 cu the installation of this package failed
Troubleshooting: 
Navigated to "%Tmp%" location and tried catching the root cause of the failure from the log file generated "opatchinstall.txt". Found these lines while scanning through the log file: "Getting the data from file <path location> UBERSRV_2.cab"
the installation of this package failed sharepoint foundation 2013
So, the catch here is, Hot fix installer is looking for "ubersrv_2.cab" file which we extracted into a different folder, and fails since it couldn't locate that file on the same folder it exists.

Solution:
Solution is simple! Just place all three extracted files together in the same folder and re-run the hot fix installation. It went through well after moving cab files in to the same folder where the hot fix installer ubersrv.exe was placed.
sharepoint 2013 service pack the installation of this package failed
Other cases:
  • In case, You cancelled the installation during patching, there are chances of the SharePoint binaries get corrupted! Repair SharePoint to fix the problem and then Re-run the installer.
  • Try download the patch again from Microsoft Technet site and try again. It could happen due to corrupted file 
  • Make sure you downloaded all the cab files along with the installer executable file (ubersrv_1.cab & ubersrv_2.cab) and placed all of them in a same directory!
  • Try Extracting the Installer (E.g. Setup.exe /extract:c:\Installer\) and then start the installation.


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Sunday, December 7, 2014

Disable UAC in Windows Server 2012 - SharePoint Best Practice

In SharePoint 2013 farms on Windows Server 2012, its annoying that we've to choose "Run as Administrator" every time when opening Central Administration, Command Prompt, SharePoint Management Shell, Windows PowerShell,etc. and failing so would introduce some weird issues such as: buttons and links missing in SharePoint Central Admin ribbon, Getting Access denied for Farm administrators, etc.
PowerShell too! When launching SharePoint Management shell, it scolds with "The local farm is not accessible. Cmdlets with featuredependencyId are not registered." On running any SharePoint cmdlets, "Cannot access the local farm. Verify that the local farm is properly configured, currently available, and that you have the appropriate permissions to access the database before trying again."
Although I'm a Domain Administrator and Local Server administrator, I've to pick "Run as Administrator" to get rid of these issues. I hate to do Right Click and choose "Run as Administrator" every time on these programs. So, Lets disable UAC in Windows Server 2012 in two steps. Here is how:
  • Go to Server Manager >> Choose "System Configuration" from Tools menu. (Shortcut: MSCONFIG)
  • Under Tools tab, Select "Change UAC Settings" and click on "Launch" button

  • Drag the slider down to "Never Notify" and click "OK".

But wait! We are not yet done. Make this registry change!
Unlike Windows Server 2008 R2, Sliding down UAC button to "Never notify" will NOT disable UAC in Windows Server 2012. You got to do one more fix in windows registry:
  • Open Windows Registry Editor (shortcut: regedit)
  • Navigate to the following registry key: [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]
  • In the Right Pane, locate the "EnableLUA" DWORD value. Double click and set its Value "0" (zero)
  • Exit Registry Editor and then restart your Server.
You can achieve the registry fix with PowerShell. Just run these commands in Windows PowerShell.
Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLUA" -Value "0"
Shutdown -r -t 0 
This script disables UAC and restarts your Server automatically!

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Fix Quick Edit Disabled in SharePoint 2013 Issue

Datasheet view is now called "Quick Edit" in SharePoint 2013. It provides a nice flexible Excel like editor to bulk edit, copy-paste list items and metadata. Similar to a spreadsheet you can create, change and delete items in the grid. As with the new name, quick edit brought many new features in SharePoint 2013, such as:
  1. You can Edit Managed Metadata columns (Still Rich text columns are not editable in Quick Edit! content type change can't be done from quick edit!!)
  2. It works just fine in other browsers ( I tested with Firefox and Chrome), where SharePoint 2010 Datasheet view was working ONLY with internet explorer 32 bit version.
  3.  No more Active-X control dependencies. Quick edit doesn't need Office access run time engine now!
  4. It supports Filters now! Remember the pain of losing filters on datasheet views in those old days?
You can launch quick edit mode either from "Quick Edit" button in List Tab, or clicking "Edit" link as in the below screen.
quick edit not working in sharepoint 2013
Quick edit is not working in SharePoint 2013?
In my SharePoint environment, few users having trouble with quick edit. Found Quick Edit button on the "List" tab is disabled (grayed out) with an error message "This control is currently disabled" and "Edit" link missing! How to enable quick edit in SharePoint 2013?
sharepoint 2013 quick edit not working
Here is my check list to troubleshoot quick edit not working issue:
  1. Check Quick Edit is Enabled: To enable/disable quick edit in SharePoint 2013, you need to navigate to: List Settings >> Advanced settings page >> Scroll down and Under quick edit option,  choose "Yes" and then click OK.
    sharepoint 2013 list quick edit disabled
  2. Remove the Group By: If you have grouping enabled in your Views, You got to remove it! If you group list or library items in SharePoint 2013, quick edit (Datasheet View) option is disabled. remove "Group By" selection by setting it to none.
  3. Change the View style to default: Changing view style to "Shaded", "Newsletter" or something else disables Quick Edit. Change it to "default" in view settings. https://support.microsoft.com/kb/2876824
  4. Enable 'Allow individual item" check boxes: In view settings make sure, "Allow Individual Items Check boxes" is enabled.    sharepoint 2013 quick edit this control is currently disabled
  5. If you are in datasheet view already- If your current view is "Datasheet view" then quick edit is disabled (obviously!). 
  6. SharePoint View definition XML uses an attribute "<JSLink>clienttemplates.js</JSLink>". During a migration, I had to add this to an existing view using SharePoint designer and verified Quick Edit works as expected.
  7. Last but not least: Try creating a new view using "Standard View".
Quick edit is not performing well with large lists. You may get "Unable to communicate with server" error and slowness when dealing with large lists. Apply filters to mitigate that issue.

Tags: quick edit not working in sharepoint 2013; sharepoint 2013 list quick edit disabled;  sharepoint 2013 quick edit not available; sharepoint 2013 quick edit this control is currently disabled; sharepoint 2013 quick edit currently disabled; sharepoint 2013 quick edit not enabled; quick edit sharepoint 2013 greyed out; sharepoint 2013 quick edit grayed out; sharepoint 2013 quick edit issues


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Friday, December 5, 2014

SharePoint 2013 Sign in as Different User Missing - Feature Based Solution

Sign in as different user menu option is missing in SharePoint server 2013, it has many possible workaround which are explained in my earlier post:  Sign in as Different User in SharePoint 2013 - Workarounds

How to add sign in as different user in SharePoint 2013:
To enable sign in as different user in SharePoint 2013, Lets build a feature based solution using Visual Studio:
  • Open Visual Studio 2013 (or 2012) >> Click on File >> New >> Project
  • Choose: Office/SharePoint >> SharePoint 2013 - Empty Project. Name your solution and click on "OK"
    sharepoint foundation 2013 sign in as different user
  • Enter the site for debugging and choose "Farm Solution" (Doesn't matters even its a sandboxed solution too!) and click on "Finish" button. wait for Visual studio to create project structure.
    how to add sign in as different user in sharepoint 2013
  • Now, in Visual studio, Right click the "Project" node from solution explorer window, choose Add >> New Item menu.
  • Choose "Module"and give it a name. Click on Add.
    sign in as different user menu option is missing in sharepoint server 2013
  • This module brings a feature "feature1" and "Sample.txt" File by default. Remove the sample.txt from the solution and rename Feature1 to something meaningful, I've made it as same as my project name - SignInAsDiffUser
    sign in with different user sharepoint 2013
  • Update the elements.xml file with the below code
      <?xml version="1.0" encoding="utf-8"?>
         <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
          <CustomAction
            Id="LoginAsDifferentUser"
            GroupId="PersonalActions"
            Location="Microsoft.SharePoint.StandardMenu"
            Sequence="1000"
            Title="Sign in as Different User">
            <UrlAction Url="/_layouts/closeConnection.aspx?loginasanotheruser=true"/>
          </CustomAction>
        </Elements> 
  • Now, Right click the Feature, "SignInAsDiffUser" from solution explorer and choose "View Designer"menu item.
  • In the feature designer page, Give a name and description to your feature. Set the scope for the feature, I've made it : Site, So that it will be applicable for the entire site collection. Make sure the module we've created is included in the feature.
    add sign in as different user in sharepoint 2013
  • Right click the solution in visual studio, choose Deploy. This will automatically Build,deploy and active your feature. Go to site collection features and make sure "Sign in As different User"feature is activated.
    how to enable sign in as different user in sharepoint 2013
Now, You'll be getting "Sign in As Different" user menu item under your personal settings menu in SharePoint foundation /Server.
enable sign in as different user sharepoint 2013


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, December 4, 2014

SharePoint Online: PowerShell to Create a List

Requirement: Create list in SharePoint online using PowerShell

SharePoint online PowerShell create list:
Here is how to create a list in sharepoint online using PowerShell
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
 
#Variables for Processing
$SiteURL = "https://Crescent.sharepoint.com/Sites/Sales"
$ListName="Parent Project"

#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred
    
    #Get All Lists 
    $Lists = $Ctx.Web.Lists
    $Ctx.Load($Lists)
    $Ctx.ExecuteQuery()

    #Check if List doesn't exists already
    if(!($Lists.Title -contains $ListName))
    { 
        #sharepoint online powershell create list
        $ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
        $ListInfo.Title = $ListName
        $ListInfo.TemplateType = 100 #Custom List
        $List = $Context.Web.Lists.Add($ListInfo)
        $List.Description = "Repository to store project artifacts"
        $List.Update()
        $Context.ExecuteQuery()
 
        write-host  -f Green "New List has been created!" 
    }
    else
    {
        Write-Host -f Yellow "List '$ListName' already exists!" 
    }
}
Catch {
    write-host -f Red "Error Creating List!" $_.Exception.Message
}

PowerShell to Create list in SharePoint Online:
To create new list using client side object model and PowerShell in SharePoint online, just change the TemplateType property value to 100 and run the above code. E.g.
$ListInfo.TemplateType = "107" #Task List

Result:
create list in sharepoint online using powershell
Related Post: Create document library in sharepoint online with PowerShell

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, November 25, 2014

Hide "Recent" from SharePoint 2013 Quick Launch Navigation

Recent section gets added automatically through a Web Control on SharePoint pages. 'Recent' menu is individual to each user! meaning everyone gets their own recent section with links to their recent activities! If you have a requirement to remove (or hide) the "Recent" menu header from the left navigation of SharePoint 2013, Here are some solutions:
sharepoint 2013 hide recent in quick launch
In Publishing sites, You can remove "Recent" section manually by going to : Site Settings >> Look and Feel >> Navigation (or Quick launch on Non-publishing sites!) .
hide recent in sharepoint 2013
How to hide recent in SharePoint 2013 using jQuery:
Edit the page, Add a script editor web part and place this code in it (or master page html)
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery(".ms-core-listMenu-item:contains('Recent')").parent().hide();
});
</script>

Hide recent heading in SharePoint 2013 Quick launch with PowerShell:
You can also remove "Recent" section using PowerShell by deleting recent header.

PowerShell script to delete recent group in SharePoint 2013 left navigation:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$web = Get-SPWeb "http://your-sharepoint-site-url"

#Process Quick launch
for ($i = $web.Navigation.QuickLaunch.Count-1; $i -ge 0; $i--)
{
    $node = $web.Navigation.QuickLaunch[$i];

    if($node.Title -eq "Recent")
        {
            $node.Delete();
            Write-host "Recent section removed from $($web.Title)"
        }
} 
You can restrict "Recent" menu by Creating a SharePoint group, Configure the audience targeting on the menu item only to the group!


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Cancel Workflows in SharePoint using PowerShell


Requirement: There was a large list with workflow attached to it. SharePoint Development team came with a requirement of cancelling multiple workflows running on these list items, nearly 2000!

While cancelling workflows on individual item is pretty straight forward, How about cancelling workflows on 1000's of items? Would be a daunting task, isn't it?

PowerShell Solution:
Well, PowerShell can help to cancel workflows in SharePoint. If you ever have to cancel multiple running workflows on all list items, use this PowerShell script:

Cancel all workflows on a list:
$web = Get-SPWeb "http://your-sharepoint-site-url"

#List Name
$list = $web.Lists["Your-List-Name"]

# Iterate through all Items and all Workflows on Items
foreach ($item in $list.Items) 
 {
   foreach ($wf in $item.Workflows) 
     {
 #Cancel Workflows        
 [Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf)      
     }
  }
To cancel all errored workflows use the condition as:
foreach ($item in $list.Items) 
 {
   foreach ($wf in $item.Workflows) 
     {
        if($wf.InternalState -match 'Error')
         {
     #Cancel Workflows        
            [Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);      
         }
     }
 }
Lets target a particular workflow:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$web = Get-SPWeb "http://your-sharepoint-site-url"

#Get the List
$list = $web.Lists["Your-List-Name"]

#Get the specific workflow, Associated with the list
$WorkFlowToCancel = "Approval Workflow"

# Iterate through all Items and all Workflows on Items
foreach ($item in $list.Items) 
 {
   foreach ($wf in $item.Workflows) 
     {
     #Check for the particular workflow
        if( ($wf.ParentAssociation.Name -eq $WorkFlowToCancel) -and ($wf.IsCompleted -ne $true) -and($wf.StatusText -ne "Canceled"  )) 
        {
            write-host "Previous workflow status:"  $wf.InternalState
            #Cancel Workflow
            [Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf)      
            write-host "Workflow Cancelled at $($list.title)! "
        }
     }
  }

Related Post: How to Start a SharePoint Workflow using PowerShell

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, November 24, 2014

Arrange Choice Field Radio Buttons Horizontally in SharePoint List Forms

Requirement is to arrange choice fields of Radio buttons to horizontally in a SharePoint 2013 custom list form:
How to arrange choice field options Horizontally?
Step 1: Create new Custom list form(Say: New.aspx) using SharePoint Designer, Edit the page in SharePoint designer, Find and wrap your choice field in <Span> tag to assign it a unique ID. E.g.optRegType.
<span id="optReqType">
 <SharePoint:FormField runat="server" id="ff3{$Pos}" ControlMode="New" FieldName="Change_x0020_Request_x0020_Type" __designer:bind="{ddwrt:DataBind('i',concat('ff3',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Change_x0020_Request_x0020_Type')}"/>
       <SharePoint:FieldDescription runat="server" id="ff3description{$Pos}" FieldName="Change_x0020_Request_x0020_Type" ControlMode="New"/>
</span>

Step 2: In the custom list form, find the tag <AdditionalPageHead> and add this code just below it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

  $(document).ready(function() {
 var firstRadio = $("#optReqType table tbody tr td .ms-RadioText:eq(0)");
 $("#optReqType table tbody tr td .ms-RadioText:gt(0)").appendTo($(firstRadio));

  });
</script>
 
What If you have Multiple Choice Fields?
When you have multiple choice fields in the form, its better to create a function to arrange them horizontally.
<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

 function alignOptions(fieldName)
 {
 var firstRadio = $("#"+fieldName +" table tbody tr td .ms-RadioText:eq(0)");
 $("#"+fieldName +" table tbody tr td .ms-RadioText:gt(0)").appendTo($(firstRadio));
 }
 
  $(document).ready(function() {

   //Call function to arrange Radio buttons horizontally
 alignOptions("optChgImpact");
 alignOptions("optChgPriority");

  });
</script>
Here is my screen:
SPServices Framework also offers this functionality:
http://spservices.codeplex.com/wikipage?title=%24%28%29.SPServices.SPArrangeChoices

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


You might also like:

Related Posts Plugin for WordPress, Blogger...