Tuesday, March 8, 2011

Powershell script - Get all Site Columns for a SharePoint 2010 site collection

Here is the powershell script to retrieve all Site Columns for a SharePoint 2010 site collection and output the details into a .csv file

Copy the code below and change the Site Collection URL and Output Path as per your requirement, save the following as .ps1 file:

Add-PsSnapin Microsoft.SharePoint.PowerShell
## SharePoint DLL
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
# Description
#   Output all available Column Field GUIDs to AllColumnFields.csv

# Settings Start
set-variable -option constant -name url     -value "http://localhost"       # Site collection
set-variable -option constant -name out     -value "C:AllColumnFields.csv"           # Output file
# Settings End

$site   =    new-object Microsoft.SharePoint.SPSite($url)
$web    = $site.rootweb.Fields
echo "Generating File..."
ForEach ($id in $web)
{
'"' + $id.Title + `
'","' + $id.Id + `
'","' + $id.InternalName + `
'","' + $id.StaticName + `
'","' + $id.MaxLength + `
'","' + $id.Description + `
'","' + $id.Group + `
'","' + $id.TypeShortDescription + `
'"' | Out-File $out -append
}
$site.Dispose()
echo "Finished"
echo "File created at : " $out

Remove-PsSnapin Microsoft.SharePoint.PowerShell

It outputs all the Site Column details available in the Site Columns Gallery to a .csv file.

Sunday, February 27, 2011

SPSecurity.RunWithElevatedPrivileges Access denied issue

SPRunWithElevatedPrivileges allows you to run your SharePoint code in the context of the App Pool identity account.

Look at the piece of code below:


function void ListItemUpdate(Guid guId)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;

SPList list = web.Lists["Products"];
SPListItem item = list.Items[guId];
item["ProductName"] = "Apple iPhone 4";
item["ProductPrice"] = "199";

item.Update();

web.AllowUnsafeUpdates = false;
});
}

So when a user with Read access tries to execute the above code, he gets an Access denied error, even after the code having the RunWithElevated Privileges set.

Lets examine, look at the code highlighted in yellow above. SPContext.Current.Site and SPContext.Current.Web runs the List Item update code in the context of the currently logged in user and not in the context of the App Pool identity.

Solution: Solution is to re-open new SPSite and SPWeb objects within the SPSecurity delegate block, lets rewrite the above code and fix the issue:

function void ListItemUpdate(Guid guId)
{
Guid siteId = SPContext.Current.Site.Id;
Guid webId = SPContext.Current.Web.Id;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteId))
{
using (SPWeb web = site.OpenWeb(webId))
{
web.AllowUnsafeUpdates = true;

SPList list = web.Lists["Products"];
SPListItem item = list.Items[guId];
item["ProductName"] = "Apple iPhone 4";
item["ProductPrice"] = "199";
item.Update();

web.AllowUnsafeUpdates = false;
}
}
});
}

Running this piece of code fixes the Access denied issue and allows the code to run under AppPool identity.

Wednesday, February 23, 2011

SharePoint 2010 - Do not dispose guidance for SharePoint objects

Do not dispose the following listed SharePoint objects explicitly: (Applicable for both SharePoint 2010 and SharePoint 2007)

•SPContext.Current.Site

•SPContext.Current.Web

•SPContext.Site

•SPContext.Web

•SPControl.GetContextWeb(..)

•SPControl.GetContextSite(..)

•SPFeatureReceiverProperties.Feature.Parent

•SPItemEventProperties.ListItem.Web

•SPList.BreakRoleInheritance()

◦Do not call list.ParentWeb.Dispose()

•SPListEventProperties.Web

•SPListEventProperties.List.Web

•SPSite.RootWeb

◦Problems may occur when SPContext.Web has equality to the SPContext.Web.. make sure you dispose of SPSite and it will cleanup sub webs automatically

•SPSite.LockIssue

•SPSite.Owner

•SPSite.SecondaryContact

•SPWeb.ParentWeb

•SPWebEventProperties.Web

Few important changes for Dispose rules in SharePoint 2010:
•Microsoft.SharePoint.WebControls.SiteAdminsitrationSelector.CurrentItem
When used with WSS 3.0 you must call Dispose(), with SharePoint Foundation 2010 you don’t.

•Event Receivers and properties.OpenWeb()
WSS 3.0: When you call properties.OpenWeb() the returned SPWeb will need to call Dispose()
SharePoint Foundation 2010: Use the newly introduced SPItemEventProperties.Web property instead of SPItemEventProperties.OpenWeb() for better performance and to avoid the need to call Dispose().

Reference: http://blogs.msdn.com/b/rogerla/archive/2009/11/30/sharepoint-2007-2010-do-not-dispose-guidance-spdisposecheck.aspx

Sunday, February 20, 2011

XML and XSL transformation control for SharePoint 2010

The ASP.NET control control for SharePoint enable users to provide their XML and XSL files, spitting out the resulting HTML based on the two control parameters.

1. Copy and paste the code below in your custom SharePoint page:
<div>
<asp:Xml runat="server" id="xmlEmployee" DocumentSource="/_layouts/SPFix/Employee.xml" TransformSource="/_layouts/SPFix/Employee.xsl">
</asp:Xml>
</div>

2. The Document Source behavior takes an XML file path and Transform Source takes an XSL file path
3. You can see the resulting HTML spitted out to the browser when you hit your SharePoint custom page.

Quickest way is to try using SharePoint Designer as per the best practice you need to create a Visual Studio solution for your SharePoint pages.

Saturday, February 19, 2011

StringWriter and HTMLTextWriter objects to emit HTML in custom Webparts

You could also use StringWriter and HTMLTextWriter objects to write HTML to the Web part rather than the LiteralControl.

For example, the following code creates a simple StringBuilder object, then writes that through using the
StringWriter and HtmlTextWriter objects:

StringBuilder sb = new StringBuilder();
sb.AppendLine(“<table border=’0’><tr><td>”);
StringWriter spStrWriter = new StringWriter(sb);
HtmlTextWriter htmlTxtWriter = new HtmlTextWriter(spStrWriter);
Page.RenderControl(htmlTxtWriter);

Admittedly, the use of multiple literalcontrol objects is not the most elegant of ways to emit HTML
when rendering Web parts. See an example usage of Literal Controls mentioned below:

StringBuilder sb = new StringBuilder();
sb.AppendLine(“<table border=’0’><tr><td>”);
this.Controls.Add(new LiteralControl(sb.ToString()));

ASP.NET provides a rich framework for writing HTML out to the page, which includes the HtmlTextWriter class. We can leverage this while writing custom webparts