About Me

Having 12 years experience in Microsoft technologies.Since more than 7 years working in SharePoint technologies. Expert in providing consultation for SharePoint projects. Hands on with development and administration.

Thursday 12 December 2013

Programatically remove a tab from all the SharePoint 2010 sites

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Navigation;
namespace GlobalNavigationRemove
{
class Program
{
static void Main(string[] args)
{
string webAppUrl = string.Empty;
int iCounter = 0;
int iNbrOfSites = 0;
if (args.Length > 0)
{
Console.WriteLine(string.Format("Web Application: {0}", args[0]));
webAppUrl = args[0].ToString();
if (args.Length > 1)
{
Console.WriteLine(string.Format("Test Iteration: {0}", args[1]));
iNbrOfSites = int.Parse(args[1].ToString());
}
}
SPWebApplication webApp = SPWebApplication.Lookup(new Uri(webAppUrl));
Console.WriteLine(string.Format("Total Site collections detected: {0}" , webApp.Sites.Count.ToString()));
Console.WriteLine(string.Format("*************************************Starting the removal ********************************"));

foreach (SPSite siteCollection in webApp.Sites)
{
if (iCounter > iNbrOfSites && iNbrOfSites != 0)
{
return;
}
PublishingWeb myPublishingWeb = PublishingWeb.GetPublishingWeb(siteCollection.OpenWeb());
Console.WriteLine(string.Format("Now Processing : {0}", myPublishingWeb.Title));
SPNavigationNodeCollection publishingNavigationNodes = myPublishingWeb.Navigation.GlobalNavigationNodes;
try
{
SPWeb web = siteCollection.OpenWeb();
SPNavigationNodeCollection webNavigationNodes = web.Navigation.TopNavigationBar;
foreach (SPNavigationNode node in webNavigationNodes)
{
if (node.Title.Trim().ToLower() == "home")
{
node.Delete();
}
}
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Exception Occurred while processing site {0} \n\n", ex.ToString()));
}
iCounter++;
}
}
}

Activate a feature in all the SharePoint site collections-PowerShell

$webAppUrl = "Web Application URL"
 

$webapp = Get-SPWebApplication $webAppUrl  | Get-SPSite -Limit All | Get-SPSite -limit 

all | ForEach-Object {Enable-SPFeature -Identity 'Feature guid'  -Url $_.Url}

Creating a SharePoint Site Collection with unique host headers-Powershell

New-SPSite http://url  -OwnerAlias DOMAIN\USERID - HostHeaderWebApplication http://SERVERNAME

SharePoint 2010 Server Topology - Server Roles and Services on Server

Many of you may think this is basic info, so don't over think what I'm saying here. I'm sitting in Shane Young's Admin class and realizing that the services on server and the server roles match up isn't very clean. Let me share some thoughts on server roles and the services. The first thing to realize is that more things in the UI contain configuration than you might think.
All Services on Server (WFE/Query/Calc/Index) - Choose "Single Server or Web Server for small server farms" start the things it tells you to, and click on the things that look like links to configure them. In "Office SharePoint Server Search" you'll be checking both boxes since you're query and index are on this box. (Hint: Don't forget about SSP for further configration) You might not be using the document conversions, most likely you're not. These are optional.
 
WFE/Query/Calc - Choose "Web Server for medium server farms" and run the recommended services, and be sure to click on everything that is a link as in Office SharePoint Server Search. Be sure to check "Use this server for serving search queries." Doc Conversions is optional. (This role is very common in medium or high availability farms)
 
WFE - Windows SharePoint Services Web Application. Both of the document conversion services are "nice to have" if you use them in your SharePoint Standard or Enterprise publishing scenarios where you are converting your word to HTML for publishing. It's not common that these are used. During install you can choose WFE only, understand what you're doing, but this will limit the services you'll see in services on server.
 
Forms Rendering - I'm listing this here, since a lot of people think of this as a server role. This is automatically always on the WFE. You can't offload this.
 
Excel Calculation - Choose Excel Calculation, this service should be running. Configuration for this is in the SSP. It's a MOSS Enterprise configuration.
 
Query - In Services on Server choose "Search Indexing" then actually click, yes click on the text (under Service) "Office SharePoint Server Search." You'll see two options. Make sure "Use this server for indexing content" is unchecked and "Use this server for serving search queries" is checked.
By the way, if you ever decide to build a query server, I would nearly always recommend considering an SSP farm. Why? Cause if you're offloading query because you have that many search requests, then you'll need at least 2 Query servers and you'll have already offloaded your index, so that's 3 servers that could easily be load balanced and create a decent SSP farm.
 
Index - In Services on Server choose "Search Indexing" then actually click, yes click on the text (under Service) "Office SharePoint Server Search." You'll see two options. Make sure "Use this server for indexing content" is checked and "Use this server for serving search queries" is unchecked. You do need to add the Windows SharePoint Services search you don't need to go with the "every 5 minutes" by default, daily is sufficient. You will later create your rules for your content sources anyway. The service accounts will be configured when you configure indexing.
 
This is the first server I offload for performance. I do recommend making the index role also a WFE, so I wouldn't usually recommend this just be an index server unless it's in the SSP farm (a farm by itself with no content).
 
Index/WFE and WFE out of load balancing (Target) - here's where you could pick custom then start the Windows SharePoint Services Web Application and the Office SharePoint Server Search and be sure to check only "Use this server for indexing content." I did a whole post on this in a post called "Use a dedicated web front end for Indexing." A target server might be a WFE that's out of load balancing that only the index servers in your environment know about (host file entries on the index servers). The other configurational you'll see is index servers that have WFE components that are configured to index themselves and hence have the WFE services (Windows SharePoint Services Web Application) and also not in load balancing. There is an option to configure the "use a dedicated WFE on the bottom of the Index server configuration page (Office SharePoint Server Search Configuration page), don't use this if you have multiple IPs or multiple NICs. It is very possible it will choose the wrong IP and better that you configure this in hosts where you manage what is in.
 
WFE/index/Query and WFE/Query - If you ever have index and query on the same server and plan on doing another server with Query.... or are thinking about doing something like this please refer to my post about the Index/Query Gotcha. The Index server will NOT propegate if the Query components are enabled on the farm. In a sense this means if both boxes are checked (Query (search requests) and Index (crawling)) in "Office SharePoint Server Search" it will NOT propegate the index to any other query server. It assumes there is not another query box no matter how many you have.
Want to force changes after a role change of a server where you need to push down the web apps to a new box?

stsadm.exe -o execadmsvcjobs

SharePoint Master Pages vs. Themes: Which Do You Choose?

Over many years, I have heard a lot of confusion and question about if a site should use a master page or a theme. In this post I am going to go through some basic pros and cons and information to help you make a better decision as to how to brand your SharePoint 2007 site.
If you need more info about either master pages or themes, check out these posts:
About Themes (note this refers to WSS v2, but is still applicable for WSS v3)
The first thing I recommend is to assess your design needs. Set aside terminology and SharePoint features and don't worry about how to execute the site branding, but identify what you need to change from the default SharePoint look and feel. Here are some questions to ask:
  1. Do you need to change the colors used? For example change the blue palette to another color palette? Often you need to incorporate corporate colors, product color schemes or colors that better reflect a mood/emotion or industry you are in.
  2. Do you need to change the images used? Do you need to incorporate certain illustrations, photos or logos? Most everyone at a minimum wants to include their own logo. Do you need to style a header that matches your branding?
  3. What navigation do you want to use? Do you want to use both the tabbed horizontal menu and the left navigation, or maybe only one or neither? If using the menu(s), do you need to alter how they look? If so, how drastically?
  4. Do you need to move core components of the page layout around? Don't think about content, but about the page wrapper (header, nav, footer). Are there other components you need to incorporate, move or remove?
  5. Do you plan on having a collection of sites and each site needs to have its own color palette? Some sites have sub sites (such as HR, travel and accounting in an Intranet) color coded.
After making some decisions about your design, you can start looking at what master pages and themes can provide and you can start to decide which is best for the site.
Master pages provide total control of the site layout. Themes on the other hand re-skin the layout by changing colors and images used in the design. Since a theme is just a CSS file and images, the layout of the page such as the location of the navigation, can't be altered.
If you are using the SharePoint site intact with the navigation that comes with the site, and you just need to update the colors and images and add a header to the site, a theme can handle all of that for you. To see what a theme can change, apply one of the many out of the box themes that SharePoint provides. Click here for instructions on how to apply a theme.
But testing out a SharePoint theme doesn't give you a full idea of what you can do with a theme. The page icon next to the title can be removed, so can the title. Header images can be added in. People often think themes can only update the colors used since that is what the out of the box themes do. But a lot more can be accomplished. Click here and here to see two examples of custom themes for WSS v2 sites.
A benefit to themes is that when you apply a theme, it also affects the pages in the _layouts directory, whereas master pages do not.
If a theme doesn't seem to fit the bill for the design you need to implement in the SharePoint site, then look to master pages. With master pages you can implement your own navigation systems, custom code and design elements, move elements around on the page or hide SharePoint components you don't want to use. It is a more complete solution for totaling changing the way SharePoint looks.
In some situations, both master pages and themes can be used. If you use a master page to style the site, using a custom theme can style the _layouts pages to coordinate with the look of the site. If you need to apply different color palettes for one design for sub sites, in MOSS use can use the alternate CSS setting, but that isn't available for WSS sites. You can create a custom master page for the WSS sites to use, then create and apply different themes to change the color palette of sub sites.
One drawback to a theme is that you have to apply it at the site level for each site. Master pages on the other hand can be inherited (for MOSS sites) through sub sites. But this is buggy and more than likely you have to apply the custom master page on each site anyways. Another possible drawback to themes is they have to be installed on the server thus making them available to all sites in the farm. But there is a way around this if you don't have access to your server or if you don't want a theme available to all sites.
You can apply a theme (pick one that most closely resembles what you want to ultimately do with your site design) to your site, and then a copy of the theme CSS file will be created for the site. You can edit this file in SharePoint Designer (thus creating a copy of it in the content database and customizing the file) and create your customizations for your site.
So, to run down some key points:
 
Master Pages
  • Can totally change the look of a site.
  • Can hide SharePoint components that you don't want to use.
  • Will allow you to alter the layout of the page, in addition to changing the colors and images used in the site.
  • Will not affect _layouts pages. You will need to use a workaround.
Themes
  • Can re-skin the layout of a site to use different images and colors.
  • Can only hide SharePoint components that can be controlled through hiding it in the CSS (display: none set on a class/ID).
  • Affects _layouts pages.
  • Can be used as an alternate CSS file application method, similar to alternate CSS setting in MOSS sites.
  • Are installed on the web server unless you customize the file.

Binding Drop-Down with Sharepoint List data



if (!Page.IsPostBack)
{
    DataSet ds = new DataSet();
    SPSite mySite = SPContext.Current.Site;
    SPWeb myWeb = mySite.OpenWeb();
    SPList list = myWeb.Lists["ListName"];
    DataTable DTable_List = list.Items.GetDataTable();
    DTable_List.TableName = "Table1";
    ds.Tables.Add(DTable_List);

    DropDownList.DataSource = ds.Tables["Table1"];
    DropDownList.DataTextField = "FieldName";
    DropDownList.DataValueField = "FieldName";
    DropDownList.DataBind();
    DropDownList.SelectedIndex = 0;
}

Using External Javascript, CSS or Image File in a SharePoint WebParts

Button btn;
Image img;
string imgPath;
// Referring External Javascript
ClientScriptManager cs = Page.ClientScript;
// Include the required javascript file.
if (!cs.IsClientScriptIncludeRegistered("jsfile"))
cs.RegisterClientScriptInclude(this.GetType(), "jsfile", "/_wpresources/javascript/jsscript.js");
 
btn= new Button();
btn.Text = "Click here";
// specify function name here
btn.OnClientClick = "ButtonClick()";
this.Controls.Add(btn);
// Refering External CSS
Microsoft.SharePoint.WebControls.CssLink cssLink = new Microsoft.SharePoint.WebControls.CssLink();
cssLink.DefaultUrl = "/_wpresources/styles/styles.css";
this.Page.Header.Controls.Add(cssLink);
// Using External Image
imgPath = "/_wpresources/images/Imglogo.jpg";
img.ImageUrl = imgPath;
img.ID = "image1";
 
this.Controls.Add(img);

PowerShell script to deploy Multiple Farm solutions from same directory - single click - SharePoint 2010, 2013

Here is the Power Shell script to deploy multiple SharePoint farm solutions from same directory

Note: 
1.  Make sure that, your solutions should be in the same directory from where you are running the script.

2. Replace $webapp with your respective web application url @ line #3

3. Pass necessary parameters to Install-SPSolution command.

4. Save file with .ps1 as extension. Example: psDeploy.ps1

5. Create .bat file and call the .ps1 file in it. Example : Deploy.bat

cd /d %~dp0
powershell -noexit -file    ".\
psDeploy.ps1" "%CD%"
pause


6. Once done, directly run the .bat file. No need of launching PowerShell console to execute.
-------------------------------------------------------------------------------------------------------------------------
Add-PsSnapin Microsoft.SharePoint.PowerShell

$logfile=$CurrentDir + "\log.log"

$webapp = "http://sp2010"

Start-Transcript $logfile

#Do not modify anything in the script from here onwards
function Get-ScriptDirectory
{
 $Invocation = (Get-Variable MyInvocation -Scope 1).Value
 Split-Path $Invocation.MyCommand.Path
}

function Deploy-Solution{
param(
[string]$physicalPath,
[string]$name)


$SolutionName = $name
$SolutionPath = Join-Path ($physicalPath) $SolutionName
echo "Extracting information from $physicalPath"

#Admin service
$AdminServiceName = "SPAdminV4"
$IsAdminServiceWasRunning = $true;

if ($(Get-Service $AdminServiceName).Status -eq "Stopped")
{
    $IsAdminServiceWasRunning = $false;
    Start-Service $AdminServiceName
   Write-Host 'SERVICE WAS STOPPED, SO IT IS NOW STARTED'
}

#Uninstall
Write-Host 'UNINSTALLING SOLUTION:' $SolutionName '...'

$Solution = Get-SPSolution | ? {($_.Name -eq $SolutionName) -and ($_.Deployed -eq $true)}

if ($Solution -ne $null)
{
    if($Solution.ContainsWebApplicationResource)
    {
        #Uninstall-SPSolution $SolutionName -AllWebApplications -Confirm:$false

    Uninstall-SPSolution $SolutionName -WebApplication $webapp -Confirm:$false
    }
    else
    {
        Uninstall-SPSolution $SolutionName -Confirm:$false
    }
}

while ($Solution.JobExists)
{
    Start-Sleep 2
}

Write-Host 'THE SOLUTION:' $SolutionName 'HAS BEEN UNINSTALLED SUCCESSFULLY.'

Write-Host 'REMOVING SOLUTION ...'

if ($(Get-SPSolution | ? {$_.Name -eq $SolutionName}).Deployed -eq $false)
{
    Remove-SPSolution $SolutionName -Confirm:$false

Write-Host 'THE SOLUTION:' $SolutionName 'HAS BEEN REMOVED SUCCESSFULLY.'
}

Write-Host 'ADDING SOLUTION: '$SolutionName '...'

Add-SPSolution $SolutionPath  | Out-Null

Write-Host 'THE SOLUTION:' $SolutionName 'HAS BEEN ADDED SUCCESSFULLY.'

Write-Host 'DEPLOYING SOLUTION:' $SolutionName '...'

$Solution = Get-SPSolution | ? {($_.Name -eq $SolutionName) -and ($_.Deployed -eq $false)}

#use '-force' paramater to install all commands in this if statement

if(($Solution -ne $null) -and ($Solution.ContainsWebApplicationResource))
{
#Install-SPSolution $SolutionName –AllwebApplications -GACDeployment -Force -Confirm:$false

Install-SPSolution $SolutionName –WebApplication $webapp -GACDeployment -Force -Confirm:$false
}
else
{
Install-SPSolution $SolutionName -GACDeployment -Force -Confirm:$false
}

while ($Solution.Deployed -eq $false)
{
    Start-Sleep 2
}

Write-Host 'SOLUTION HAS BEEN DEPLOYED SUCCESSFULLY.'

if (-not $IsAdminServiceWasRunning)
{
    Stop-Service $AdminServiceName
}
}

#Get Current Physical Path
$currentPhysicalPath = Get-ScriptDirectory

#Iterate through all .wsp files in the current Physical Path to deploy solution
get-childitem $currentPhysicalPath -include *.wsp -recurse | foreach ($_) {Deploy-Solution $currentPhysicalPath $_.name}

Stop-Transcript

#Remove SharePoint Snapin
Remove-PsSnapin Microsoft.SharePoint.PowerShell

Echo Finish
----------------------------------------------------------------------------------------------------------------------

Wednesday 11 December 2013

How to implement Impersonation in Sharepoint 2010

Sometime during SharePoint application development when you need your code to perform certain functions that the current user does not have the necessary permissions to perform. The SharePoint SPSecurity class provides a method (RunWithElevatedPrivileges) that allows you to run a subset of code in the context of an account with higher privileges than the current user. 

You need to wrap the RunWithElevatedPrivileges method around your code. And if you are working with Web forms, you may also need to set the AllowUnsafeUpdates property of SPWeb object to true to temporarily turn off security validation within your code. If you use this technique, it is imperative that you set the AllowUnsafeUpdates property back to false to avoid any potential security risks.

Code example :

SPSite objSite = SPContext.Current.Site;
SPWeb objWeb = mySite.OpenWeb();
//Using RunWithElevatedPrivileges
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Get references to the site collection and site for the current context.
   // using statement makes sures these references are disposed properly.
   using (SPSite siteCollection = new objSite(mySite.ID))
   {
      using (SPWeb web = siteCollection.OpenWeb(objWeb.ID))
      {
         web.AllowUnsafeUpdates = true;
         try
         {
            //Your code
         }
         web.AllowUnsafeUpdates = false;
         siteCollection = null;
         web = null;
      }
   }
});

