Code for Creating New Documents based on a content type and template
This method “CreateDocument” will create a new document in a SharePoint document library using a content type. It will copy the document template associated with the content type into the new document:
// Creates document in given list (root folder).
// Returns true if the file was created, false if it already
// exists or throws exception for other failure
protected bool CreateDocument( string sFilename,
string sContentType, string sList)
{
try
{
SPSite site = SPContext.Current.Site;
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[sList];
// this always uses root folder
SPFolder folder = web.Folders[sList];
SPFileCollection fcol = folder.Files;
// find the template url and open
string sTemplate =
list.ContentTypes[sContentType].DocumentTemplateUrl;
SPFile spf = web.GetFile(sTemplate);
byte[] binFile = spf.OpenBinary();
// Url for file to be created
string destFile = fcol.Folder.Url + “/” + sFilename;
// create the document and get SPFile/SPItem for
// new document
SPFile addedFile = fcol.Add(destFile, binFile, false);
SPItem newItem = addedFile.Item;
newItem["ContentType"] = sContentType;
newItem.Update();
addedFile.Update();
return true;
}
}
catch (SPException spEx)
{
// file already exists?
if (spEx.ErrorCode == -2130575257)
return false;
else
throw spEx;
}
}
This code:
- Gets a SPSite for the current site collection, and opens an SPWeb for the site.
- Gets a SPList for the given list, and then an SPFolder for the root folder in this list. This code always creates the document in the root folder, but the code can easily be changed to place the document in any folder in the document library.
- Gets a SPFileCollection for the documents in the folder.
- “DocumentTemplateUrl” is used to return the Url of document template associated with the given content type.
- Get an SPFile for the document template in spf and open it for binary access using OpenBinary
- Add a new document to the folder through the SPFileCollection referenced by fcol.
- Get an SPItem for the new document and set the “ContentType” column to ensure it uses the correct content type (it will default to the first content type in the document library).
- Update the item and the added file.
- The catch section checks for an -2130575257 error, which indicates the file already exists.
Logging in as a different user
When using default.master in SharePoint users have the “Sign in as Different User” menu option on the “Welcome” menu to login as a different user. This is useful when testing security etc.
This menu is often removed when customizing sites – clients we find often do not want these options displayed. So how can you add a link to allow this facility for testing?
The “Sign in as Different User” navigates to the /_layouts/AccessDenied.aspx page, which displays thus:

You’ll notice the link “Sign in as a different user”. From the browser status bar you can find the target of this link:

So, it turns out to login as another user you simply need to navigate to:
/_layouts/AccessDenied.aspx?loginasanotheruser=true
The standard browser username/password dialog box will be displayed without the “Access Denied” page being displayed to the user.
Changing Order / Hiding Columns in New / Edit Forms
The default order of columns in New/Edit forms for lists and document libraries is typically the order they are added. In many cases you may want to change this order, or to remove columns from these forms.
Changing the column order is easy but the method depends on whether you have selected “Allow management of content types” for the list. See below if you have this option selected, otherwise you can:
- Open the list and select Settings + List Settings
- Select the “Column ordering” link under “Columns”.
- Use the “Change Field Order” form to change the order of columns.

You can only hide columns if “Allow management of content types” is selected! So, to hide, for example, the “Title” column you can:
- Open the list and select Settings + List Settings
- Select Advanced settings
- Click Yes for “Allow management of content types” and then click OK.
- From the list of content types, select the content type the column appears in, e.g. “Item”.
- From the list of columns for the selected content type, select the column (e.g. Title).
- Select Hidden and click OK.

