Wednesday, June 25, 2014

Nintex Workflow Timeout Issue - Solutions

Recently got these timeout related errors in Nintex workflow 2007 with MOSS 2007 environment:
  • "Failed to report workflow progress. Failed to open a connection to a Nintex Workflow content database"
  • "Failed to Start Workflow. Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding"
  • Error: Timeout expired. The timeout period elapsed prior to completion of the server is not responding
Here is some error screenshots:
Failed to report workflow progress. Failed to open a connection to a Nintex Workflow content database
 and the another one:
Failed to Start Workflow. Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding
Meanwhile, In Event Logs, Found these errors:
Nintex Workflow; Build: 11201 (http://sharepoint.crescent.com/finance/approvals/default.aspx)
System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader()
   at Nintex.Workflow.Reports.MyWorkflowInfoCollection.BuildCollection(String username, SPWeb web, Int32 minRow, Int32 maxRow, String orderBy, OrderByDirection direction, List`1 statesToShow)
   at Nintex.Workflow.Reports.MyWorkflowInfoCollection..ctor(String user, SPWeb web, Int32 minRow, Int32 maxRow, String orderBy, OrderByDirection orderByDirection, List`1 statesToShow, Boolean& additionalRows)
   at Nintex.Workflow.ServerControls.WebParts.MyWorkflows.LoadView()
   at Nintex.Workflow.ServerControls.WebParts.MyWorkflows.Render(HtmlTextWriter writer)

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

Troubleshooting Steps:

Verify database is up and running and there is no network connectivity issues between Web and Database Severs. Follow these steps to troubleshoot timeout issues.

1. Increase Timeout value: 
Get the current database connection timeout value by:
stsadm -o getproperty -pn database-connection-timeout

By default, it would be 15 seconds. You can increase the timeout with the below command:
stsadm -o setproperty -pn database-connection-timeout -pv 60
This can be used for SharePoint Database connectivity Timeout Issues too.

2. Workflow Content Database may grown to large in size:
Large amount of data in the Nintex content database tables could likely to cause SQL Server timeout errors. So, Analyze Nintex content database table sizes. Here is how to do it in SQL Server 2008 and above.
  1. Open SQL Management Studio >> Expand the Database node
  2. Find the Nintex Workflow database (usually named NW2007DB or NW2010DB)
  3. Right-click on the Nintex Workflow database and select Reports > Standard Reports > Disk Usage by Table
If you are running with SQL Server 2005, use the below query to analyze database table usages:
USE [Nintex_WF_2007_Content]
begin try 
SELECT 
 a3.name AS [schemaname],
 a2.name AS [tablename],
 a1.rows as row_count,
 (a1.reserved + ISNULL(a4.reserved,0))* 8 AS reserved, 
 a1.data * 8 AS data,
 (CASE WHEN (a1.used + ISNULL(a4.used,0)) > a1.data THEN 
   (a1.used + ISNULL(a4.used,0)) - a1.data ELSE 0 END) * 8 AS index_size,
 (CASE WHEN (a1.reserved + ISNULL(a4.reserved,0)) > a1.used THEN 
   (a1.reserved + ISNULL(a4.reserved,0)) - a1.used ELSE 0 END) * 8 AS unused
FROM
 (SELECT 
  ps.object_id,
  SUM (
   CASE
    WHEN (ps.index_id < 2) THEN row_count
    ELSE 0
   END
   ) AS [rows],
  SUM (ps.reserved_page_count) AS reserved,
  SUM (
   CASE
     WHEN (ps.index_id < 2) THEN 
   (ps.in_row_data_page_count + ps.lob_used_page_count + ps.row_overflow_used_page_count)
     ELSE (ps.lob_used_page_count + ps.row_overflow_used_page_count)
   END
   ) AS data,
  SUM (ps.used_page_count) AS used
 FROM sys.dm_db_partition_stats ps
 GROUP BY ps.object_id) AS a1
LEFT OUTER JOIN 
 (SELECT 
  it.parent_id,
  SUM(ps.reserved_page_count) AS reserved,
  SUM(ps.used_page_count) AS used
  FROM sys.dm_db_partition_stats ps
  INNER JOIN sys.internal_tables it ON (it.object_id = ps.object_id)
  WHERE it.internal_type IN (202,204)
  GROUP BY it.parent_id) AS a4 ON (a4.parent_id = a1.object_id)
INNER JOIN sys.all_objects a2  ON ( a1.object_id = a2.object_id ) 
INNER JOIN sys.schemas a3 ON (a2.schema_id = a3.schema_id)
WHERE a2.type <> 'S' and a2.type <> 'IT'
ORDER BY a3.name, a2.name
end try 
begin catch 
select 
        ERROR_NUMBER() as tablename
,       ERROR_SEVERITY() as row_count
,       ERROR_STATE() as reserved
,       ERROR_MESSAGE() as data
,       1 as index_size
,   1 as unused 
end catch
Make sure: dbo.WorkflowProgress table down to about 10-15 million rows!

What to do when Workflow Progress table is over sized?
You can reduce the size of the workflow progress database table: http://connect.nintex.com/files/folders/white_papers/entry30032.aspx

Find Which Workflows Causing this bottleneck: 
Lets find which workflows are flooding the database tables. Use the below query to find all Nintex workflows (such as: Popular workflows or errored workflows) which may over utilize workflow progress table.
SELECT TOP 100 
I.WorkflowName, 
I.WorkflowInstanceID, 
I.SiteID, 
I.WebID, 
I.ListID, 
I.ItemID, 
I.WorkflowInitiator, 
I.WorkflowID,
I.State, COUNT(P.WorkflowProgressID) as WorkflowProgressRecords
FROM WorkflowInstance I inner join WorkflowProgress P WITH (NOLOCK)
ON I.InstanceID = P.InstanceID
--WHERE i.State=2 
GROUP BY I.WorkflowName, I.WorkflowInstanceID, I.SiteID, I.WebID, I.ListID, I.ItemID, I.WorkflowInitiator, I.WorkflowID, I.State 
ORDER BY COUNT(P.WorkflowProgressID) DESC
Here is the output:

From the above data, Use: Get SharePoint Site Collection, Web, List Objects from GUID to get the list/web/site objects.

Purge Workflow Data:
So, We got which workflow instances are causing this bottle neck. Next step is to Purge workflow data! Lets Purge workflow data using Nintex Admin command line tool: NWAdmin.exe (Located at: C:\Program Files (x86)\Nintex\Nintex Workflow 2007)

NWAdmin.exe -o PurgeWorkflowData -instanceId "GUID of the workflow instance"

Also, You can try purging workflow data based on date, Workflow status, etc. Keep an eye on the workflow content database, Log file sizes. Try truncating log files.

3. Move Workflow data to Another Workflow Content database:
You can also move workflow data to a new workflow content database. Follow these steps:
http://connect.nintex.com/files/folders/30882/download.aspx

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


Tuesday, June 24, 2014

Open with Explorer Error: You might not have permission to use this network resource. Contact the administrator of this server to find out if you have access permissions. The file cannot be accessed by the system.

Problem:
In a SSL enabled SharePoint 2013 sites, "Open with Explorer" functionality didn't work! additionally, editing documents online did not work. It just opens the file in Temporary internet files folder and updates ONLY the local file but not the one in SharePoint.

Open with Explorer resulted with an error message:
\\SharePointSiteURL@SSL\DavWWWRoot is not accessible. You might not have permission to use this network resource. Contact the administrator of this server to find out if you have access permissions. 

The file cannot be accessed by the system.
@SSL\DavWWWRoot is not accessible. You might not have permission to use this network resource. Contact the administrator of this server to find out if you have access permissions.      The file cannot be accessed by the system.

Troubleshooting:
Tried various solutions including hot-fixes, registry fixes, etc.

Solution:
And finally the solution worked for me: Perform Windows update on client machine!!! Not very sure which patch fixed this problem, But windows update resolved this issue.

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


Monday, June 23, 2014

Remove Theme in SharePoint 2013 using PowerShell

Requirement: To enforce consistency, We wanted to reset custom themes applied on SharePoint sites by end users in our SharePoint environment.

Solution: Remove theme programmatically using PowerShell!
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Variable
$WebAppURL = "http://intranet.crescent.com"

Get-SPWebApplication $WebAppURL | Get-SPSite -Limit ALL | Get-SPWeb | ForEach-Object {
#remove theme sharepoint 2013
$Theme = [Microsoft.SharePoint.Utilities.ThmxTheme]::RemoveThemeFromWeb($Web,$false)
$Web.Update()
}
Write-host "Themes are removed from all sites!" 
This removes and reset to default SharePoint theme. Same script works for SharePoint 2010 also to remove theme.

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


Export SharePoint List Item Version History to Excel

I wrote a PowerShell script and C# object model codes to generate SharePoint version history report in SharePoint document version history report, related to that, got a new requirement to export version history to excel.

This version history report helps to compare what data is changed, who changed the list data, etc over time.  just replace the values of WebURL, ListName variables with your Site/List values and run the script to export version history SharePoint 2013.

Here is the PowerShell script for SharePoint version history export to excel:
# ******* Variables Section ******************
#Define these variables 
$WebURL="http://sharepoint.crescent.com/sites/Sales/"
$ListName ="Invoice"
$ReportFile = "D:\Invoice_VersionHistory.csv"
# *********************************************

#delete file if exists
If (Test-Path $ReportFile)
 {
 Remove-Item $ReportFile
 }

#Get the Web and List
$Web = Get-SPWeb $WebURL
$List = $web.Lists.TryGetList($ListName) 

 #Check if list exists
 if($List -ne $null)
 {
  #Get all list items
  $ItemsColl = $List.Items
  
  #Write Report Header
  Add-Content -Path $ReportFile -Value "Item ID, Version Lable, Created by, Created at, Title" 
 
  #Loop through each item
  foreach ($item in $ItemsColl) 
  {
   #Iterate each version
      foreach($version in $item.Versions)
       {
    #Get the version content
    $VersionData = "$($item.id), $($version.VersionLabel), $($version.CreatedBy.User.DisplayName), $($version.Created), $($version['Title'])"
    #Write to report
    Add-Content -Path $ReportFile -Value $VersionData
   }
  }
 }
Write-Host "Version history has been exported successfully!"

Please note, in Line number 25 and 36, I've added only "Title" field from the list. You may want to add additional fields as per your requirement. on running the script, all list item versions will be exported to excel (CSV format).

To export SharePoint document version history, Refer: Extract and Download all document versions

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


Sunday, June 22, 2014

How to Disable Mobile Views in SharePoint 2013

SharePoint 2013's new mobile features are definitely improved a lot from its previous versions. Now it provides support for a variety of mobile devices, Geo-location, Office Web Apps integration, Device Channels, etc.  However there are certain shortfalls in SharePoint 2013 mobile view such as it doesn't provide responsive web sites, lack of menus and navigation, features like people picker, upload files doesn't work, calendar views are too difficult navigate, etc.

SharePoint 2013 mobile example
sharepoint 2013 mobile home page
sharepoint 2013 mobile interface
sharepoint 2013 list mobile view
SharePoint 2013 disable mobile redirect
In my case, we wanted to take control over mobile web sites and disable mobile view for our public SharePoint web sites, as it loads default mobile view with most of the features disabled. Here are the two methods that helped me to turn off mobile view in SharePoint 2013.
  1. Deactivate Mobile Browser View feature
  2. Disable Mobile redirect behavior in SharePoint 2013

Method 1: Deactivate SharePoint Mobile feature

In SharePoint 2013, the Mobile Browser View feature is enabled by default for all sites. This feature is responsible for rendering different User Interface when SharePoint is viewed on a mobile devices To Deactivate Mobile view in SharePoint 2013 follow these steps:
  • Open your SharePoint site >> Click on Site Settings
  • Click on "Manage Site Features" link under site actions section.
  • Locate and click on "Deactivate" button next to "Mobile Browser View" feature
    sharepoint 2013 disable mobile site
That's all! This disables mobile redirect on the particular SharePoint site. But wait! This feature is scoped at site level. So, if you want to turn off mobile view for your SharePoint 2013, you have to repeat these steps in each and every site in your web application!

Disable mobile view in SharePoint 2013 using PowerShell
Fortunately, we have PowerShell. Lets use PowerShell to deactivate mobile friendly sites.
Disable-SPFeature -Identity MBrowserRedirect -Url http://yoursite 
Mobile view is scoped at web object. So in order to disable mobile view on all sites in the web application, Here is my PowerShell script.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$WebAppURL = "http://portal.crescent.com"

#In SharePoint 2010: $FeatureName = "MobilityRedirect"

$FeatureName = "MBrowserRedirect"

#Disable Mobile View feature on all sites in the web application
$WebsCollection = Get-SPWebApplication $WebAppURL | Get-SPSite -Limit ALL | Get-SPWeb -Limit ALL 

#Itereate through each web
ForEach($Web in $WebsCollection)
{ 
    #Check if feature is already activated
    $feature = Get-SPFeature -web $Web.Url  | Where-object {$_.DisplayName -eq $FeatureName}

    if($feature -ne $null)
    {
        #Disable the Mobile browser view feature 
        Disable-SPFeature -identity $FeatureName -URL $Web.URL -Force -Confirm:$false 
        write-host "Feature deactivated at site: $($Web.Url)"
    }
 }

Method 2: Change the redirect behavior of a mobile browser

To disable mobile site, Lets edit the "compat.browser" file - which lists all of the browser "user agent" strings that it will redirect. By default this file is located at "c:\inetpub\wwwroot\wss\VirtualDirectories\80\App_Browsers\compat.browser"
  • Login to your SharePoint Web front End(s), Open IIS Manager
  • From IIS Manager, Right click your SharePoint Web site, and choose "Explore". This will open the virtual directory of your SharePoint web application.
  • Open "App_Browsers" folder and then Open "compat.browser" file in a Notepad (or any other text editor)
  • You'll find multiple "Browser" nodes in file. E.g.
        <!-- Windows Phone -->
        <browser id="WindowsPhone" parentID="IE6to9">
            <identification>
                <userAgent match="Windows Phone"/>
                <userAgent nonMatch="IEMobile"/>
            </identification>
            <capabilities>
                <capability name="isMobileDevice" value="true" />
            </capabilities>
        </browser>
  • Just change the "Value" attribute of the node "Capability" from "true" to "false".
       <capability name="isMobileDevice" value="false" />
  • Search and replace this attribute for all occurrences in the file. Save and Restart IIS! 
This method Turns-Off Mobile redirect for all specific mobile browsers.

Turn Off Mobile Redirect for a Web Application:
While the above method disables mobile redirect per device, There are chances that some devices/browsers may not be listed there. Also there is a high probability of SharePoint service packs overwriting our changtes with latest updates. So, lets see the alternate approach of disabling mobile view in SharePoint 2013 by editing web.config file.

Add the below code with in <configuration> node, just before </system.web> node of the web.config file (located at the root of your SharePoint web site in IIS) of your SharePoint web application.
    <browserCaps>
        <result type="System.Web.Mobile.MobileCapabilities, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        <filter>isMobileDevice=false</filter>
    </browserCaps>
and my screenshot:
sharepoint 2013 turn off mobile view
This eliminates the ability to detect all mobile browsers in SharePoint 2013. All of these procedures applicable to SharePoint Foundation as well.

Best practice: Instead of disabling mobile views, you can utilize "Device Channels" feature in SharePoint 2013. Device Channels feature lets you to display the same site content with different master pages, page layouts and CSS targeted to specific mobile devices.

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


Fix "The form submission cannot be processed because it exceeded the maximum length allowed by the web administrator." error in SharePoint 2013

Getting "The form submission cannot be processed because it exceeded the maximum length allowed by the web administrator. Please resubmit the form with less data" error in SharePoint 2013 when trying to upload a file?

Root cause: By default, SharePoint 2013 web applications have limitation on maximum upload size for documents. If you try to upload a file bigger than 250 MB, you will get this error message.
The form submission cannot be processed because it exceeded the maximum length allowed by the web administrator
Resolution:
You need to increase maximum upload size in SharePoint 2013 central administration site:
  • Go to Central Administration >> Application Management >> Select required web application 
  • Click on "Web Application General Settings"
  • Change the "Maximum Upload Size" value
Here is my article to configure maximum file size limit in SharePoint 2013: Increase Maximum File Upload Size in SharePoint 2013

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


Tuesday, June 17, 2014

How to Enable Chart Web Part in SharePoint 2013

As per Microsoft, Chart web part in SharePoint 2013 has been discontinued, So, chart web part will be missing! Of course there are many 3rd party products available to bring Chart functionality in SharePoint 2013, is it possible to resurrect the same old chart Web part in SharePoint 2013? Yes! We can!! Here is how to enable chart web part in SharePoint 2013:
Disclaimer: I'm not sure this is a fully supported method, but it serves the purpose!
Step 1: Save this below chunk as a "Chart.Webpart" file
<webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type name="Microsoft.Office.Server.WebControls.ChartWebPart, Microsoft.Office.Server.Chart, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      <importErrorMessage>Cannot import Chart Web Part.</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="RealTimeInterval" type="int">0</property>
        <property name="Height" type="unit" />
        <property name="IsCustomized" type="bool">False</property>
        <property name="ListUrl" type="string" null="true" />
        <property name="AllowConnect" type="bool">True</property>
        <property name="CatalogIconImageUrl" type="string" />
        <property name="Title" type="string">Chart Web Part</property>
        <property name="Hidden" type="bool">False</property>
        <property name="ShowDebugInfoRuntime" type="bool">False</property>
        <property name="BindToDataDesignMode" type="bool">True</property>
        <property name="TitleIconImageUrl" type="string" />
        <property name="ChromeState" type="chromestate">Normal</property>
        <property name="Description" type="string">Helps you to visualize your data on SharePoint sites and portals.</property>
        <property name="ChartXml" type="string">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Chart BorderColor="26, 59, 105" BorderWidth="1" BorderlineDashStyle="Solid"&gt;
  &lt;Series&gt;
    &lt;Series Name="Default" ShadowOffset="2" ChartArea="Default" BorderColor="26, 59, 105"&gt;
    &lt;/Series&gt;
  &lt;/Series&gt;
  &lt;ChartAreas&gt;
    &lt;ChartArea BackColor="White" ShadowOffset="2" BorderColor="26, 59, 105" BorderDashStyle="Solid" Name="Default"&gt;
      &lt;AxisY&gt;
        &lt;MajorGrid LineColor="Silver" /&gt;
        &lt;MinorGrid LineColor="Silver" /&gt;
      &lt;/AxisY&gt;
      &lt;AxisX&gt;
        &lt;MajorGrid LineColor="Silver" /&gt;
        &lt;MinorGrid LineColor="Silver" /&gt;
      &lt;/AxisX&gt;
      &lt;AxisX2&gt;
        &lt;MajorGrid LineColor="Silver" /&gt;
        &lt;MinorGrid LineColor="Silver" /&gt;
      &lt;/AxisX2&gt;
      &lt;AxisY2&gt;
        &lt;MajorGrid LineColor="Silver" /&gt;
        &lt;MinorGrid LineColor="Silver" /&gt;
      &lt;/AxisY2&gt;
    &lt;/ChartArea&gt;
  &lt;/ChartAreas&gt;
  &lt;BorderSkin BackColor="CornflowerBlue" BackSecondaryColor="CornflowerBlue" /&gt;
&lt;/Chart&gt;</property>
        <property name="WorkBookUrl" type="string" null="true" />
        <property name="AllowMinimize" type="bool">True</property>
        <property name="ChromeType" type="chrometype">Default</property>
        <property name="AlignDataPointsByAxisLabel" type="bool">False</property>
        <property name="AllowZoneChange" type="bool">True</property>
        <property name="DataBindingsString" type="string">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;ArrayOfDataBinding xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" /&gt;</property>
        <property name="ShowToolbar" type="bool">True</property>
        <property name="Width" type="unit" />
        <property name="HelpMode" type="helpmode">Navigate</property>
        <property name="TitleUrl" type="string" />
        <property name="DesignerTemplateId" type="string" />
        <property name="HelpUrl" type="string" />
        <property name="ExportMode" type="exportmode">All</property>
        <property name="ConnectionPointEnabled" type="bool">True</property>
        <property name="AllowClose" type="bool">True</property>
        <property name="AllowEdit" type="bool">True</property>
        <property name="Direction" type="direction">NotSet</property>
        <property name="AllowHide" type="bool">True</property>
        <property name="DesignerChartTheme" type="Microsoft.Office.Server.Internal.Charting.Utilities.ChartTheme, Microsoft.Office.Server.Chart, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">BrightPastel</property>
      </properties>
    </data>
  </webPart>
</webParts>
BTW, I exported this from SharePoint 2010!

Step 2: Upload the web part to Web parts gallery:
Next step is to enable chart web part in SharePoint 2013.
  • Go to Site Settings >> Click on "Web Parts" link under "Web Designer Galleries" section.
  • On the "Files" tab, Click on "Upload Document"
  • Locate the "Chart.webpart" file and specify web part attributes.
how to enable chart web part in sharepoint 2013

Step 3: Add chart web part to SharePoint 2013 page:
So, now we have the web part ready! Navigate to any page where you want to add chart web part, Click on "Web Part" from "Insert" tab, Choose "Chart Web Part" and click "OK".
chart web part in sharepoint 2013
Configure Data connections and other properties of the chart, and here is the output:
how to create chart web part in sharepoint 2013
This chart web part also works in SharePoint online 2013!

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


Add New URL to Host-named Site Collection's Zone

Requirement:
In a  SharePoint hosting Web application, once sites are provisioned from hosting control panel, We got to manually add a internet zone URL with "https" to make it available over Internet.

PowerShell script to Add new URL to internet zone for a host-named site collection:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$OutPutFile = "c:\Scripts\Log"
 
#Get All Host Named Sites of the Hosting Web Application
$SitesColl = Get-SPSite -Limit $All | Where-Object {$_.HostHeaderIsSiteName -eq $true} 

#Loop through each site
ForEach($site in $SitesColl)
 {
    #Check if site created in Internet Zone
    if( (Get-SPSiteURL -Identity $site.Url | Where Zone -eq "Internet").count -eq 0)
    {
        Set-SPSiteURL -Identity $site.URL -Zone Internet -Url ($site.Url -replace "http", "https")
 Write-host "Created Internet Zone for site:"$site.Url 

        #Append to a Log
 "Created Internet Zone for site: $($site.Url) on $(get-date)" >> $OutPutFile
    }
 }
Scheduled the script to run for every 5 minutes using Windows Task scheduler.

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


Monday, June 16, 2014

SharePoint 2013 Error: Unexpected response from server. The status code of response is '500'. The status text of response is 'System.ServiceModel.ServiceActivationException'.

SharePoint 2013 Search returned an error:
Unexpected response from server. The status code of response is '500'. The status text of response is 'System.ServiceModel.ServiceActivationException'.


In Event logs of SharePoint web front ends, it left an event:
System.ServiceModel.ServiceHostingEnvironment+HostingManager/33228940
Exception: System.ServiceModel.ServiceActivationException: The service '/_vti_bin/client.svc' cannot be activated due to an exception during compilation.


Solution: 
Either increase the Server Memory or Try closing some running applications in the SharePoint WFEs to freed up the memory in server!

You can also try limiting the memory consumption on various services running on the server. Here are some:
  • Limit the search service 
    • Set-SPEnterpriseSearchService -PerformanceLevel Reduced 
  • Limit the NodeRunner.exe's memory (NodeRunner is a SharePoint Search component)
    • Open the configuration file at "C\Program Files\Microsoft Office Servers\15.0\Search\Runtime\1.0\noderunner.exe.config" Locate the node "nodeRunnerSettings" and set the value for "memoryLimitMegabytes" attribute (Say: 100). By default its value is 0 (which means unlimited). Once done, restart SharePoint Search Host Controller process.
Do not limit node runner memory in Production Servers!

It also happens with you try add/update new items to SharePoint 2013 lists:



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


Move Files Between Document Libraries with Metadata and Version History

Requirement: We have a very large document library with more than 100,000 documents which is causing search crawl and latency issues. So, decided to archive old documents into separate document libraries year-wise.
Stop: Before proceeding with any of the below method, Save your source list or library as a template without including content and create new list from the list template, So that your source and destination libraries will look a like!

Solution 1 - Using Content and Structure page to move files with versions and Metadata:
All SharePoint versions including MOSS 2007, SharePoint 2010 and SharePoint 2013 supports this functionality.
  • Go to Site settings >> Click on "Content and structure" link under Site Administration section
    sharepoint move files with version history
  • Pick the items/files to be moved, Click on Actions >> Move 
  • Select the target list or library and click "OK" to complete move operation.
This sends files with version history and metadata to the target list.

Solution 2: Move files between document libraries programmatically using PowerShell:
Lets use PowerShell script to move files between lists: The idea is to create sub-folder for each Month and move documents into sub-folders based on their creation date.
#For MOSS 2007 compatibility
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

Function global:Get-SPWeb($url)
{
  $site= New-Object Microsoft.SharePoint.SPSite($url)
        if($site -ne $null)
            {
               $web=$site.OpenWeb();        
            }
    return $web
}

#Get the web and List
$Web = Get-SPWeb "http://intranet.sharepoint.com/sites/Marketing/"
$SourceList = $web.Lists["Proposals"]
$TargetList = $Web.Lists["Proposal Archive 2009"]

#Get all Files Created in 2009
 $Query = '<Where><And><Geq><FieldRef Name="Created" /><Value IncludeTimeValue="TRUE" Type="DateTime">2009-01-01T00:00:00Z</Value></Geq><Leq><FieldRef Name="Created" /><Value IncludeTimeValue="TRUE" Type="DateTime">2009-12-31T23:59:59Z</Value></Leq></And></Where>'
 $SPQuery = new-object Microsoft.SharePoint.SPQuery
 #$SPQuery.ViewAttributes = "Scope='Recursive'" #To include Sub-folders in the library
 $SPQuery.Query = $Query
 $SourceFilesCollection =$SourceList.GetItems($SPQuery)

Write-host "Total number of files found: "$SourceFilesCollection.count

#Move each file to the destination folder
foreach($item in $SourceFilesCollection)
{
  #Get the Source File
  $file = $Web.GetFile($item.File.URL)

  #Get the Month value from the File crated date
  $MonthValue = $item.File.TimeCreated.ToString('MMMM')
  
  # Try to Get the Sub-Folder in the Library!
  $TargetFolder = $TargetList.ParentWeb.GetFolder($TargetList.RootFolder.Url + "/" +$MonthValue);
  
  #If the folder doesn't exists, Create!
  if ($TargetFolder.Exists -eq $false)
   {
     $TargetFolder = $TargetList.Folders.Add("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, $MonthValue)
     $TargetFolder.Update() 
   }

   #Move the File
   $file.MoveTo($TargetFolder.Url + "/" + $File.name)
  
}
While the Move operation preserves Metadata and version history, Copy doesn't!

Solution 3: Move files using SharePoint designer
  • Open your site in SharePoint Designer
  • Go to All Files >> Navigate to source library. Select files you want to copy/move, choose cut/copy
    move files using sharepoint designer
  • Go to your target library, Right click and choose "Paste"
Tips: SharePoint general rule of thumb for better performance on large list and libraries: Have < 2000 files per container (list/library/folder).
All of the above methods move documents between libraries of the same site collection!

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


Enable Versioning for All Document Libraries in SharePoint

SharePoint versioning feature tracks changes, so that you can View document or item's version history and audit/recover them if needed. 

How to enable versioning in SharePoint?
Version feature is configured at list or library level. So, to enable version history:
  • Go to your document library >> Click the Library tab on the Ribbon >> Click on Library Settings.
  • Under general Settings, click Versioning Settings link.
  • From the Versioning Settings page, choose "Create major versions". Optionally, you can set a limit on number of versions.
sharepoint 2010 enable versioning all document libraries
This enables SharePoint version history. Once versioning feature is enabled, you can select a document and click on "Version History" icon from the Ribbon to view versions created.

Enable Versioning on All Document Libraries of All Sites in SharePoint
Well activating versioning is quite simpler as shown above! But you may want to enable versioning for all document libraries from all sites in your site collection. You may have a site collection with 100's of subsites, all with document libraries loaded.

Unfortunately there is no direct way through UI to enable versioning on all libraries at Site Collection level. Here is where PowerShell scripts comes to help you to enable versioning in all libraries programmatically.

Enable versioning for all document libraries using PowerShell
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

$webURL="http://demo.crescent.com"
#Get the Web
$web = Get-Spweb $webURL

#Get all lists - Exclude System lists
$ListColl = $web.lists | Where-Object  { ($_.hidden -eq $false) -and ($_.IsSiteAssetsLibrary -eq $false) -and ($_.BaseType -eq "DocumentLibrary") }

foreach($list in $ListColl)
 {
    if ($list.EnableVersioning -eq $false) 
    {
        #Enable Versioning Settings
        $list.EnableVersioning = $true
        $list.MajorVersionLimit = 5 #No. of versions - versioning best practices
        $list.EnableMinorVersions = $true #Applicable only to Libraries
        $list.MajorWithMinorVersionsLimit = 5 #No. of Drafts in Lists

        $list.Update() 
        write-host Versioning enabled for: $list.RootFolder.URL
    }
}
This script enables versioning programmatically in the entire site.

How to Enable versioning by default?
Versioning is disabled by default! There is no automatic versioning in SharePoint. There is no OOTB way to turn on versioning globally . One trick could be: using List templates - Create a Base list or library, Enable versioning, Save list as template. Any list or library created from this template have versioning turned on by default! You can also try Event Receivers -ListAdded event.

SharePoint Versioning best practices:
It is important to keep in mind that each version is basically a copy of the document or item. so if you are editing a 10 MB file for 10 times, it occupies 100 MB of disk. This could eventually affect the performance of your site. So, Its a best practice to set versioning limits.  Thankfully, SharePoint 2013 shredded storage brings the advantage of storing only the versioning delta.

Related Posts:


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


Saturday, June 14, 2014

Remove All Users from SharePoint Site, List with PowerShell

Requirement: There is a SharePoint 2013 list lot of user permissions. Wanted to remove all user permissions from that SharePoint list. So tried removing all users, but SharePoint gave "You have chosen to delete too many groups at once. Select fewer groups and try again." when choosing All users check box and Remove them from SharePoint site or group.

So the problem here is: We can't delete users in bulk when it exceeds the maximum count by SharePoint. Here is my nifty PowerShell scripts to remove all users from SharePoint site or List.

PowerShell script to remove all user permission from SharePoint list:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Variables
$SiteUrl="http://your-sharepoint-site.com" 
$ListName="Your-List-Name" 

#get the Web
$web = Get-SPWeb $SiteUrl
#Get the List
$list = $web.Lists[$ListName]

#If the List is not using Unique permissions, Break inheritance
if(!$list.HasUniqueRoleAssignments)
{
    #Break list inheritance - without copying users
    $list.BreakRoleInheritance($false)
}

#Remove all users from the list
 for ($i = $list.RoleAssignments.Count - 1; $i -ge 0; $i--)
    {
      $RoleAssignment = $list.RoleAssignments[$i]
      $list.RoleAssignments.RemoveByID($RoleAssignment.Member.ID)
      write-host "Removed User/Group :" $RoleAssignment.Member.name
    } 
Remove all users from SharePoint site
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Site collection URL 
$SiteUrl="http://demo.sp.cloudservicesme.com" 

#get the Root Web
$web = Get-SPWeb $SiteUrl

#Get All Users of the site collection
$UserAccounts = @()
foreach ($user in $web.SiteUsers)
{
   $UserAccounts = $UserAccounts + $user.loginname
}

#Remove all users one by one.
foreach ($user in $UserAccounts)
{
    try
    {
        #Set the Error Action
        $ErrorActionPreference = "Stop"

        #Remove User if not site admin
        if(!$web.SiteUsers[$User].isSiteAdmin)
        {
            $web.SiteUsers.Remove($user)
            Write-host "User Removed :" $user -ForegroundColor Green
        }
    }
    catch    
    {
        Write-host "Failed to remove the user:" + $user -ForegroundColor Red   
    }
    Finally
    {
        #Reset the Error Action to Default
        $ErrorActionPreference = "Continue"
    } 
}


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


Thursday, June 12, 2014

Sync-Update User Display Name from Active Directory to SharePoint

Problem: Discrepancies in User's properties in AD and SharePoint. Say for E.g. User''s display name property updated in Active Directory. But SharePoint still shows the old display name for the user.

Solution: Ideally, a proper setup of SharePoint user profile sync should avoid these kind of issues. Use these PowerShell scripts to force update from AD to SharePoint.We can use PowerShell script to update display name of the user. E.g.
Set-SPUser -Identity "i:0#.w|domain\username" -DisplayName "NewDisplayName" –Web http://sp-site
The above cmdlet updates the given user's display name for the particular site. Lets do it for all site collections.

PowerShell script to update display name of the user on all site collections in SharePoint:
This PowerShell script scans and updates the given user properties in all sites.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Variables
$UserID = "i:0#.w|Crescent\MichaelF"
$NewDisplayName = "Michael Fisher"

#Get All Site Collections
$Sites = Get-SPSite -limit all

#Iterate through each site collection
foreach ($Site in $Sites)
{
    #Try to Get the User from site collection
    $User = Get-SPUser -identity $UserID -web $Site.url -ErrorAction SilentlyContinue

    #If User found
    If($user)
    {    
        #Update the Display Name of the user
        Set-SPUser -identity $user -DisplayName $NewDisplayName
        Write-host –foregroundcolor green "Display Name updated in Site  $($site.url)"
    }

}
While the above code sets only the given display name, Lets sync all properties, such as E-Mail, Department, Job Title, etc. from AD to SharePoint:
$User = Get-SPuser "i:0#.w|Crescent\michaelf" -web http://intranet.crescent.com 
$User | Set-SPUser -SyncFromAD
 
Sync All User's Properties in All Sites:
How about syncing all user properties in all SharePoint 2010 sites?
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get All Site Collections
$Sites = Get-SPSite -limit all

#Iterate through each site collection
foreach ($Site in $Sites)
{
    #Try to Get the User from site collection
    $UsersColl = Get-SPUser -web $Site.url

    #Process each user
    foreach($user in $UsersColl)
    {    
        $User | Set-SPUser -SyncFromAD -ErrorAction SilentlyContinue

        Write-host –foregroundcolor green "Display Name for $($user.Name) updated in Site  $($site.url)"
    }

}


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


Sunday, June 8, 2014

Get SharePoint Central Admin URL in PowerShell

In a PowerShell script writing, I had to get central admin URL of the SharePoint farm. Tried various approaches and found the below to get SharePoint 2010/SharePoint 2013 Central Administration site URL using PowerShell:

#sharepoint 2010 powershell get central admin url
Get-SPWebApplication -includecentraladministration | where `
  {$_.IsAdministrationWebApplication} | Select -ExpandProperty URL

Alternatively,  you can use:
[Microsoft.SharePoint.Administration.SPAdministrationWebApplication]::Local.URL 


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


Wednesday, June 4, 2014

Enable PDF Preview in SharePoint 2013 with Office Web Apps

PDF preview for SharePoint 2013 integrated with Office web apps isn't enabled by default. Use this below script to enable PDF previews in SharePoint 2013 search results.

SharePoint 2013 office web apps PDF preview:
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

$TenantOwner = Get-SPEnterpriseSearchOwner -Level SSA

#Search Service application name
$ssa = "Search Service Application" 

$Rule = Get-SPEnterpriseSearchPropertyRule -PropertyName "FileType" -Operator "IsEqual"
$Rule.AddValue("pdf")
$RuleCollection = Get-SPEnterpriseSearchPropertyRuleCollection
$RuleCollection.Add($rule)

$Item = New-SPEnterpriseSearchResultItemType -Owner $TenantOwner -SearchApplication $ssa -Name "PDF Preview" -Rules $RuleCollection -RulePriority 1 -DisplayProperties "Title,Author,Size,Path,Description,EditorOWSUSER,LastModifiedTime,CollapsingStatus,DocId,HitHighlightedSummary,HitHighlightedProperties,FileExtension,ViewsLifeTime,ParentLink,ViewsRecent, FileType,IsContainer,SecondaryFileExtension,DisplayAuthor,docaclmeta,ServerRedirectedURL,SectionNames,SectionIndexes,ServerRedirectedEmbedURL, ServerRedirectedPreviewURL" -DisplayTemplateUrl "~sitecollection/_catalogs/masterpage/Display Templates/Search/Item_Word.js" -OptimizeForFrequentUse $true

SharePoint 2013 PDF preview in Search results:
sharepoint 2013 office web apps enable pdf preview
SharePoint 2013 enabling PDF previews in document libraries:
Wictor Wilen has written a great tool to enable PDF previews in SharePoint 2013 document libraries with Office Web Apps 2013: http://www.wictorwilen.se/sharepoint-2013-enabling-pdf-previews-in-document-libraries-with-office-web-apps-2013

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


How to Create Host Named Site Collections in SharePoint 2013

In short, Host-named site collections allows you to have unique URL addresses for each site collection. Say for e.g. Instead of having a typical "Sales" site URL as: http://SharePoint.yourcompany.com/sites/sales, You can have it as http://sales.yourcompany.com and for HR, it can be http://hr.yourcompany.com and so on. As per Technet, HNSC as the preferred method for deploying site collections in SharePoint 2013. So, lets see how to create host named site collection in SharePoint 2013 using PowerShell.
Host named site collections can be managed only through PowerShell as of today!
Before heading into creating Host-named site collections, There are few Points to ponder:
  • All necessary DNS entries must be created prior creating HNSC (Which is obvious!) You can create a Foward lookup zone in DNS with wildcard entry pointing to the Load balancer or Web Server's IP.
  • The web application that houses host named site collection will be created without any host headers and listening to the default port 80. So the "Default web site" of IIS must be deleted first! Also make sure no other web app is using that port without host headers. If this can't be done for any reason, You have to manually add the host header entries in the bindings in IIS on every WFE.
Although, Its possible to create site collections with unique URLs by creating separate web applications in traditionally way, Remember there is a limit of 20 web applications per SharePoint farm!

Create Host-Named Site Collections Step-by-Step:

Step 1. Create hosting Web Application for Host Named site collections:
By default, the New-SPWebApplication cmdlet creates web application in windows classic mode authentication! make sure you are providing -AuthenticationProvider switch to make it on claims authentication mode.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Set variables for New web application creation
$WebAppName = "HNSC Host Web Application"

#Variables for new Application Pool
$AppPoolName = "HNSC App Pool"
#Get the existing Managed Account
$AppPoolAccount = Get-SPManagedAccount "Crescent\SvcAppPool"
#To utilize existing AppPool, Use: Get-SPServiceApplicationPool <AppPoolName>

$ContentDatabase = "SP13_HNSC_Content"
$AuthProvider = New-SPAuthenticationProvider –UseWindowsIntegratedAuthentication

#Create the web application
$WebApp = New-SPWebApplication -ApplicationPool $AppPoolName -ApplicationPoolAccount $AppPoolAccount -Name $WebAppName -Port 82 -AuthenticationProvider $AuthProvider -DatabaseName $ContentDatabase -path "C:\inetpub\wwwroot\wss\VirtualDirectories\HNSCHost" #-URL http://G1WFE01

Step 2. Create Blank Root Site collection without templates:
The root site collection should be created without assigning any template to it. So, it will be a empty-blank site.
$ServerName = "http://G1WFE01"
New-SPSite -URL $ServerName -Name "HNSC Root" -OwnerAlias "Global\SvcOwner"
The above two steps can be performed either by PowerShell or with Central Admin UI and they are one time activity. Once we have the host web application and blank root site collection ready, we can create any number of Host header site collections in it.

Step 3. Create Host Named Site collection using PowerShell
SharePoint 2013 host named site collections can be created using PowerShell only. Here is the PowerShell script to create Host-named site collection:
$HostURL = "http://WFE01"
$OwnerID = "Crescent\Support"
$OwnerMail= "Support@Crescent.com"
$SiteURL = "http://sales.crescent.com"
$TemplateVal ="sts#0" #Team Site
#Create the HNSC
New-SPSite -url $SiteURL -HostHeaderWebApplication $HostURL -owneralias $OwnerID -owneremail $OwnerMail -Template $TemplateVal
That's all! We are done! The above script creates a host named site collection of Team site template. Hit the URL in browser and you should be able to access the site now!!

Tail: Managed Paths in Host-Named site collections:
Unlike SharePoint 2010, SharePoint 2013 allows managed paths in host named site collections. Here is how: Create a new managed path "teams"
New-SPManagedPath "Teams" –Hostheader
Once the managed path is created, we can create site collection underneath as below:
$HostURL = "http://WFE01"
$OwnerID = "Crescent\Salaudeen"
$OwnerMail= "Support@Crescent.com"
$SiteURL = "http://Sales.crescent.com/teams/cloud"
$SiteName = "Clould Sales Team"
$TemplateVal ="sts#0"

#Get the Host named site collection by its name
$webApp = Get-SPWebApplication $HostURL
#Create new Host-named site under the managed path
New-SPSite $SiteURL -OwnerAlias $OwnerID -HostHeaderWebApplication $webApp -Name $SiteName -Template $TemplateVal
Note that, there is no UI to create managed path for host named site collections, instead we have to use PowerShell cmdlet as above.
Info: The managed paths used by HNSC are not the managed paths configured at the web application but instead they are configured on the Farm level
Host-named site collections concepts are explained in my another article: Host Named Site Collections in SharePoint. Technet article for SharePoint 2013 host named site collections with SSL, Migrating path based site collections to Host-named site collection, etc.: SharePoint 2013 Host-named site collection architecture and deployment

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


Tuesday, June 3, 2014

Get User E-mail Address from List Item "Created By" using PowerShell

For a PowerShell automation work, I had to retrieve the Email ID of the user who has created a particular list item. Here is the nifty PowerShell script to retrieve E-mail ID from created by field:

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

#Function to get User's Email from User ID 
Function GetUserEmail($UserValue)
{
    #Uservalue: E.g: "1;#user name";
	$arr = $UserValue.Split(";#");
	$UserID = $arr[0];
	$user = $web.SiteUsers.GetById($UserId);	
	#the above line returns: SPUser Object
	
	return $user.Email
}

$WebURL ="http://sharepoint.crescent.com/SharePointSupport/"
$ListName ="Site Requests"

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

#Get an Item by id
$item = $list.GetItemByID(1)

 #Get Created by User details
 #$item["Author"] Returns something like: 3;#Salaudeen
 $CreatorMail = GetUserEmail($item["Author"])

 Write-Host $CreatorMail

Same thing can be done in C# also to get user email address programmatically.

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


jQuery Image Rotator for SharePoint

Here is the quick and simple way to implement rotating image slider for SharePoint using jQuery.All you have do is: upload slider images to any SharePoint library and change the image paths in Slider section of the below code and place it in content editor web part or Script editor in SharePoint 2013:

jQuery Rotating Banner code:
<div class="im-brand-central-slider">
    <ul class="slider">
        <li><img src="/sites/teams/brandcentral/images1/Home_Rotator/Growth.jpg" /></li>
        <li><img src="/sites/teams/brandcentral/images1/Home_Rotator/ImproveTechOutcomes.jpg" /></li>
        <li><img src="/sites/teams/brandcentral/images1/Home_Rotator/NewEyes.jpg" /></li>
        <li><img src="/sites/teams/brandcentral/images1/Home_Rotator/NextGeneration.jpg" /></li>
<li><img src="/sites/teams/brandcentral/images1/Home_Rotator/PeopleAreKey.jpg"  /></li>
<li><img src="/sites/teams/brandcentral/images1/Home_Rotator/Realize.jpg" /></li>
    </ul>
    <div class="slider-nav">
        <a href="javascript:void(0)" class="slider-prev">Prev</a>
        <a href="javascript:void(0)" class="slider-next">Next</a>
    </div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
    (function ($) {
        "use strict";
        var ver = 'Lite-1.7';
        var msie = /MSIE/.test(navigator.userAgent);
        $.fn.cycle = function (options) {
            return this.each(function () {
                options = options || {};

                if (this.cycleTimeout)
                    clearTimeout(this.cycleTimeout);

                this.cycleTimeout = 0;
                this.cyclePause = 0;

                var $cont = $(this);
                var $slides = options.slideExpr ? $(options.slideExpr, this) : $cont.children();
                var els = $slides.get();
                if (els.length < 2) {
                    if (window.console)
                        console.log('terminating; too few slides: ' + els.length);
                    return; // don't bother
                }

                // support metadata plugin (v1.0 and v2.0)
                var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {});
                var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null;
                if (meta)
                    opts = $.extend(opts, meta);

                opts.before = opts.before ? [opts.before] : [];
                opts.after = opts.after ? [opts.after] : [];
                opts.after.unshift(function () { opts.busy = 0; });

                // allow shorthand overrides of width, height and timeout
                var cls = this.className;
                opts.width = parseInt((cls.match(/w:(\d+)/) || [])[1], 10) || opts.width;
                opts.height = parseInt((cls.match(/h:(\d+)/) || [])[1], 10) || opts.height;
                opts.timeout = parseInt((cls.match(/t:(\d+)/) || [])[1], 10) || opts.timeout;

                if ($cont.css('position') == 'static')
                    $cont.css('position', 'relative');
                if (opts.width)
                    $cont.width(opts.width);
                if (opts.height && opts.height != 'auto')
                    $cont.height(opts.height);

                var first = 0;
                $slides.css({ position: 'absolute', top: 0 }).each(function (i) {
                    $(this).css('z-index', els.length - i);
                });

                $(els[first]).css('opacity', 1).show(); // opacity bit needed to handle reinit case
                if (msie)
                    els[first].style.removeAttribute('filter');

                if (opts.fit && opts.width)
                    $slides.width(opts.width);
                if (opts.fit && opts.height && opts.height != 'auto')
                    $slides.height(opts.height);
                if (opts.pause)
                    $cont.hover(function () { this.cyclePause = 1; }, function () { this.cyclePause = 0; });

                var txFn = $.fn.cycle.transitions[opts.fx];
                if (txFn)
                    txFn($cont, $slides, opts);

                $slides.each(function () {
                    var $el = $(this);
                    this.cycleH = (opts.fit && opts.height) ? opts.height : $el.height();
                    this.cycleW = (opts.fit && opts.width) ? opts.width : $el.width();
                });

                if (opts.cssFirst)
                    $($slides[first]).css(opts.cssFirst);

                if (opts.timeout) {
                    // ensure that timeout and speed settings are sane
                    if (opts.speed.constructor == String)
                        opts.speed = { slow: 600, fast: 200 }[opts.speed] || 400;
                    if (!opts.sync)
                        opts.speed = opts.speed / 2;
                    while ((opts.timeout - opts.speed) < 250)
                        opts.timeout += opts.speed;
                }
                opts.speedIn = opts.speed;
                opts.speedOut = opts.speed;

                opts.slideCount = els.length;
                opts.currSlide = first;
                opts.nextSlide = 1;

                // fire artificial events
                var e0 = $slides[first];
                if (opts.before.length)
                    opts.before[0].apply(e0, [e0, e0, opts, true]);
                if (opts.after.length > 1)
                    opts.after[1].apply(e0, [e0, e0, opts, true]);

                if (opts.click && !opts.next)
                    opts.next = opts.click;
                if (opts.next)
                    $(opts.next).unbind('click.cycle').bind('click.cycle', function () { return advance(els, opts, opts.rev ? -1 : 1); });
                if (opts.prev)
                    $(opts.prev).unbind('click.cycle').bind('click.cycle', function () { return advance(els, opts, opts.rev ? 1 : -1); });

                if (opts.timeout)
                    this.cycleTimeout = setTimeout(function () {
                        go(els, opts, 0, !opts.rev);
                    }, opts.timeout + (opts.delay || 0));
            });
        };

        function go(els, opts, manual, fwd) {
            if (opts.busy)
                return;
            var p = els[0].parentNode, curr = els[opts.currSlide], next = els[opts.nextSlide];
            if (p.cycleTimeout === 0 && !manual)
                return;

            if (manual || !p.cyclePause) {
                if (opts.before.length)
                    $.each(opts.before, function (i, o) { o.apply(next, [curr, next, opts, fwd]); });
                var after = function () {
                    if (msie)
                        this.style.removeAttribute('filter');
                    $.each(opts.after, function (i, o) { o.apply(next, [curr, next, opts, fwd]); });
                    queueNext(opts);
                };

                if (opts.nextSlide != opts.currSlide) {
                    opts.busy = 1;
                    $.fn.cycle.custom(curr, next, opts, after);
                }
                var roll = (opts.nextSlide + 1) == els.length;
                opts.nextSlide = roll ? 0 : opts.nextSlide + 1;
                opts.currSlide = roll ? els.length - 1 : opts.nextSlide - 1;
            } else {
                queueNext(opts);
            }

            function queueNext(opts) {
                if (opts.timeout)
                    p.cycleTimeout = setTimeout(function () { go(els, opts, 0, !opts.rev); }, opts.timeout);
            }
        }

        // advance slide forward or back
        function advance(els, opts, val) {
            var p = els[0].parentNode, timeout = p.cycleTimeout;
            if (timeout) {
                clearTimeout(timeout);
                p.cycleTimeout = 0;
            }
            opts.nextSlide = opts.currSlide + val;
            if (opts.nextSlide < 0) {
                opts.nextSlide = els.length - 1;
            }
            else if (opts.nextSlide >= els.length) {
                opts.nextSlide = 0;
            }
            go(els, opts, 1, val >= 0);
            return false;
        }

        $.fn.cycle.custom = function (curr, next, opts, cb) {
            var $l = $(curr), $n = $(next);
            $n.css(opts.cssBefore);
            var fn = function () { $n.animate(opts.animIn, opts.speedIn, opts.easeIn, cb); };
            $l.animate(opts.animOut, opts.speedOut, opts.easeOut, function () {
                $l.css(opts.cssAfter);
                if (!opts.sync)
                    fn();
            });
            if (opts.sync)
                fn();
        };

        $.fn.cycle.transitions = {
            fade: function ($cont, $slides, opts) {
                $slides.not(':eq(0)').hide();
                opts.cssBefore = { opacity: 0, display: 'block' };
                opts.cssAfter = { display: 'none' };
                opts.animOut = { opacity: 0 };
                opts.animIn = { opacity: 1 };
            },
            fadeout: function ($cont, $slides, opts) {
                opts.before.push(function (curr, next, opts, fwd) {
                    $(curr).css('zIndex', opts.slideCount + (fwd === true ? 1 : 0));
                    $(next).css('zIndex', opts.slideCount + (fwd === true ? 0 : 1));
                });
                $slides.not(':eq(0)').hide();
                opts.cssBefore = { opacity: 1, display: 'block', zIndex: 1 };
                opts.cssAfter = { display: 'none', zIndex: 0 };
                opts.animOut = { opacity: 0 };
                opts.animIn = { opacity: 1 };
            }
        };

        $.fn.cycle.ver = function () { return ver; };

        // @see: http://malsup.com/jquery/cycle/lite/
        $.fn.cycle.defaults = {
            animIn: {},
            animOut: {},
            fx: 'fade',
            after: null,
            before: null,
            cssBefore: {},
            cssAfter: {},
            delay: 0,
            fit: 0,
            height: 'auto',
            metaAttr: 'cycle',
            next: null,
            pause: false,
            prev: null,
            speed: 1000,
            slideExpr: null,
            sync: true,
            timeout: 4000
        };

    })(jQuery);
    jQuery(document).ready(function ($) {
        $('ul.slider').cycle({
            prev: $('.slider-prev'),
            next: $('.slider-next')
        });
    });
</script>
<style>
    .im-brand-central-slider .slider-nav {
        width: 685px;
        background: #000;
        color: #fff;
        font-size: 11px;
        padding: 3px 0px;
        text-transform: uppercase;
        font-family: Verdana, Arial, Helvetica, sans-serif;
        text-align: right;
    }
    .im-brand-central-slider .slider-nav a {
        cursor: pointer;
		color: #f0f0f0 !important;
    }
	.im-brand-central-slider .slider-nav a:hover{
		color: #ffffff !important;
    }
    .im-brand-central-slider .slider-nav a.slider-prev {
        border-right: 1px solid #888;
        padding-right: 10px;
        margin-right: 5px;
    }
    .im-brand-central-slider .slider-nav a.slider-next {
    	margin-right: 10px;
    }
    .im-brand-central-slider,
    .im-brand-central-slider ul.slider {
        position: relative;
    }
    .im-brand-central-slider,
    .im-brand-central-slider ul.slider,
    .im-brand-central-slider ul.slider li {
        width: 685px;
        height: 200px;
        padding: 0;
        margin: 0;
    }
    .im-brand-central-slider {
    	height: 219px;
    	margin-bottom: 20px;
    }
    .im-brand-central-slider ul.slider,
    .im-brand-central-slider ul.slider li{
        list-style-type: none;
    }
    .im-brand-central-slider ul.slider li{
        display: block;
        position: absolute;
        top: 0;
        left: 0;
    }
    .im-brand-central-slider ul.slider li img{
        width: 100%;
        height: auto;
    }
</style>

Verified this rotating banner code works in all of the versions of SharePoint, including SharePoint 2007, SharePoint 2010 and in SharePoint 2013.

Rotating banner in SharePoint 2013:
jquery rotating banner sharepoint


Rotating banner in SharePoint 2007:
jquery rotator sharepoint
My other jQuery Banner rotating implementations:


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


Sunday, June 1, 2014

SharePoint Site Detailed Storage Report using PowerShell

Requirement: Generate a detailed report on all list and library sizes of a SharePoint site.

Solution: PowerShell script! Here is the PowerShell script to generate detailed storage information with listing all list and library sizes.
#Get Size of all lists and libraries in a SharePoint Site
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Get-SPWeb cmdlet for MOSS 2007
Function global:Get-SPWeb($url)
{
  $site= New-Object Microsoft.SharePoint.SPSite($url)
        if($site -ne $null)
            {
               $web=$site.OpenWeb()        
            }
    return $web
}
 
#Function to Get Storage Metrics for a list/library 
Function GetStorageMetrics($Folder)
{   
    $TotalSize=0 
    #Get the size of each file in the folder
    foreach ($File in $Folder.Files)
    {
        #Get File Size
        $FileSize = $File.TotalLength
        
        $VersionSize=0
        #Get the Versions Size
        foreach ($FileVersion in $File.Versions)
        {
            $VersionSize += $FileVersion.Size
        }
        $TotalSize += $VersionSize+ $FileSize  
    }
    

      #Get Files in Sub Folders
        foreach ($SubFolder in $Folder.SubFolders)
        {   
         if($SubFolder.Name -ne "Forms") #Leave "Forms" Folder which has List default Aspx Pages.
             {
     #Call the function recursively for the subfolders
                $TotalSize += GetStorageMetrics($SubFolder)          
             }
        } 
        
        #Return the object
     return $TotalSize
}

#Set Site URL  variable
$WebURL = "http://sharepoint.crescent.com"
#Get the Web
$Web = Get-SPWeb $WebURL

#Array to hold Storage data for all lists and libraries
$StorageDataCollection = @() 

foreach($List in $Web.Lists)
 {
    #Leave the Hidden Lists and exclude certain Libraries
    if($List.Hidden -eq $false)
    {
        #Write-host "Procesing list:" $list.title
        #Call the function to get library's Size relatedMetrics
        $LibrarySize = GetStorageMetrics($List.RootFolder)
        
        #Create an object to hold storage data
        $StorageDataResult = New-Object PSObject
        
        #Add other details of the list 
        $StorageDataResult | Add-Member -type NoteProperty -name "List/Library Name" -value $List.Title
        $StorageDataResult | Add-Member -type NoteProperty -name "Item/File Count" -value $List.ItemCount
        $StorageDataResult | Add-Member -type NoteProperty -name "Created by" -value $List.Author
        $StorageDataResult | Add-Member -type NoteProperty -name "Created on" -value $List.Created
        $StorageDataResult | Add-Member -type NoteProperty -name "Last Modified" -value $List.LastItemModifiedDate
        $StorageDataResult | Add-Member -type NoteProperty -name "URL" -value $List.DefaultViewUrl
        
        #Add storage related Data
        $StorageDataResult | Add-Member -type NoteProperty -name "Total Size (KB)" -value ([Math]::Round(($LibrarySize/1KB),2))

        #Add object to an array
        $StorageDataCollection += $StorageDataResult        
    }
 }

#Get Recycle bin size
$RecyclebinSize=0
foreach($RecycleBinItem in $Web.RecycleBin)
        {
           $RecyclebinSize += $RecycleBinItem.Size
        }
#Get the Total size of the library
$TotalSiteSize = ($StorageDataCollection | Measure-Object 'Total Size (KB)' -Sum | Select -expand Sum)


Write-host "Total Lists/Libraries Size in MB: "([Math]::Round(($TotalSiteSize/1KB),2))
write-host "Recycle bin Size in MB:" ([Math]::Round(($RecyclebinSize/1MB),2))
#Add recycle bin size
Write-host "Total site Size in MB: "([Math]::Round(($TotalSiteSize/1KB)+($RecyclebinSize/1MB),2))
write-host "Total Number of Lists/Libraries in the Site:" $Web.Lists.Count 

#export the detailed storage Info the CSV file
$StorageDataCollection | sort-object "Total Size" -descending | Export-csv "SiteStroageRpt.csv" -notypeinformation
Write-host "Site Storage Report has been generated!"
      
$Web.dispose()
This script generates the report in CSV format. Here is a snapshot after exporting to Excel:
It also gives the total size of lists, libraries and size of the recycle bin.

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