Backup and Restore the SharePoint 2010 site using PowerShell command

Backup
Backup-SPSite –identity "<url of site of which you want to take backup>" –path "<path where your backup file resides\name of your backup file.bak>"

e.g.: Backup-SPSite –identity "http://domainName:2711" –path "C:\BackupFolder\mybackup.bak"
 

Restore
Restore-SPSite –identity "<url of that site on wich you want to restore>" –path "<path of your backup file\name of your backup file.bak>" -force

e.g.: Restore-SPSite –identity "http://domainName:2711" –path "C:\BackupFolder\mybackup.bak" –force

SharePoint 2010: BCS External List Throttling

Sometime it may happen that your external list worked well on development server but when you deploy it to production server, Surprisingly it do not work.

Most common cause is that BCS has throttled an external system call for taking too long, or trying to transfer too much data. If you have logging turned on for Business Connectivity Services in Central Administration -> Monitoring -> Diagnostic Logging you will see errors similar to this in your Sharepoint Logs:
Error while executing web part: Microsoft.BusinessData.Runtime.ExceededLimitException: Database Connector has throttled the response. The response from database contains more than ’2000′ rows. The maximum number of rows that can be read through Database Connector is ’2000′.
Defaul throttling is set to 2000 rows. By default this feature is enabled in SharePoint 2010 to deny access of Service attacks that could adversely affect SharePoint or external system health by performing huge transactions. But the better part is that you can change the limit or disable them as per your business needs. Remember that this is a farm level setting.