Even if you have a single content type, selecting the “Allow management of content types” option does no harm, so this should work in all cases.
Note that when displaying the content type there is a “Column Order” link under the list of columns which can be used to change the order of columns.
In this example, “Title” is a required field, but you can still hide it. The form will allow the item to be created or updated even though a value has not been supplied.
Increasing size of Rich Text Editing Control
When using the rich text column type in SharePoint lists the edit control has a fixed width of 384 pixels. This is often too small for easy editing.
The width of the control used to edit rich text is set through the ms-rtelong style. You can change the width using the style in the core.css or other style sheets you may be using. However, this will change the width for every use of this control in your site.
If you need to change the width for a single form, open the form in SharePoint Designer and add a style defining ms-rtelong at the top of the content place holder in which the form is displayed with new dimensions, e.g.
<asp:Content ContentPlaceHolderId=”PlaceHolderMain” runat=”server”>
<style type=”text/css”>
.ms-rtelong {
width:700px;
height:600px;
}
</style>
You can do this for standard uncustomised forms (e.g. NewForm.aspx) or for pages you create using the custom list form web part.
Trimming WebPart Output with SPSecurityTrimmedControl
The SPSecurityTrimmedControl can be used in your SharePoint pages and web parts to conditionally display content based on permissions assigned to a user.
Here’s an example of using the control in a web part. The control is declared in Microsoft.SharePoint (in microsoft.sharepoint.dll). First, create an instance:
SPSecurityTrimmedControl stcEditItem= new SPSecurityTrimmedControl();
stcEditItem.Permissions = SPBasePermissions.EditListItems;
Next, specify the output to display only if the current user has the given permissions. In this case
- Define a literal server control, add some content
- Add the literal to the SPSecurityTrimmedControl
- Add the SPSecurityTrimmedControl to the controls collection for the web part:
Literal litEditItem = new Literal();
litEditItem.Text = “My Content”;
stcEditItem.Controls.Add(litEditItem);
this.Controls.Add(stcEditItem);
Finally, you can explicitly render the SPSecurityTrimmedControl control in the web part’s “Render” method:
stcEditItem.RenderControl(writer);
The content “My Content” will only be displayed in the web part if the user has the “EditListItems” permission.
Also, you can programmatically test for permissions on various SharePoint objects, such as SPListItem, using the AllRolesForCurrentUser method:
SPListItem li;
…
if (!li.AllRolesForCurrentUser.Contains(web.RoleDefinitions["Approve"]))
{
…
This web post from Richard Harbridge shows how to use the SPSecurityTrimmedControl in an ASPX page.
When an SPListItem won’t Update or Change
Here’s a problem that recently bit me. This code executes a query that returns a single SPListItem and then attempts to change the approved status through the SPListItemCollection:
SPListItemCollection lic = list.GetItems(query);
lic[0].ModerationInformation.Status = SPModerationStatusType.Approved;
lic[0].Update();
Strangely enough, before calling the change to “Status” (second line) the status was “Pending” and *after* the call the status was still “Pending”!
However, assigning to a SPListItem and updating through this object changes the approved status as expected:
SPListItemCollection lic = list.GetItems(query);
SPListItem li = lic[0];
li.ModerationInformation.Status = SPModerationStatusType.Approved;
li.Update();
It seems the SharePoint object model cannot handle repeated calls through the item collection to the same list item object – perhaps it creates a new temporary object each time?
SharePoint Designer: Clearing the Web Part Cache
When developing web parts (say in Visual Studio 2008) and using these web parts in SharePoint Designer 2007 you may find that your property definitions are not refreshed in SharePoint Designer. For example, if you add a new property in VS 2008 and recompile, the new property may not not displayed in SharePoint Designer.
To remedy this you can clear SharePoint Designers web site cache:
- Navigate to {my profile}\AppData\Local\Microsoft\WebsiteCache
- Locate the folder that relates to the web site you’re using (server name + port)
- Delete the contents of the folder.
You will find a file in this folder called {webpartproject}.Proxy.DLL. If you cannot delete this file because it’s in use just rename it.
Now, when you next run SharePoint Designer you’ll get a refreshed list of web parts.
Hiding the Search Box When Printing
Ever noticed that the search box is shown on a SharePoint page when printed while other parts of the page are hidden?

The Search box can be hidden, along with other parts of a form you don’t want printed by using styles. This can be done using Microsoft Office SharePoint Designer:
- Open the master page in SharePoint Designer
- Add the following style either to a CSS file included in the master page or as a style within the master page itself:
@media print{
.HideForPrinting
{
display:none;
}
}
- Locate the delegate control used to display the search box and add the code shown in italics:
<asp:ContentPlaceHolder id=”PlaceHolderSearchArea” runat=”server”>
<span class=”HideForPrinting”>
<SharePoint:DelegateControl runat=”server” ControlId=”SmallSearchInputBox”/>
</span>
</asp:ContentPlaceHolder>
This defines a span that uses the style HideForPriting, the content of which will be hidden when the page is printed.
BDC Catalog Designer from Microsoft!
Microsoft have released a tool for developing BDC XML catalogs (applications) and it’s part of the Microsoft Office SharePoint Server August SDK.
Find out more here: http://blogs.msdn.com/sharepoint/archive/2007/08/22/announcing-the-microsoft-business-data-catalog-definition-editor-for-microsoft-office-sharepoint-server-2007.aspx
Update: 28 November 2008 – Warning; this tool cannot do SQL Server 2005/2008 schemas. This means you cannot use it against AdventureWorks, but you can use it against AdventureWorksDW. This is an astounding limitation given Microsoft’s push towards using schemas. If you try, you’ll get the error “Could not process Table ‘….’. Make sure you have SELECT Rights on the Table/VIEW”. This needs to be fixed.