Sunday, June 30, 2013

Set Content Editor Web Part (CEWP) Content with PowerShell

Scenario:
We've a Project site collection with 100's of sub sites created for each project from a custom site template. Home page of each site has a content Editor web part with some content in it, titled "Dashboard Links". Years later, business wanted to change the content in the "Dashboard Links" in each site!

So, Here the requirement is to set the Content Editor web part's content in all sub sites. Lets use PowerShell to automate:

Set Content Editor Web Part (CEWP) Content with PowerShell
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the Site collection
$site=Get-SPSite "http://sharepoint.crescent.com/PMO/"

#Loop throgh each subsite in the site collection
foreach($web in $Site.AllWebs)
{
  #Get the Default.aspx file
  $file= $web.GetFile($web.Url +"/SitePages/Home.aspx")

  if($file.Exists)
    {
     #Web Part Manager to get all web parts from the file
     $WebPartManager = $web.GetLimitedWebPartManager( $file,  [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
 
     #Iterate through each web part
     foreach($webPart in $WebPartManager.WebParts) 
      {
        # Get the Content Editor web part with specific Title
        if( ($webPart.title -eq "Dashboard Links") -and ($webPart.GetType() -eq [Microsoft.SharePoint.WebPartPages.ContentEditorWebPart]) )
        {
           #Content to be Placed inside CEWP
           $HtmlContent= "<ul><li><a href='/pmo/dashboard/team-allocation.aspx'>PMO Team Allocation</a></li><li><a href='/pmo/dashboard/bi-dashboard.aspx'>PMO Business Intelligence Dashboard</a></li><li><a href='/pmo/dashboard/pmi-admin.aspx'>PMO PMIS Admin</a></li><li><a href='/pmo/dashboard/pmo-yammer.aspx'>PMO on Yammer</a></li></ul>"

           $XmlDoc = New-Object System.Xml.XmlDocument
     $contentXml=$xmlDoc.CreateElement("content") 
           $contentXml.InnerText= $HtmlContent

           #Set content and Save
           $webpart.Content = $contentXml     
           $webPartManager.SaveChanges($webPart);
         }
      }
    }
 }


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


Thursday, June 27, 2013

Get Query String and Set List Form Field Value using jQuery

Years back, I used JavaScript for the similar requirement in SharePoint 2007: Get the value from URL Query String and populate the value of SharePoint list form field: How to Get the Query String from URL and Set SharePoint List Form field value?

Now in SharePoint 2010, lets use jQuery to get query string from URL and populate list form field's value and SharePoint designer Quick Step to pass the query string value to target URL.

Scenario: We've a "Projects" list with list of projects, and "Project Metrics" list to capture project metrics.We need to add project metrics to the projects from a context (ECB) menu item from Projects list.

Overall Idea:
  1. Lets add a Quick Step using SharePoint designer to pass query string. 
  2. On clicking the Quick Step Link, say "Add Project Metrics", It navigates to the NewForm URL of Project Metrics list with QueryString "ProjectID".
  3. Lets get the query string from URL and set the NewForm's "Project ID" field of Project metrics list item. 
Get Query String and Set List Form Field Value using jQuery
Add a Quick Step in SharePoint Designer:
Create a new Quick Step in SharePoint designer with "Navigate to URL" selected. Enter the below code in it, to navigate to NewForm.aspx file of Project Metrics list with ProjectID value in URL.
javascript:SP.UI.ModalDialog.showModalDialog({url:"/Lists/ProjectMatrics/NewForm.aspx?ProjectID={ItemId}",dialogReturnValueCallback:
 function(dialogResult, returnValue) { 
SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK) }}) 
sharepoint list newform query string
Get Query String and Populate List Form Field Value
In NewForm.aspx of the Project Metrics list, Add a CEWP and link to the below script. Basically, it fetches the Query string "ProjectID" from URL and sets the "Project ID" field in Project metrics list item.
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>

        <script language="javascript" type="text/javascript">

         $(document).ready(function() {

            //Get the Query string value
            var qs = getQueryString('ProjectID'); 

            //Set the Value of "ProjectID" field
     $("input[Title='Project ID']").val(qs);

            //Disable "Project ID" field
     $("input[Title='Project ID']").attr("disabled", "disabled");
         //You can also make the field read-only: $("input[Title='Project ID']").attr('readonly','true');

   });

          //Function to Get Query String from URL
          function getQueryString(key){
            var regex=new RegExp('[\\?&amp;]'+key+'=([^&amp;#]*)');
            var qs=regex.exec(window.location.href);
            return qs[1];
          }

          //Clear the "Disabled" property on Save. If its not enabled, Mandatory field validation fails
   function PreSaveAction() {
     $("input[Title='Project ID']").attr("disabled", "");
     return true;
   }

         </script>
Result: Project ID field is populated from the query string ProjectID from URLsharepoint set field value query string

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


Wednesday, June 26, 2013

Building Charts in SharePoint with Google Charts API

Looking for a quick way to build Charts & Graphs from SharePoint list data? Here is the quickest way to create charts on SharePoint with Google Chart API!
  1. Go to: http://usermanagedsolutions.com/SharePoint-User-Toolkit/Pages/Pie-Bar-Chart-Connector.aspx Building Charts in SharePoint with Google Charts API
  2. Provide "Edit view " URL in the given Text box. E.g. I've a List "Q1Summary" in Finance site collection. Edit view URL is: http://sharepoint.crescent.com/sites/finance/Q1Summary/_layouts/ViewEdit.aspx?List=%7BB9E23283%2DC445%2D4918%2D9229%2DB918FC2D71E2%7D&View=%7BB5A76744%2D98ED%2D422B%2D807A%2DCCBF1BF1F070%7D
  3. Specify other optional parameters such as Chart Type (Pie Chart, Bar, Column), Width, Chart title to generate chart code. Place the generated Chart code in Content editor web part
The code generated would look like:
<div id="spChart"></div>
<script src="//www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">

/* 2012 * Christophe Humbert * http://usermanagedsolutions.com/SharePoint-User-Toolkit/ */
(function(){

var options={
chartType: "Bar",
title:"Chart title",
is3D:false,
width:500,
height:300,
url:"/sites/finance/q1summary/_vti_bin/owssvr.dll?Cmd=Display&XMLDATA=TRUE&List=%7BB9E23283%2DC445%2D4918%2D9229%2DB918FC2D71E2%7D&View=%7BB5A76744%2D98ED%2D422B%2D807A%2DCCBF1BF1F070%7D"
};

var o=options,URL=o.url+"&_ts="+(new Date()).getTime(),c=document.getElementById("spChart");c.id="";google.load('visualization','1.0',{'packages':['corechart']});var x=new XMLHttpRequest();x.onreadystatechange=function(){if (x.readyState==4){if (x.status==200){var xml=x.responseXML,r=(xml.getElementsByTagNameNS)?xml.getElementsByTagNameNS("*","row"):xml.getElementsByTagName("z\:row");google.setOnLoadCallback(dC(r));}}};x.open("GET",URL,true);x.send(null);function dC(r) {var d=new google.visualization.DataTable(),a=r[0].attributes,aC=a.length;for (var i=aC-1;i>=0;i--) {if (a[i].name.indexOf("Title")>=0) {var tA=a[i].name;} else {var vA=a[i].name;}}d.addColumn('string',tA.replace(/ows_/,""));d.addColumn('number',vA.replace(/ows_/,""));var rC=r.length,rs=[];for (var i=0;i<rC;i++) {(function(){var arr=[];arr[0]=r[i].getAttribute(tA);var n=r[i].getAttribute(vA).split("#");arr[1]=parseFloat(n[1]||n[0]);rs.push(arr);})();}d.addRows(rs);var chart=(o.chartType=="Pie")?new google.visualization.PieChart(c):(o.chartType=="Bar")?new google.visualization.BarChart(c):new google.visualization.ColumnChart(c);chart.draw(d,options);}})();
</script>

That's it! See the result in action: Here is an SharePoint Google chart example
google chart sharepoint 2007
Google charts in SharePoint 2007


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


Tuesday, June 25, 2013

Export SharePoint 2007 Search Crawl History using PowerShell

Here is the PowerShell script to export Search crawl history in SharePoint 2007 using PowerShell:
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.Search")

    function global:Get-CrawlHistory($url)
    {
     #Objects to get Crawl History
     $site = new-Object Microsoft.SharePoint.SPSite($url);
     $context = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($site);
     $history = new-Object Microsoft.Office.Server.Search.Administration.CrawlHistory($context);

     Write-OutPut $history.GetCrawlHistory()
     
     #Dispose site object
     $site.Dispose()
    }
    
    #Call the function to get Crawl History
    Get-CrawlHistory -url "http://sharepoint.crescent.com" | Export-CSV "d:\Reports\CrawlLog.csv"
This gives data such as: CrawlType (2 - Increment, 1- FULL), ContentSourceID ( 4 - Local Crawls, 10 -People search), Status, Start Time, End Time, Success Count, Error Count, Warning Count of last 8 crawls.

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


Monday, June 24, 2013

Download All Files From a SharePoint Library Programmatically using PowerShell

Ever wanted to download all files from a SharePoint Library (Document Library, Picture Library, etc) to your local drive?

While downloading a single file or document is fairly straight forward by Clicking "Download a Copy" from documents Tab of the Ribbon or From the ECB Menu of the document  >> Send To >> "Download a Copy", downloading Multiple files or a complete folder is not that easy when the files count is high.

Sure, Explorer view can do it! Go to the Document Library and choose Explorer View from the Ribbon
Download All Files From a SharePoint Library Programmatically using PowerShell
Now you can drag & Drop (or Copy & Paste) folders, Files from and to your local drive from SharePoint. You can also use map your SharePoint libraries to network drive. 

But How about downloading all documents from all document libraries? Yes, PowerShell can do it well!

PowerShell Script to download all files and folders from a SharePoint Library along with its Structure:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

# Function to Download All Files from a SharePoint Library
Function DownloadFiles($SPFolderURL, $LocalFolderPath)
{
        #Get the Source SharePoint Folder
        $SPFolder = $web.GetFolder($SPFolderURL)


        $LocalFolderPath = Join-Path $LocalFolderPath $SPFolder.Name 
        #Ensure the destination local folder exists! 
        if (!(Test-Path -path $LocalFolderPath))
        {    
             #If it doesn't exists, Create
             $LocalFolder = New-Item $LocalFolderPath -type directory 
        }

	    #Loop through each file in the folder and download it to Destination
	    foreach ($File in $SPFolder.Files) 
	    {
	        #Download the file
	        $Data = $File.OpenBinary()
		$FilePath= Join-Path $LocalFolderPath $File.Name
	        [System.IO.File]::WriteAllBytes($FilePath, $data)
	    }

    	#Process the Sub Folders & Recursively call the function
        foreach ($SubFolder in $SPFolder.SubFolders)
        {
           if($SubFolder.Name -ne "Forms") #Leave "Forms" Folder
             {
                  #Call the function Recursively
                  DownloadFiles $SubFolder $LocalFolderPath
             }
        }
 
    }

#Get the Source Web
$Web = Get-SPWeb "http://sharepoint.crescent.com/sites/Operations"
 
#Get the Source SharePoint Library's Root Folder
$SourceLibrary =  $Web.Lists["Design Documents"].RootFolder

#Local Folder, where the Files to be downloaded 
$DestinationPath = "C:\Test" 

#Call the Download Files Function
DownloadFiles $SourceLibrary $DestinationPath

The above code is pretty simple. We can re-write this in C# Object model code, Add a Custom Ribbon item to download all files.


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


Tuesday, June 18, 2013

How to Run SQL Server Query from PowerShell Script

For a migration project, there was a requirement to read from SQL Server table data , process the migration and then insert / update the tables back from PowerShell. We got to run SQL Server query from PowerShell. Here is how to query SQL Server using PowerShell:

Using PowerShell to query SQL Server
Function QuerySQLServer([string]$DBServer, [string]$DBName, [string]$Query)
{
 <#
  .SYNOPSIS
   Queries SQL Server from PowerShell
  .DESCRIPTION
  This PowerShell function Queries SQL Server from PowerShell
 .EXAMPLE
  QuerySQLServer "G1VWFE01" "MigrationDB" "SELECT [SourceSiteUrl], [TargetSiteUrl], [SiteType] FROM [MigrationData]"
      This example Gets table entries from the database "MigrationDB" in server "G1VWFE01"
 .INPUTS
  DBServer - Name of the Database Sever where the  target database is located
  DBName - Name of the Database from which the query to be executed
         Query - Query to Execute
 .OUTPUTS
  Rows from the prodefined table "MigrationData"
 #>

 try
        {
  $ErrorActionPreference = "Stop"
  
  #Connection object
  $cn = new-object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=SSPI;Initial Catalog=$DBName")
  $cn.open() 

  #SQL Query to retrieve Table rows
  $cmd = new-object "System.Data.SqlClient.SqlCommand" ($Query , $cn)
  $reader = $cmd.ExecuteReader()
                #Process the Data
   while ($reader.Read()) 
    {
        #Iterate through Rows
      for ($i = 0; $i -lt $Reader.FieldCount; $i++) 
      {
          #Retrieve the Field (Column) values
          $Reader.GetValue($i)
      }
    }
   }
 catch
        { 
     #Write error message on screen and to a LOG file
            write-host $_.Exception.Message
     $_.Exception.Message >> "d:\error.log"
        }
        finally
        {
            $ErrorActionPreference = "Continue"
        }
 }
#Call the function
QuerySQLServer "GIS-WFE01" "MigrationData"
     "SELECT [SourceSiteUrl], [TargetSiteUrl], [SiteType] FROM [MigrationSiteMapping]"
Its also possible to process the Queried data like:
 
  Function ProcessSQLServerData([string]$DBServer, [string]$DBName, [string]$Query)
     {
 try
        {
  $ErrorActionPreference = "Stop"
  
  #Connection object
  $cn = new-object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=SSPI;Initial Catalog=$DBName")
  $cn.open() 

  #SQL Query to retrieve Table rows
  $cmd = new-object "System.Data.SqlClient.SqlCommand" ($Query , $cn)
  $reader = $cmd.ExecuteReader()
                #Process the Data
   while ($reader.Read()) 
    {
      for ($i = 0; $i -lt $Reader.FieldCount; $i++) 
      {
          #Retrieve the parameters from SQL Server "MigrationMapping" table
          $SourceSiteUrl = $Reader.GetValue(0)
       $TargetSiteUrl =$Reader.GetValue(1)
       $SiteType = $Reader.GetValue(2)

       #Check the SiteType
       if($SiteType  -eq "client")
       {
           Write-Host "Processing Client Site URL: $($SourceSiteUrl)"
                                                            #call a PowerShell function from an External script to process the given parameters
           MigrateClientSite $SourceSiteUrl $TargetSiteUrl
       }
       else #it a Case site
       {
           Write-Host "Processing Case Site URL: $($SourceSiteUrl)"
           #call a PowerShell function from an External script to process the given parameters
           MigrateCaseSite $SourceSiteUrl $TargetSiteUrl
       }
      }
    }
   }
 catch
        { 
     #Write error message on screen and to a LOG file
            write-host $_.Exception.Message
     $_.Exception.Message >> "d:\error.log"
        }
        finally
        {
            $ErrorActionPreference = "Continue"
        }
 }
 
The above PowerShell SQL Server query example retrieves and process the SQL server table rows.

Powershell script Execute  SQL Server Query performs Insert/Update:
Similarly, for Insert and update, the PowerShell script goes like:
Function RunSQLQuery([string]$DBServer, [string]$DBName, [string]$Query )
{
 <#
  .SYNOPSIS
   Executes SQL Query, such as Insert, Update, Delete, etc 
  .DESCRIPTION
   This PowerShell function executes the provided SQL query on the provided Database.
  .EXAMPLE
   powershell sql server query update: " RunSQLQuery "G1VWFE01" "MigrationData" "UPDATE [Table-name] SET [SiteStatus]='CREATED' WHERE [SiteID] = '$SiteID' AND [Category] = '$Category' "
                 powershell sql server query insert: use the SQL query as: "INSERT INTO [TableName] ( [SourceSiteUrl], [TargetSiteUrl],  [SiteType] ) VALUES ('http://sharepoint2007.crescent.com','http://sharepoint2010.crescent.com', 'case')"
  .INPUTS
   DBServer - Name of the Database Sever where the "LVMAdmin" database is located
   DBName - NameNo value of the cases table
   Query - Query to execute. Such as Insert, Delete
  .OUTPUTS
   None
 #>
 try
        {
  #Connection object
  $cn = new-object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=SSPI;Initial Catalog=$DBName")
  $cn.open() 

  $cmd = new-object "System.Data.SqlClient.SqlCommand" ($Query, $cn)
  $cmd.ExecuteNonQuery()
 }
 catch
        {
               #Write error message on screen and to a LOG file
               write-host $_.Exception.Message
  $_.Exception.Message >> "d:\error.log"
        }
        finally
        {
            $ErrorActionPreference = "Continue"
        }
}
This will run SQL Server query from PowerShell.

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


Monday, June 17, 2013

How to Prevent SharePoint List or Columns from Deletion

Scenario: We've a configuration list being used by a custom SharePoint application and we don't want to let the users to delete the configuration list in SharePoint. So how to prevent delete in SharePoint list?

The idea is: Set the "AllowDeletion" property of the SharePoint list or Library to false. These properties can be set programmatically using object mode code C# or PowerShell.

PowerShell script to make SharePoint List/Library deletable:
#Get the Web
$web = Get-SPWeb "http://sharepoint.crescent.com/sites/pmo"

#Get the List
$list = $web.Lists["Design Documents"]

#Set the "AllowDeletion" property
$List.AllowDeletion=$false
$List.Update()

"Delete this document library" or "Delete this list" link will go hidden under list settings!
sharepoint 2010 delete this list option missing

We can use the C# code as well to disable delete option on SharePoint list and libraries:
using(SPSite site = new SPSite("http://sharepoint.crescent.com/sites/pmo"))
 {
  using(SPWeb web = site.OpenWeb())
   {
       SPList list = web.Lists["Design Documents];
       list.AllowDeletion = false;
       list.Update();
    }
 }

Same trick applies to SharePoint list columns as well. Sett the field's "AllowDeletion" property to false to prevent the field from deletion. Here is an example: Typical SharePoint list columns will look like:
Lets prevent the column from deletion by setting "AllowDeletion" property to false.

PowerShell script to disable delete on list columns:
#Get the Web
$web = Get-SPWeb "http://sharepoint.crescent.com/sites/pmo"

#Get the List
$list = $web.Lists["Design Documents"]

#Get the column
$column = $list.Fields["Category"]

#Disable Delete
$column.AllowDeletion = $false
$column.Update()
 
$web.Dispose()
Output:
sharepoint 2010 unable to delete list column
Now, the reverse: Delete Button Missing in SharePoint Column? Here is How to Delete them.

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


SharePoint 2010 Rating Feature Configuration - How to Activate? Fix Ratings not Updating Issue

Rating feature was introduced in SharePoint 2010, It helps to rate Lists, Documents, Pages on a SharePoint site.

How To Enable SharePoint 2010 Rating Setting:
To setup SharePoint 2010 rating configuration, follow these steps:
  • Navigate to your SharePoint site and then Target list or document library where you want Ratings to be enabled.
  • Go to the list settings, Click on "Rating Settings" under the "General Settings" section
    sharepoint 2010 rating document library
  • Enable "Allow items in this list to be rated" and click OK. This will add rating columns to SharePoint 2010 list/library.
    sharepoint 2010 enable rating feature
  • Now you will see two new columns: the Ratings (0-5) and the Number of Ratings under the Columns section of list settings.
    sharepoint 2010 list rating column
  • Go to the list items view, You can set the ratings inline or edit a list item/document and set the  rating for the item by simply mouse over the stars in the Rating(0-5) column and set the ratings as needed. (You need Edit permissions, BTW)sharepoint 2010 how to enable rating
The next time the service timer job responsible for this social feature runs, the rating scale and number will reflect the results

SharePoint 2010 Ratings not working?
So you rated a List item or a document, but upon refresh, found SharePoint 2010 ratings not updating? Ratings not saved? But when you mouse over the rating icons, SharePoint gives the previously selected rating in tool tip. Well, that's confusing most of the users!

This is due to: By default the Timer Jobs listed below, related to Rating service is set to run for every hour!
rating in sharepoint 2010 not working
Once ratings given to an item then it'll be stored in database. When the ratings are all gathered together it will show the average ratings, not just your ratings. When the page is refreshed, if the data hasn’t been analyzed yet by SharePoint via the below timer jobs, the ratings will be blank or old! This is how ratings work in SharePoint 2010.

SharePoint 2010 rating timer jobs
Rating values are compiled by these timer jobs
  1. User Profile Service Application - Social Data Maintenance Job
  2. User Profile Service Application - Social Rating Synchronization Job
By default, This timer job is scheduled to run every 1 Hour. You can Run these timer jobs on-demand by clicking "Run Now" or change the "Recurring Schedule" as required. Here is how - Go to:
Central Administration >> Monitoring >> Timer Jobs >> Review Job Definition >> and select the above timer jobs.

Click on "Run Now". our convenience and testing, schedule both these jobs to run every 1 min as shown below.
sharepoint 2010 rating timer job


As you hover over the ratings stars they light up, and then you just click to select your rating and record your vote,  users can see the average ratings  (Blue Stars) after the timer job run.
sharepoint 2010 rating documents
If a user giving rating which he already given, then his previous rating will be discarded and new selection only getting considered.

SharePoint 2010 rating settings not available? Here is how to activate rating feature:
Don't have "Rating Settings" appear on lists/libraries settings? Enable Rating feature to fix SharePoint 2010 rating settings missing issue:
Enable-SPFeature Ratings -url http://site-collection-url

Rating feature is available only with SharePoint Server 2010 and not with the SharePoint Foundation Services!


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


Sunday, June 16, 2013

SharePoint WSP Solution Deployment Stuck at "Deploying"

Issue: SharePoint WSP Solution got stuck at "Deploying" stage for hours while trying to deploy using STSADM command in SharePoint 2007!
SharePoint WSP Solution Deployment Stuck at "Deploying"
Same thing happened in SharePoint 2013 also:
sharepoint wsp stuck in deploying

Workarounds: 
Try these workarounds to fix the solution deployment stuck at "deploying" stage.
  • Make sure all your WFE & DB Servers in the Farm has no Time zone different! Make them aligned!
  • Try running: stsadm -o execadmsvcjobs as the first step!
  • Cancel the deployment, Remove the WSP and Re-deploy: 
    • stsadm -o enumdeployments - This will give the GUIDs of all solution in "Deploying" State. Cancel the deployment using stsadm -o canceldeployment <GUID> command. E.g.:
    • stsadm -o canceldeployment -id "95823b2b-8c92-4d08-99d5-7cf14c7be602"
    • Delete the stuck solution with stsdm -o deletesolution -name mysolution.wsp -override
    • Redeploy the solution.
  • Try deploying for a single web application rather all.
  • Try Restarting Timer Job on all servers of the Farm. Restart SharePoint Timer Service on all Servers in the Farm
  • Try Clear Config Cache : How to Clear SharePoint Configuration Cache using PowerShell 
  • In "services on server", make sure "Microsoft SharePoint Foundation Workflow Timer Service" is running. If not, start it!
  • Check "SharePoint Administration Service" in services console. If stopped, start it.
  • If any one of your SharePoint Web front end server (where SharePoint web application is running) is turned-off, You may get into this issue. Either turn it ON or remove the server from the SharePoint server farm.
  • As the last: Reboot the server! If nothing helps, have a look at the SharePoint logs/Event Log to check root cause.


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


IE 10 Browser Compatibility issues with MOSS 2007 and SharePoint 2010

Found so many user interface issues with Internet Explorer 10 while using it in MOSS 2007 and SharePoint 2010 sites. For instance, KPI didn't load, Grouped items stuck with "Loading.." message, "Save" button didn't work on SharePoint list forms, etc. Additionally, Experienced many JavaScript errors when tying Datasheet view, Multiple File Upload, etc.
IE 10 Browser Compatibility issues with MOSS 2007 IE 10 Browser Compatibility issues with SharePoint 2010

Temporary Fix: Set the Browser Mode to IE 8!

How? Press F12, which fires IE Developer Tools. Select "Browser Mode: IE8". You can also try setting User Agent string to IE 8 from tools menu of IE Development tools.
Internet Explorer 10 issues with SharePoint 2007 and 2010

Permanent Fix: Install the Hot fix! http://support.microsoft.com/kb/2600100/en-us

We can also force Internet explorer 10 to work on IE9 compatibility mode by setting the META tag in SharePoint Master page:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">

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


Delete All Document Versions in SharePoint Document Library using PowerShell

Requirement: Delete all old document versions in SharePoint site collection to free-up some disk space occupied by document versions. Because, simply disabling versioning does not deletes old versions which are already created until the next update happens on the document! So, If you want to release the space occupied by previous versions, you'll have to remove them manually.

To Delete all previous versions of a document in SharePoint, follow these steps:
  • Navigate to your SharePoint Library, click the ellipse (...) and then click on Version History
  • From the version history page, click on "Delete all versions" link, confirm if prompted!
    powershell to delete all document versions in sharepoint

PowerShell to Delete all Document Versions in SharePoint:
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
 
#Configuration Parameters
$WebURL = "http://portal.crescent.com.com/projects/"
$ListName = "Documents"

#Get the Web, List objects
$Web= Get-SPWeb $WebURL
$List= $web.Lists[$ListName]

#Get all Items from the List
$ListItems = $List.Items
Write-host "Total Items Found in the List:"$List.ItemCount
$Counter =0

#Iterate through each item
foreach ($ListItem  in $ListItems)
{
    #Display Progress bar
    $Counter=$Counter+1    
     Write-Progress -Activity "Cleaning up versions" -Status "Processing Item:$($ListItem['Name']) $($counter) of $($List.ItemCount)" -PercentComplete $($Counter/$List.ItemCount*100)
     
    #If the File has versions, clean it up
    if ($ListItem.Versions.Count -gt 1)
    { 
        Write-host "Cleaning versions for: " $ListItem["Name"]
        $ListItem.file.Versions.DeleteAll()
    }
}

SharePoint: PowerShell delete all versions for entire site collection
How about deleting document versions for all document libraries in a site collection? Here is the PowerShell script to delete all document versions in a site collection:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Get the Site Collection
$site = Get-SPSite "http://sharepoint.crescent.com/sites/operations"

#Loop through all sites in the site collection
foreach($web in $site.AllWebs)
{
  #Iterate through all Lists
  foreach($List in $Web.Lists)
 { 
 #Get only document libraries & Skip Hidden 
  if( ($List.BaseType -eq "DocumentLibrary") -and ($List.EnableVersioning) -and ($List.Hidden -eq $false) -and($List.IsApplicationList -eq $false) ) 
     {   
   #loop through each item
      foreach ($item in $list.Items)
      {
    if($item.File.Versions.Count -gt 0)
    {
        # delete all versions
     Write-Host "Deleting $($item.File.Versions.Count) Version(s) on: $($web.URL)$($item.URL)"
      $item.file.Versions.DeleteAll()
    }
      }
  }
 }
 }
 
$site.Dispose()
Write-Host "Script execution Completed!"
This PowerShell script will delete old versions in SharePoint document libraries for the entire site collection.

Related posts:
Checkout my codeplex tool to cleanup document versions in SharePoint: Download SharePoint Versioning Manager from CodePlex

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


Thursday, June 13, 2013

How to Hide SharePoint 2010 Ribbon Tab - Group - Button - Menu

How to hide Ribbon Tab - Group - Button - Menu in SharePoint 2010? But why? because, the requirement is: Users to fill the form and not upload any existing documents to the document libraries in a particular site. So wanted to disable Upload Document button from SharePoint ribbon.
hide sharepoint ribbon button

Solution:
Override the existing SharePoint 2010 Ribbon Tab/Group/Button/Menu by creating an empty CommandUIDefinition!

Steps in Detail:
1. Create an empty SharePoint 2010 farm solution project in Visual Studio 2010. Give it a name. Say, Crescent.TeamSites.HideUploadButton.
sharepoint hide ribbon items
2. Add a new "Empty Element" item to the project. This will create a Feature with Elements.xml file.
hide sharepoint ribbon tab

3. Update the Elements.xml file with below content.
 <?xml version="1.0" encoding="utf-8"?>
  <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <CustomAction
      Id="RemoveRibbonButton"
      Location="CommandUI.Ribbon">
      <CommandUIExtension>
        <CommandUIDefinitions>
          <CommandUIDefinition
            Location="Ribbon.Documents.New.AddDocument" />
        </CommandUIDefinitions>
      </CommandUIExtension>
    </CustomAction>
  </Elements> 
hide a ribbon button in sharepoint 2010

4. Now, Go to Feature designer, Name the Feature Title & Description. Specify the scope as Web and Include the Element to the feature.
sharepoint 2010 hide button from ribbon

5. Deploy the feature and see the result in action.
hide a ribbon button in sharepoint 2010
Here the Location is the key. For all available location values, refer MSDN: http://msdn.microsoft.com/en-us/library/ee537543%28v=office.14%29.aspx

Tips: You can also use IE Toolbar/Firebug to get the location ID! (Take the text till - Hyphen )
sharepoint ribbon hide tab

Hiding SharePoint 2010 Ribbon Tabs, Groups, Button Menus
The above method applies when you want to hide button menus from the Ribbon.
  • E.g. Hide "Upload Multiple Documents" Menu link under "Upload" button, specify the location as: Ribbon.Documents.New.AddDocument.Menu.Upload.UploadMultiple
  • To Hide Ribbon Tabs, E.g. Hide Documents tab in document library ribbon, the location should be "Ribbon.Document". 
  • Similarly to hide Ribbon Tab Button Groups, E.g. "New" group in SharePoint Ribbon, specify the location as: Ribbon.Documents.New

How to Hide Ribbon  Tab - Group - Button - Menu on a Particular List?
While its possible to target custom action to List types, Content Types, File Types, There is no way to target on specific list declaratively! So, we can get it done programmatically. Here is how to hide ribbon buttons in SharePoint 2010 programmatically:

    static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://sharepoint.crescent/"))
            using (SPWeb web = site.OpenWeb())
            {
                //Get the "Projects" List 
                SPList list = web.Lists.TryGetList("Projects");
                if (list != null)
                {
                    var action = list.UserCustomActions.Add();
                    action.Location = "CommandUI.Ribbon";
                    action.Sequence = 50;
                    action.Title = "Hide Upload Button from Ribbon";

                    action.CommandUIExtension = @" 
                        <CommandUIExtension><CommandUIDefinitions>
                        <CommandUIDefinition Location=""Ribbon.ListItem.New"">
                        </CommandUIDefinition>
                        </CommandUIDefinitions>
                        </CommandUIExtension>";
                    action.Update();
                }
            }
        }

To remove the custom action use this code:
      using (SPSite site = new SPSite("http://sharepoint.crescent.com/"))
            using (SPWeb web = site.OpenWeb())
            {   
                //Get the "Projects" List 
                SPList list = web.Lists.TryGetList("Projects");
                if (list != null)
                {
                     
                   foreach (SPUserCustomAction action in list.UserCustomActions)
                    {
                        if (action.Title == "Hide Upload Button from Ribbon")
                        {
                            action.Delete();
                            break;
                        }
                    }
                }
            }

Hide Ribbon Button by CSS:
We can hide ribbon buttons using CSS also. Refer this post for more info: How to Disable Multiple File Upload in SharePoint

Microsoft KB: http://support.microsoft.com/kb/2285182

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


Wednesday, June 12, 2013

Open with Explorer Error - Alternate Method

When you try to use "Open with Explorer" on SharePoint document library, Received Error "Your client does not support opening this list with Windows Explorer".
Your client does not support opening this list with Windows Explorer
You tried all the workarounds on Open with Windows Explorer Error: "Your client does not support opening this list with windows explorer" , but no luck!

Well, there is a alternate to Open with Explorer. Map to Network Drive!

Just go to My Computer >> Right Click "Computer" node from left side Tree view >> Choose "Map Network Drive" and provide the SharePoint document library location.
Open with Explorer Error - Alternate Method

You may be prompted to provide credentials. Once done, will get a New Drive in My computer, where you can copy/paste files as you do in windows explorer.




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


Sunday, June 9, 2013

How to Remotely Execute SharePoint 2010 PowerShell Cmdlets

PowerShell allows us to run cmdlets remotely from client machines. We can run SharePoint 2010 cmdlets on the SharePoint Server, remotely connecting from client machines by following these two steps:

Step 1: To execute SharePoint PowerShell remotely, you have to enable PowerShell Remoting on the Server first! By default PowerShell Remoting is disabled. Log-On to the server you want to access remotely, enable remote PowerShell for running SharePoint 2010 cmdlets

Enable-PSRemoting
execute sharepoint 2010 powershell remotely
This command enables remote PowerShell for SharePoint 2010 by enabling WinRM service and configures windows firewall to allow incoming sessions. 
Its a one time activity to configure remote PowerShell in SharePoint 2010.

Step 2:
Now, We can either directly invoke PowerShell Cmdlets or establish a session and then execute PowerShell cmdlets. E.g. To get the total no. of site collections, I'm using the below code:

 Option 1: Invoke PowerShell remotely to run SharePoint 2010 cmdlets:
 To Invoke SharePoint 2010 PowerShell on remote server:
 Invoke-Command -ComputerName SPSWFE01 -ScriptBlock { 
 Add-PSSnapin Microsoft.SharePoint.PowerShell; 
 $webApp = Get-SPWebApplication "http://sharepoint.crescent.com"; 
 write-host "Total No. of sites in the Web Application: $($webApp.Sites.Count)" 
 } -credential (Get-Credential)

Option 2: Establish a Remote Session and then execute PowerShell cmdlets:
We've to connect to remote SharePoint server using PowerShell. In the Client machine, enter:
Enter-PSSession "SharePoint Server Name" -Credential (Get-Credential) 

This cmdlet prompts for credentials and opens PowerShell remote session from the remote SharePoint farm .Once done, we can run PowerShell commands. Here is an example to establish and execute PowerShell commands
Add-PSSnapin Microsoft.SharePoint.PowerShell
$webApp = Get-SPWebApplication "http://sharepoint.crescent.com"
write-host "Total No. of sites in the Web Application: $($webApp.Sites.Count)"

Don't forget to exit the PowerShell session, once you are done with PowerShell:
Exit-PSSession


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


Wednesday, June 5, 2013

How to Hide a List or Library in SharePoint?

How to Hide a SharePoint list or library from browser? 
But why? Because, My custom application uses some configurations which should be stored and retrieved from a SharePoint list, but it must not be visible to end-users to avoid any mess. So, we got to hide our configuration list from users.

We don't want the configuration list to be available to users, but visible only for the custom application code to read/write in it.  So lets hide the configuration lists from "View All Site Content" page.

Solution:
To hide a SharePoint 2007 or SharePoint 2010 list or library, either we've to use SharePoint API (Set SPList.Hidden property of the SharePoint list programmatically with either C# Object Model code or PowerShell) or use SharePoint designer.

Even SharePoint itself uses lots of hidden Lists & Libraries for its own operations (E.g. "Content and Structure Reports", "Master Page Gallery", "Form Templates", "User Information List", etc)

To hide a list in SharePoint 2010 using PowerShell:
To hide library in SharePoint, use the below PowerShell script.

#Define the Web URL & List Name
$WebUrl = "http://sharepoint.crescent.com/sites/Sales"
$ListToHide = "AppConfig"

#Get the Web
$web = Get-SPWeb $WebUrl
#Get the List
$list = $web.Lists[$ListToHide]

#Set the Hidden Property
$list.Hidden = $true
$list.Update()

#Displose Web Object
$web.Dispose()

Hide SharePoint 2013 List using CSOM-PowerShell:
#Load SharePoint CSOM Assemblies
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime") | Out-Null

#Variables for Processing
$SiteUrl = "https://portal.crescent.com/sites/sales"
$LibraryName="Team Docs"
 
#Setup Credentials to connect
$Credentials = [System.Net.CredentialCache]::DefaultCredentials

#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) 
$Context.Credentials = $credentials

#Get the List and Make it hidden
$list = $Context.Web.Lists.GetByTitle($LibraryName)
$list.Hidden = $true
$list.Update()
$Context.ExecuteQuery()

Hide a Document Library in SharePoint using C# Object Model Code:
using (SPSite site = new SPSite("http://sharepoint.crescent.com/sites/Sales"))
{
    using (SPWeb web = site.OpenWeb())
    {
       SPList configList = web.Lists["AppConfig"];
       configList.Hidden = true;
       configList.Update();
    }
}
This method of hiding SharePoint list applies to any SharePoint List, Document Library, picture library, etc.
hide sharepoint list from view all site content
This is how we can actually hide the lists from user view  programmatically using C# or PowerShell.
Programmatically setting the Hidden property of the list will also hide the list from Quick Launch bar.  However, It is possible that the document library link may be placed in Quick launch manually and still appears! so take care of it.

Hide a list from users using SharePoint Designer:
Here is how we can hide a document library or list in SharePoint 2010:

  • Open the site in SharePoint Designer, Right click the target list >> Choose List settings >> General Settings
  • Check the "Hide from browser" option
  •  Uncheck the "Display this list on quick launch" option
  •  Click on "Save" button to apply the changes
hide document library in sharepoint 2010
Now, Open it SharePoint site in browser and verify that your list is hidden.

To Unhide a Hidden list in SharePoint Designer:
Unhide a hidden list is little tricky! The above steps to hide list in SharePoint, will also hide the list from SharePoint designer's "Lists and Libraries" section. So, To unhide the list:
  • Go to "All Files" folder from the SharePoint designer left pane Treeview.
  • Right click on your hidden list >> Choose Properties
  • Revert back the settings "Hide from browser" to false and "Display this list on quick launch" to True! Save your settings.
  • Now, you'll get the hidden list back in the browser and in the SharePoint designer.
Remember, although list's hidden property is set, it will not stop users from directly hitting the list URL in browser and get into the list! E.g. http://sharepoint.Crescent.com/Lists/AppConfig
If you really concerned about the confidentiality of the list, To hide a list from users: You have to break list permission inheritance and remove all user permissions from the list. So that the list data will not be visible to any users (But this doesn't control Site collection Admins, Farm Admins with Web Application Policy).

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


Saturday, June 1, 2013

Change "Save" or "OK" Button Text on SharePoint List Forms

Wouldn't it be more meaningful to rename SharePoint List NewForm.aspx "Save" or "OK" button text to "Submit" in Request Tracking Lists?

Yes! Sure, I'll possible to change "Save" button's text to something else which gives more meaningful in the context.

Using jQuery to Rename "Save" button Text:
Place the below jQuery script in a text file, Upload it to a document library, add a CEWP to the NewForm.aspx page, and specify the "Content Link" in Content Editor Web Part's Property Pane.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
 
<script>
    $(document).ready(function()
      {
                    $("input[value$='Save']").attr('value', "Submit");
     });

</script>
Result in action: SharePoint 2010 change save button text
sharepoint 2010 change save button text

Using JavaScript to Set SharePoint save button text:
Open the NewForm.aspx in browser, Append: ?toolpaneview=2 , (E.g. http://sharepoint.crescent.com/sharepointsupport/lists/URLChangeRequests/NewForm.aspx?toolpaneview=2) You will get the page in edit mode. Now, add the CEWP below List View Web part and place the below code:

<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("changeOKBtnTxt()");

function changeOKBtnTxt()
{
//Get all Input Elements on the page
var inputs = document.getElementsByTagName("input");

//Get the "OK" button
for(i = 0; i<inputs.length; i++)
 {
    if(inputs[i].type == "button" && inputs[i].value == "OK")
     {
      //Change the "OK" button's Text to "Submit"
      inputs[i].value = "Submit";
     } 
  }

}
</script>
sharepoint 2007 change ok button text
Its also possible to do it with SharePoint Designer. You have to hide the Default OK button and add custom buttons as explained in this post: Redirect Users to Thank You page from NewForm.aspx after form submission

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...