You can change these throttle limits using the following powershell script:
$bdcProxy = Get-SPServiceApplicationProxy | where {$_.GetType().FullName -eq ('Microsoft.SharePoint.BusinessData.SharedService.' + 'BdcServiceApplicationProxy')}
To view a rule, run the following command:
$dbRule = Get-SPBusinessDataCatalogThrottleConfig -Scope Database -ThrottleType Items -ServiceApplicationProxy $bdcProxy
Use $dbRule to view throttling rules. This handle will maintain only the fetched copy. If you do anything to change a throttling rule, you should re-fetch it from BCS using the above script to be sure that you have the latest copy.

To view the $dbRule by itself just type $dbrule, you’ll see something like this:
Scope: Database

ThrottleType: Items 

Enforced: True 

Default : 2000 

Max: 1000000
You can change it using a command like any of these examples:
Set-SPBusinessDataCatalogThrottleConfig -Identity $dbRule -Maximum 1000000 -Default 3000

#Default and Maximum must be provided together. This increases the limit for external lists to 3000.

#This disables a throttling rule. 

Set-SPBusinessDataCatalogThrottleConfig -Identity $dbRule -Enforced:$false



#This enables a throttling rule. 

Set-SPBusinessDataCatalogThrottleConfig -Identity $dbRule -Enforced:$true

