Prerequisites for migrating SharePoint 2007 site to SharePoint 2010:1. Check whether the packages (wsp features etc) in source server are same as in the target server (if not please install).
2. Check the web.config modifications made in the MOSS 2007 site (source site), if any do the same modifications on MOSS 2010 site (target site) accordingly.
Migration process:
The only process to migrate the site from SharePoint 2007 to SharePoint 2010 is the migrating contentDB of source site to target site.
Steps to follow for migrating ContentDB:
1. Take the backup of the source site contentDB and restore the same on target server.
2. Create the web application in SharePoint 2010, and then create the site collection (it doesn’t matter what site template you are using for creating site collection).
3. Once finished creating the SharePoint 2010 site, go to central administration --> Manage content databases --> select the web application you created for migration --> click on database --> check in the remove content database --> click ok
4.Add the restored database in the target site by using stsadm.exe in command prompt
Stsadm.exe –o addcontentdb –url “enter your url” –databasename “enter your db name”
5.Restart iis.
My Solutions in SharePoint,ASP.NET, Sql server, Visual Studio, C#, Java script, CSS and more.
Tuesday, December 8, 2009
Monday, December 7, 2009
Hide the infopath form banner "Powered by infopath form services"
After the publishing the infopath form in the SharePoint Site. You will find a banner called "Powered by infopath form services" in at the bottom of infopath form.
Blow command explains how to customize the form banner-
Remove banner:
stsadm.exe -o setformserviceproperty -pn allowbranding -pv false
Add banner:
stsadm.exe -o setformserviceproperty -pn allowbranding -pv true
To check the weather the banner is set or not
stsadm.exe -o getformserviceproperty -pn allowbranding
hope this helps you very much.
Blow command explains how to customize the form banner-
Remove banner:
stsadm.exe -o setformserviceproperty -pn allowbranding -pv false
Add banner:
stsadm.exe -o setformserviceproperty -pn allowbranding -pv true
To check the weather the banner is set or not
stsadm.exe -o getformserviceproperty -pn allowbranding
hope this helps you very much.
Friday, November 20, 2009
CSS,Javascript not working in IE8 browser but working fine in IE7
The CSS and JAVSCRIPT which I implemented in Ramp Group (http://rampgroup.com) Website is working fine in IE7,Firefox,Google Chrome and safari.
However when it comes to IE8 it’s not working fine.
After a long research I found that we need to add a small meta tag in head tag
<meta http-equiv="X-UA-Compatible" content="IE=7"/ >
It tells to IE8 to build a website exactly same as IE7.
However when it comes to IE8 it’s not working fine.
After a long research I found that we need to add a small meta tag in head tag
<meta http-equiv="X-UA-Compatible" content="IE=7"/ >
It tells to IE8 to build a website exactly same as IE7.
Tuesday, November 17, 2009
Windows PowerShell Execution Policy for 'AuthorizationManager check failed'
ERROR:
Command execution stopped because the shell variable "ErrorActionPreference" is set to Stop: Windows PowerShell snap-in "Quest.ActiveRoles.ADManagement" is loaded with the following warnings: Error loading the extended type data file: Quest.ActiveRoles.ADManagement, C:\Program Files\Quest Software\Management Shell for AD\Quest.ActiveRoles.ADManagement.Types.ps1xml : File skipped because of validation exception: "AuthorizationManager check failed.". There were errors in loading the format data file: Quest.ActiveRoles.ADManagement, C:\Program Files\Quest Software\Management Shell for AD\Quest.ActiveRoles.ADManagement.Format.ps1xml : File skipped because of validation exception: "AuthorizationManager check failed.".
At line:80 char:35 + if(-not $testsnapin){add-pssnapin <<<< -Name $SnapInName}
'AuthorizationManager check failed' means that initially we doesn't have permission to execute the Powershell Script to all users in the Sharepoint site because by default the execution policy is set to restricted.
To resolve the issue we need to got to 'ActiveRoles Management shell for Active Directory' command prompt and set execution policy to 'remotesigned' as shown below

C:\program files\Quest software\Management Shell for AD>set-Executionpolicy
cmdlet set-executionpolicy at command pipeline position 1
Supply values for the following parameters:
ExecutionPolicy: remotesigned
[PS] C:\Program Files\Quest Software\Management Shell for AD>
It will allows you to execute the script for all users who have permission to add the user in ADAM and for the SharePoint site.
WINDOWS POWERSHELL EXECUTION POLICIES:
The Windows PowerShell execution policies are as follows:
"Restricted" is the default policy.
Restricted
- Default execution policy.
- Permits individual commands, but will not run
scripts.
- Prevents running of all script files, including
formatting and configuration files (.ps1xml), module
script files (.psm1), and Windows PowerShell
profiles (.ps1).
AllSigned
- Scripts can run.
- Requires that all scripts and configuration files
be signed by a trusted publisher, including scripts
that you write on the local computer.
- Prompts you before running scripts from publishers
that you have not yet classified as trusted or
untrusted.
- Risks running unsigned scripts from sources other
than the Internet and signed, but malicious, scripts.
RemoteSigned
- Scripts can run.
- Requires a digital signature from a trusted
publisher on scripts and configuration files that
are downloaded from the Internet (including
e-mail and instant messaging programs).
- Does not require digital signatures on scripts that you have run
and that you have written on the local computer (not
downloaded from the Internet).
- Risks running signed, but malicious, scripts.
Unrestricted
- Unsigned scripts can run. (This risks running malicious
scripts.)
- Warns the user before running srcipts and configuration
files that are downloaded from the Internet.
Bypass
- Nothing is blocked and there are no warnings or
prompts.
- This execution policy is designed for configurations
in which a Windows PowerShell script is built in to a
a larger application or for configurations in which
Windows PowerShell is the foundation for a program
that has its own security model.
Undefined
- There is no execution policy set in the current scope.
- If the execution policy in all scopes is Undefined, the
effective execution policy is Restricted, which is the
default execution policy.
Command execution stopped because the shell variable "ErrorActionPreference" is set to Stop: Windows PowerShell snap-in "Quest.ActiveRoles.ADManagement" is loaded with the following warnings: Error loading the extended type data file: Quest.ActiveRoles.ADManagement, C:\Program Files\Quest Software\Management Shell for AD\Quest.ActiveRoles.ADManagement.Types.ps1xml : File skipped because of validation exception: "AuthorizationManager check failed.". There were errors in loading the format data file: Quest.ActiveRoles.ADManagement, C:\Program Files\Quest Software\Management Shell for AD\Quest.ActiveRoles.ADManagement.Format.ps1xml : File skipped because of validation exception: "AuthorizationManager check failed.".
At line:80 char:35 + if(-not $testsnapin){add-pssnapin <<<< -Name $SnapInName}
'AuthorizationManager check failed' means that initially we doesn't have permission to execute the Powershell Script to all users in the Sharepoint site because by default the execution policy is set to restricted.
To resolve the issue we need to got to 'ActiveRoles Management shell for Active Directory' command prompt and set execution policy to 'remotesigned' as shown below

C:\program files\Quest software\Management Shell for AD>set-Executionpolicy
cmdlet set-executionpolicy at command pipeline position 1
Supply values for the following parameters:
ExecutionPolicy: remotesigned
[PS] C:\Program Files\Quest Software\Management Shell for AD>
It will allows you to execute the script for all users who have permission to add the user in ADAM and for the SharePoint site.
WINDOWS POWERSHELL EXECUTION POLICIES:
The Windows PowerShell execution policies are as follows:
"Restricted" is the default policy.
Restricted
- Default execution policy.
- Permits individual commands, but will not run
scripts.
- Prevents running of all script files, including
formatting and configuration files (.ps1xml), module
script files (.psm1), and Windows PowerShell
profiles (.ps1).
AllSigned
- Scripts can run.
- Requires that all scripts and configuration files
be signed by a trusted publisher, including scripts
that you write on the local computer.
- Prompts you before running scripts from publishers
that you have not yet classified as trusted or
untrusted.
- Risks running unsigned scripts from sources other
than the Internet and signed, but malicious, scripts.
RemoteSigned
- Scripts can run.
- Requires a digital signature from a trusted
publisher on scripts and configuration files that
are downloaded from the Internet (including
e-mail and instant messaging programs).
- Does not require digital signatures on scripts that you have run
and that you have written on the local computer (not
downloaded from the Internet).
- Risks running signed, but malicious, scripts.
Unrestricted
- Unsigned scripts can run. (This risks running malicious
scripts.)
- Warns the user before running srcipts and configuration
files that are downloaded from the Internet.
Bypass
- Nothing is blocked and there are no warnings or
prompts.
- This execution policy is designed for configurations
in which a Windows PowerShell script is built in to a
a larger application or for configurations in which
Windows PowerShell is the foundation for a program
that has its own security model.
Undefined
- There is no execution policy set in the current scope.
- If the execution policy in all scopes is Undefined, the
effective execution policy is Restricted, which is the
default execution policy.
Monday, November 16, 2009
Create Users in ADAM using Windows PowerShell
In the previous post, I defined the Windows PowerShell .Now, I will show you how it is useful in real time.
In my scenario, I have an requirement to create an UI (User interface) for adding the User in ADAM. We can do it using c#, Vb.Net also. but if we use C# we need to install visual studio which will take of about 3GB from you hard disk.So, I prefer to use Powershell scripting language instead of using c# because it occupies less space than VS from the hard disk.
I searched in Google, I found a wonderful web part(iLoveSharePoint) to run the Power Shell script in SharePoint. Click here to download. I also found the CmdLets to add users in ADAM called Quest AD Management Shell.
AD Management Shell:
It is a PowerShell snap-In that allows you to add the users, groups in the ADAM (Active directory Application Mode) and AD in very handy. The cmdlets are from Quest Software.
How to use Quest Software:
iLoveSharePoint:
########## Initialize ############
## declare global variables and functions
$tbUserName = New-Object System.Web.UI.WebControls.TextBox
$button = New-Object System.Web.UI.WebControls.Button
$lbUserName = New-Object System.Web.UI.WebControls.Label
$lbuserPrincipalName = New-Object System.Web.UI.WebControls.Label
$tbuserPrincipalName = New-Object System.Web.UI.WebControls.TextBox
$lbMessage = New-Object System.Web.UI.WebControls.Label
$ErrorMessage = New-Object System.Net.WebException
############# Load ##############
## first time the OnLoad fires before CreateChildControls
function OnLoad
{
$lbUserName.Text = 'UserName'
$lbuserPrincipalName.Text = 'Email'
$lbMessage.Text = ''
# Check if GET Request (first request).
if($isPostBack -eq $false)
{
#$label.Text = 'GET request.'
}
}
####### 3. Create Controls ########
# create child controls
function CreateChildControls($controls)
{
$controls.Add($tbUserName)
$button.Text = 'Add User'
Subscribe-Event $button 'Click' 'OnButtonClicked'
$controls.Add($button)
$controls.Add($lbUserName)
$controls.Add($lbuserPrincipalName)
$controls.Add($tbuserPrincipalName)
$controls.Add($lbMessage)
}
function connect-ADAM{
# This allows the use of a windows account for ADAM athentication without granting the application pool account rights to ADAM
$passwd = convertto-securestring "provide your admin password here" -asplaintext -force
$adamcred = new-object -typename System.Management.Automation.PSCredential -argumentlist "provide your admin user",$passwd
#ADAM connection, please provide the server followed by port number of your ADAM
connect-QADService -Service localhost:65000 -Credential $adamcred
}
function New-User
{
param([String]$newlogonid,[String]$userPrincipalName)
# provide the password here for the new user
$newpassword = "password123$"
$adamconnection = connect-ADAM
New-QADUser -Name $newlogonid -UserPassword $newpassword -ParentContainer $usercontainer -userPrincipalName $userPrincipalName -Connection $adamconnection
}
####### Events ########
# handle control events
# subscribe to an event with "Subscribe-Event($control, 'eventName','callback function name')"
function OnButtonClicked($sender, $args)
{
$SnapInName = "Quest.ActiveRoles.ADManagement"
$testsnapin = $null
$testsnapin = get-pssnapin | where { $_.Name -eq $SnapInName}
if(-not $testsnapin){add-pssnapin -Name $SnapInName}
$usercontainer = 'CN=Users,CN=ADAMPartition,DC=rajkamal,DC=COM'
$userPrincipalName = $tbuserPrincipalName.Text
$newUserName = $tbUserName.Text
$connection = connect-ADAM
if(($newUserName -eq '') -or ($userPrincipal -eq ''))
{
$lbMessage.Text = 'Please provide the details'
}
else
{
$results = get-QADUser -SearchRoot $usercontainer -name $newUserName -connection $connection
$principalName= get-QADUser -SearchRoot $usercontainer -ObjectAttributes @{userPrincipalName = $userPrincipalName} -connection $connection
if(!$results)
{
if(!$principalName)
{
New-User -newlogonid $newUserName -userPrincipalName $userPrincipalName
$lbMessage.Text = 'User successfully added'
}
else
{
$lbMessage.Text = 'UserPrincipalName already exists'
}
}
else
{
$lbMessage.Text = 'User already exists'
}
}
$tbUserName.text = [string]::Empty
$tbuserPrincipalName.text = [string]::Empty
}
## render html
function Render($writer)
{
$writer.Write("<table><tr><td colspan='2'><b>Add Users in ADAM</b></td></tr><tr><td>")
$lbUserName.RenderControl($writer)
$writer.Write(":</td><td>")
$tbUserName.RenderControl($writer)
$writer.Write("</td></tr><tr><td>")
$lbuserPrincipalName.RenderControl($writer)
$writer.Write(":</td><td>")
$tbuserPrincipalName.RenderControl($writer)
$writer.Write("</td></tr><tr><td colspan='2' align='center'>")
$button.RenderControl($writer)
$writer.Write("</td><tr><td colspan='2' style='color:red;font-weight:bold;text-align:center'>")
$lbMessage.RenderControl($Writer)
$writer.Write("</td></tr></table>")
}
In my scenario, I have an requirement to create an UI (User interface) for adding the User in ADAM. We can do it using c#, Vb.Net also. but if we use C# we need to install visual studio which will take of about 3GB from you hard disk.So, I prefer to use Powershell scripting language instead of using c# because it occupies less space than VS from the hard disk.
I searched in Google, I found a wonderful web part(iLoveSharePoint) to run the Power Shell script in SharePoint. Click here to download. I also found the CmdLets to add users in ADAM called Quest AD Management Shell.
AD Management Shell:
It is a PowerShell snap-In that allows you to add the users, groups in the ADAM (Active directory Application Mode) and AD in very handy. The cmdlets are from Quest Software.
How to use Quest Software:
- Download the file according to your system configuration.
- Download the provided Guide which gives you a brief description.
- Install the downloaded file.
- Download the iLoveSharePoint web part from the codeplex.
- Please follow the instruction provided in the downloaded file.
- copy the script provided below to add the user in ADAM.
########## Initialize ############
## declare global variables and functions
$tbUserName = New-Object System.Web.UI.WebControls.TextBox
$button = New-Object System.Web.UI.WebControls.Button
$lbUserName = New-Object System.Web.UI.WebControls.Label
$lbuserPrincipalName = New-Object System.Web.UI.WebControls.Label
$tbuserPrincipalName = New-Object System.Web.UI.WebControls.TextBox
$lbMessage = New-Object System.Web.UI.WebControls.Label
$ErrorMessage = New-Object System.Net.WebException
############# Load ##############
## first time the OnLoad fires before CreateChildControls
function OnLoad
{
$lbUserName.Text = 'UserName'
$lbuserPrincipalName.Text = 'Email'
$lbMessage.Text = ''
# Check if GET Request (first request).
if($isPostBack -eq $false)
{
#$label.Text = 'GET request.'
}
}
####### 3. Create Controls ########
# create child controls
function CreateChildControls($controls)
{
$controls.Add($tbUserName)
$button.Text = 'Add User'
Subscribe-Event $button 'Click' 'OnButtonClicked'
$controls.Add($button)
$controls.Add($lbUserName)
$controls.Add($lbuserPrincipalName)
$controls.Add($tbuserPrincipalName)
$controls.Add($lbMessage)
}
function connect-ADAM{
# This allows the use of a windows account for ADAM athentication without granting the application pool account rights to ADAM
$passwd = convertto-securestring "provide your admin password here" -asplaintext -force
$adamcred = new-object -typename System.Management.Automation.PSCredential -argumentlist "provide your admin user",$passwd
#ADAM connection, please provide the server followed by port number of your ADAM
connect-QADService -Service localhost:65000 -Credential $adamcred
}
function New-User
{
param([String]$newlogonid,[String]$userPrincipalName)
# provide the password here for the new user
$newpassword = "password123$"
$adamconnection = connect-ADAM
New-QADUser -Name $newlogonid -UserPassword $newpassword -ParentContainer $usercontainer -userPrincipalName $userPrincipalName -Connection $adamconnection
}
####### Events ########
# handle control events
# subscribe to an event with "Subscribe-Event($control, 'eventName','callback function name')"
function OnButtonClicked($sender, $args)
{
$SnapInName = "Quest.ActiveRoles.ADManagement"
$testsnapin = $null
$testsnapin = get-pssnapin | where { $_.Name -eq $SnapInName}
if(-not $testsnapin){add-pssnapin -Name $SnapInName}
$usercontainer = 'CN=Users,CN=ADAMPartition,DC=rajkamal,DC=COM'
$userPrincipalName = $tbuserPrincipalName.Text
$newUserName = $tbUserName.Text
$connection = connect-ADAM
if(($newUserName -eq '') -or ($userPrincipal -eq ''))
{
$lbMessage.Text = 'Please provide the details'
}
else
{
$results = get-QADUser -SearchRoot $usercontainer -name $newUserName -connection $connection
$principalName= get-QADUser -SearchRoot $usercontainer -ObjectAttributes @{userPrincipalName = $userPrincipalName} -connection $connection
if(!$results)
{
if(!$principalName)
{
New-User -newlogonid $newUserName -userPrincipalName $userPrincipalName
$lbMessage.Text = 'User successfully added'
}
else
{
$lbMessage.Text = 'UserPrincipalName already exists'
}
}
else
{
$lbMessage.Text = 'User already exists'
}
}
$tbUserName.text = [string]::Empty
$tbuserPrincipalName.text = [string]::Empty
}
## render html
function Render($writer)
{
$writer.Write("<table><tr><td colspan='2'><b>Add Users in ADAM</b></td></tr><tr><td>")
$lbUserName.RenderControl($writer)
$writer.Write(":</td><td>")
$tbUserName.RenderControl($writer)
$writer.Write("</td></tr><tr><td>")
$lbuserPrincipalName.RenderControl($writer)
$writer.Write(":</td><td>")
$tbuserPrincipalName.RenderControl($writer)
$writer.Write("</td></tr><tr><td colspan='2' align='center'>")
$button.RenderControl($writer)
$writer.Write("</td><tr><td colspan='2' style='color:red;font-weight:bold;text-align:center'>")
$lbMessage.RenderControl($Writer)
$writer.Write("</td></tr></table>")
}
Windows PowerShell
Windows PowerShell (WPS) is a .NET-based environment for console-based system i.e, it is an object-oriented programming language and interactive command line shell for Microsoft windows.
WPS is similar to Perl which includes more than 130 standard commands called cmdlets (Command-lets).
Powershell is available as a free download for windows XP, windows server 2003 and vista, where as in Windows server 2008 and Windows 7 includes additional option to install this feature.
Advantages of PowerShell:
It is not preferable for larger tasks.
WPS is similar to Perl which includes more than 130 standard commands called cmdlets (Command-lets).
Powershell is available as a free download for windows XP, windows server 2003 and vista, where as in Windows server 2008 and Windows 7 includes additional option to install this feature.
Advantages of PowerShell:
- It's not a compiled language.
- It has a plug-in ecosystem with lots of 'libraries' for doing various domain specific things like copying files, playing with AD, Exchange.
- It's the right tool for a different, slightly overlapping set of jobs.
- It's a lot more powerful and consistent than CMD.EXE and other things evolved from command shells that needed to fit into 8K RAM.
- For smaller task, it is more preferable.
It is not preferable for larger tasks.
Thursday, October 29, 2009
SharePoint coding tips and tricks
The elementary thing that SharePoint developers should consider is, the correct way of using SharePoint object mode, and how to apply general programming techniques (such as caching and threading) to the SharePoint platform specifically. Generally developers who write custom code for developing the SharePoint Application will counter some issues like performance, scalability. This article makes you easier to find and fix your problem areas in the code and can avoid known pitfalls using SharePoint object model.
These are some of the areas that developers should concern
· Disposing of SharePoint Objects.
· Performance concerns related to folders, lists and SPQuery objects.
· Exact way of using SharePoint data and objects efficiently.
· Using web controls and timer jobs.
Disposable SharePoint objects:
1. Developers who are working on the windows SharePoint service object model for developing new SharePoint applications have objects that inherited from the IDisposable interface.
2. This article serves as a guide to the proper procedures for handling and disposing of SharePoint objects that implement IDisposable interface.
3. Some of the primary objects are SPWeb class and SPSite class, created as managed objects.
4. Microsoft .NET requires objects that implement the IDisposable interface to properly cleanup the unmanaged resources by explicitly calling the Dispose () or Close () method when you are finished using them.
5. Internally, SPSite and SPSite both hold references to an "internal class Microsoft.SharePoint.Library.SPRequest" which holds on to unmanaged COM resources.
Coding techniques to ensure Object Dispose:
These are some of the techniques to ensure the Object Dispose
· Dispose Method
· Using Clause
· Try, catch and finally blocks
Dispose vs. Close Method:
Both of them are same, but the dispose method internally calls the close method. For the best practice, use Dispose method instead of using close method because SPWeb and SPSite Objects implements IDisposable interface, and standard .NET framework garbage collector call the dispose method to free any resources associated with the object from memory.
Using Clause
1. Using clause will automatically dispose the SharePoint Objects. You can greatly simplify the code with using clause.
2. Common Language Run Time will convert the using clauses to try, catch and finally block, and any objects that implement the IDisposable interface are disposed for you.
Note: SPContext objects are managed from SharePoint framework and need not be disposing separately.
Try, catch and finally block:
Whenever you need to handle the exceptions we obviously use Try, catch and finally blocks. Please don’t leave the catch block empty. Declare Dispose method in the finally block, and make a note that for best practice check null before disposing the SharePoint objects as shown below.
SPSite spSite = null;
SPWeb spWeb = null;
try
{
spSite = new SPSite ("http://server");
spWeb = spSite.OpenWeb ();
}
catch (Exception e)
{
}
finally
{
if(spSite != null)
{
spSite.Dispose();
}
if (spWeb != null)
{
spWeb.Dispose ();
}
}
Respose.Redirect, with try, catch and finally block and using statements:
1. The finally block executes after calls to Response.Redirect in the try block. Response.Redirect ultimately generates a ThreadAbortException.
2. When this exception is raised, the runtime executes all finally blocks before ending the thread.
3. However, because the finally block can do an unbounded computation or cancel the ThreadAbortException, there is no guarantee that the thread will end.
4. Therefore, before any redirection or transfer of processing can occur, you must dispose of the objects. If your code must redirect, implement it in a way similar to the following code example.
SPSite spSite = null;
SPWeb spWeb = null;
try
{
spSite = new SPSite ("http://server");
spWeb = spSite.OpenWeb ();
if (spSite != null)
{
spSite.Dispose();
}
if (spWeb != null)
{
spWeb.Dispose ();
}
Response.Redirect ("www.google.com");
}
catch (Exception ex)
{
}
finally
{
if (spSite != null)
{
spSite.Dispose();
}
if (spWeb != null)
{
spWeb.Dispose ();
}
}
Performance concerns related to folders, lists and SPQuery objects:
1. To retrieve the all items from list, please don’t use SPList.Items.
2. SPList.Items will retrieve all the items from folders, subfolders including all fields in the list.
3. To eradicate this Problem use SPList.GetItems(Query).
4. Getting Items by identifier, Please use SPList.GetItemById(int) instead of using SPList.Items.GetItemById().
5. To retrieve the list from the site, It is always preferable to get the list based GUID or url i.e. SPWeb.Lists[GUID] or SPWeb.GetList(strUrl) instead of using List Name i.e., SPWeb.Lists[strListName].
Conclusion:
· Please check whether your code dispose the SharePoint objects.
· Please check that your code cache objects properly.
· Please check that your code use thread synchronization when necessary.
If you consider these issues when you write your code, your SharePoint system will run more efficiently and your users will have a much better experience. You can also help to prevent unexpected failures and errors in your system.
These are some of the areas that developers should concern
· Disposing of SharePoint Objects.
· Performance concerns related to folders, lists and SPQuery objects.
· Exact way of using SharePoint data and objects efficiently.
· Using web controls and timer jobs.
Disposable SharePoint objects:
1. Developers who are working on the windows SharePoint service object model for developing new SharePoint applications have objects that inherited from the IDisposable interface.
2. This article serves as a guide to the proper procedures for handling and disposing of SharePoint objects that implement IDisposable interface.
3. Some of the primary objects are SPWeb class and SPSite class, created as managed objects.
4. Microsoft .NET requires objects that implement the IDisposable interface to properly cleanup the unmanaged resources by explicitly calling the Dispose () or Close () method when you are finished using them.
5. Internally, SPSite and SPSite both hold references to an "internal class Microsoft.SharePoint.Library.SPRequest" which holds on to unmanaged COM resources.
Coding techniques to ensure Object Dispose:
These are some of the techniques to ensure the Object Dispose
· Dispose Method
· Using Clause
· Try, catch and finally blocks
Dispose vs. Close Method:
Both of them are same, but the dispose method internally calls the close method. For the best practice, use Dispose method instead of using close method because SPWeb and SPSite Objects implements IDisposable interface, and standard .NET framework garbage collector call the dispose method to free any resources associated with the object from memory.
Using Clause
1. Using clause will automatically dispose the SharePoint Objects. You can greatly simplify the code with using clause.
2. Common Language Run Time will convert the using clauses to try, catch and finally block, and any objects that implement the IDisposable interface are disposed for you.
Note: SPContext objects are managed from SharePoint framework and need not be disposing separately.
Try, catch and finally block:
Whenever you need to handle the exceptions we obviously use Try, catch and finally blocks. Please don’t leave the catch block empty. Declare Dispose method in the finally block, and make a note that for best practice check null before disposing the SharePoint objects as shown below.
SPSite spSite = null;
SPWeb spWeb = null;
try
{
spSite = new SPSite ("http://server");
spWeb = spSite.OpenWeb ();
}
catch (Exception e)
{
}
finally
{
if(spSite != null)
{
spSite.Dispose();
}
if (spWeb != null)
{
spWeb.Dispose ();
}
}
Respose.Redirect, with try, catch and finally block and using statements:
1. The finally block executes after calls to Response.Redirect in the try block. Response.Redirect ultimately generates a ThreadAbortException.
2. When this exception is raised, the runtime executes all finally blocks before ending the thread.
3. However, because the finally block can do an unbounded computation or cancel the ThreadAbortException, there is no guarantee that the thread will end.
4. Therefore, before any redirection or transfer of processing can occur, you must dispose of the objects. If your code must redirect, implement it in a way similar to the following code example.
SPSite spSite = null;
SPWeb spWeb = null;
try
{
spSite = new SPSite ("http://server");
spWeb = spSite.OpenWeb ();
if (spSite != null)
{
spSite.Dispose();
}
if (spWeb != null)
{
spWeb.Dispose ();
}
Response.Redirect ("www.google.com");
}
catch (Exception ex)
{
}
finally
{
if (spSite != null)
{
spSite.Dispose();
}
if (spWeb != null)
{
spWeb.Dispose ();
}
}
Performance concerns related to folders, lists and SPQuery objects:
1. To retrieve the all items from list, please don’t use SPList.Items.
2. SPList.Items will retrieve all the items from folders, subfolders including all fields in the list.
3. To eradicate this Problem use SPList.GetItems(Query).
4. Getting Items by identifier, Please use SPList.GetItemById(int) instead of using SPList.Items.GetItemById().
5. To retrieve the list from the site, It is always preferable to get the list based GUID or url i.e. SPWeb.Lists[GUID] or SPWeb.GetList(strUrl) instead of using List Name i.e., SPWeb.Lists[strListName].
Conclusion:
· Please check whether your code dispose the SharePoint objects.
· Please check that your code cache objects properly.
· Please check that your code use thread synchronization when necessary.
If you consider these issues when you write your code, your SharePoint system will run more efficiently and your users will have a much better experience. You can also help to prevent unexpected failures and errors in your system.
Subscribe to:
Posts (Atom)