Now if you type $dbRule, you won’t see the changes reflected. You should re-fetch the rule using Get-SPBusinessDataCatalogThrottleConfig and try again to view $dbrule but it may take a few minutes for them to be reflected in external lists and other runtime scenarios.

Create custom site definition in SharePoint Server 2010

Introduction

 In this article I am explaining the steps to create a SharePoint 2010 custom site definition by copying an existing site definition. The steps involved in this are not much different then the last versions on SharePoint.You only need to change in two schema files. First file is the copy of WEBTEMP xml file and second is copy of onet.xml file.

Background

For copying existing site definition, you first need to know the location of the existing site definitions. Site definitions are located in the following folder in the SharePoint server 14 hive:
C:\Program Files\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\SiteTemplates 
Each site definition has its own sub directory under this folder. The sub directory contains the .aspx pages, images, and one onet.xml file. onet.xml file contains the configuration and modules informations of that particular site definition. WEBTEMP xml file contains the registration information of the Site Definition with SharePoint. Actual name of WEBTEMP file would be like WEBTEMP_<Name of Site Definition>.xml. WEBTEMP file are located in the following location:
C:\Program Files\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\1033\XML

Steps Involved

1. Clone an existing site definition folder located in the C:\Program Files\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\SiteTemplates\ directory.

2. Give it any name that contains no spaces. For example, to create a custom site definition that derives from the blank site definition for Windows SharePoint Services, copy the \sts folder.
3. Rename the copy of sts folder to MyTestSite.

4. Make a copy of the WebTemp.xml file that is located in C:\Program Files\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\1033\XML.

5. Rename the copied file to WEBTEMP_MyTestSite.xml

6. Open WEBTEMP_MyTestSite.xml using Vishal Studio 2010 or some other editor to do the customization. It contains a collection of Template elements and Configuration subelements. The Configuration element defines the title, description, URL for the image displayed in the user interface, and a display category that specifies the tab on which to display the template in the Template Selection section of the New SharePoint Site page. "My Custom Site Definition" in this example.
<?xml version="1.0" encoding="utf-8"?>

   <Templates xmlns:ows="Microsoft SharePoint">

      <Template Name="MyTestSite" ID="10005">

         <Configuration ID="0" Title="MyTestSite Template" Hidden="FALSE" ImageUrl="" 
            Description="This template is used for initializing a new site." 
            DisplayCategory="My Custom Site Definition"></Configuration>

      </Template>

   </Templates>

Note: In each Template element defined in the WebTemp file, the Name attribute must contain the same name that is assigned to the new folder. In this example it is "MyTestSite". Also, to avoid conflict with IDs already used in Windows SharePoint Services, use unique values greater than 10,000 for the ID attribute. I am using ID = 10005 in this example.
7. Reset the IIS. (Open command prompt. Type iisreset and press enter key.)

8. Open Central Administration and goto Application Management -> Create Site Collection. A new tab will appear.

9. Select the site template you created. Enter Title and Url and click on Create button.

Your new sharepoint site is created.