Posts Tagged ‘How-To’
SP 2010: Developing for performance Part 5 – Disposal patterns and tools
January 31st, 2011 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
SharePoint 2010 developing for performance article series:
In this series of articles I will briefly introduce you to some key concepts when it comes to developing for performance in our SharePoint 2010 applications.
Related articles in this article series
Part 1 – SP 2010: Developing for performance Part 1 – Developer Dashboard
Part 2 – SP 2010: Developing for performance Part 2 – SPMonitoredScope
Part 3 – SP 2010: Developing for performance Part 3 – Caching in SharePoint 2010
Part 4 – SP 2010: Developing for performance Part 4 – Logging
Part 5 – SP 2010: Developing for performance Part 5 – Disposal patterns and tools
Part 6 – SP 2010: Developing for performance Part 6 – CSS Sprites
Part 7 – SP 2010: Developing for performance Part 7 – Crunching those scripts
Part 8 – SP 2010: Developing for performance Part 8 – Control that ViewState
Part 5 (this article):
In SharePoint 2010 (and 2007 for that matter) there’s a few objects in the API’s that requires your special attention in order to behave properly. If you do not consider the disposal patterns and rules set forth, your application may very well suffer performance issues. In this article I will briefly touch upon the subject of disposing your SharePoint objects and foremost enlighten how important it is to dispose the objects!
What does Disposing mean and why is it important?
When I deliver training, there’s always the question about why disposing is important. In SharePoint there’s valid grounds for saying it’s important to dispose, more than just saying "It’s best practice". If you don’t properly dispose some of your objects in SharePoint you’ll quickly face performance issues since those objects don’t get caught and disposed by the Garbage Collector in a timely fashion as most other objects do in .NET.
What is a "dispose pattern"?
The Dispose Pattern is the approach used to properly dispose and clean up the resources you’re using in your projects when programming in .NET (or other runtimes). Normally there’s an automatic garbage collector doing the cleanup for you – but in certain scenarios (like the ones described later in this article), you’ll need to manually dispose your objects.
IDisposable
In Microsoft .NET when an object inherits from the IDisposable interface it means that the Garbage Collector will call the .Dispose() method of that object when it’s no longer used. The Dispose() method in turn calls the Close() method which generally means you should call the .Dispose() method instead of the .Close() method to make sure the objects are properly disposed. Keep reading to see why this is so important!
Why is manual disposal really, really important in SharePoint?
Some of the objects you’re working with heavily in the SharePoint object model (for example the SPWeb and SPSite) are mostly using unmanaged code – and since the managed part of the code is quite small it doesn’t leave a large memory footprint and hence the Garbage Collector don’t necessarily dispose of that object – which means that it’ll be occupying server resources for a longer time if you don’t manually dispose of those objects.
What happens if I forget to dispose?
There’s several things that you may notice in your applications if you’ve implemented a solution that are not properly disposing their objects.
- Memory consumption.
- The consumption of your server memory may peak and the worker process (w3wp.exe) may consume a lot more memory than it would normally have to consume.
- Application Pool recycling.
- If the worker process consumes too much memory, it’ll recycle the application pool.
- If you’ve got an underperforming application causing overwhelming memory consumption the Application Pool will recycle more often.
- Performance issues!
- Slow response times
- Timeouts
- Unexpected errors
- Headache
- User headache
- Support headache
- Admin headache
- Developer headache (ultimately)
In other words: Make sure you’re properly disposing your objects at all times!
Sandboxed Solutions and Resource Usage – Think about dispose patterns!
If you’re developing applications for the Sandbox in SharePoint 2010 (User Code Solutions / Sandboxed Solutions) you may be aware of the resource point system that will limit your application’s usage of resources on the server. This is a great way to keep the admins calm and developers keen on producing quality code.
A thing to note is that if you don’t correctly dispose your objects they will consume more server resources which in turn would lead to the resource points increasing. If the resource usage reaches the limits set forth by SharePoint for a sandboxed solution – it’ll deactivate it.
In other words: Make sure you’re properly disposing your objects at all times!
Let’s visualize the performance problem!
Okay, so now that I’ve got your attention – let’s do a quick performance test to see how the process handles the memory if we create the same application with and without disposal patterns in SharePoint.
I created a simple application that will work heavily with the SPSite and SPWeb objects on one of my servers. After hooking up a performance counter and monitoring the memory consumption repeatedly during a few hours of repeated execution it was easy to line down a conclusion which you can see in the chart below.
Performance summary
The following chart displays the same application with and without implementing the dispose patterns in a SharePoint 2010 execution environment.
You can see by the results of the two applications above that when we’re properly disposing our objects there’s a notable difference in the performance in our application – and hence the overall server resource usage.
In other words: Make sure you’re properly disposing your objects at all times!
How to: Implement dispose patterns in your SharePoint code
At this point we know it’s very important to dispose our objects in SharePoint – let’s take a look at how we can do that properly and what tooling and guidelines we can use to help us in this important quest!
Approach 1 – Manually calling Dispose()
The absolutely most general and simple approach to dispose your objects is to simply call the .Dispose() method of your objects:
SPSite site = new SPSite ("http://zimmergren/");
// Do stuff
site.Dispose();
Approach 2 – Encapsulating the statement in a using() block
A more common approach is to encapsulate the code in a using-block where the object will be automatically disposed when we’re reaching the end of our block.
using (SPSite site = new SPSite ("http://zimmergren"));
{
// Do stuff
}
Approach 3 – Utilize a try/finally block
Whenever you’re expecting to catch an exception or somehow might stumble onto exceptions and need to handle them – a better approach for disposing is to create a try-finally block and dispose the object in the finally-block.
Sample 1: Without exception handling
SPSite site = null ;
try
{
site = new SPSite ("http://zimmergren");
// do stuff
}
finally
{
if (site!=null ) site.Dispose();
}
Sample 2: With exception handling
SPSite site = null ;
try
{
site = new SPSite ("http://zimmergren");
// do stuff
}
catch (Exception ex)
{
// Handle the exception
// Possibly send it to the logs
}
finally
{
if (site!=null ) site.Dispose();
}
SharePoint 2010 Logging information: http://zimmergren.net/archive/2011/01/17/sp-2010-developing-for-performance-part-4-logging.aspx
Approach 4 – A mix of the aforementioned approaches
In some scenarios it might be a necessity to mix the aforementioned methods for disposing.
using (SPSite site = new SPSite ("http://zimmergren"))
{
foreach (SPSite oSite in site.WebApplication.Sites)
{
try
{
// Do stuff
}
catch (Exception ex)
{
// Log and handle exceptions
}
finally
{
if (oSite!=null ) oSite.Dispose();
}
}
}
Using SPDisposeCheck.exe to help us check for issues
It’s one thing to be pro-active and think about the dispose patterns when you’re developing your applications – but sometimes you can’t cope for every scenario in your complex code. Don’t worry though – you’ve got one of my best friends to help you out with that – the SPDisposeCheck.exe tool that Microsoft released to check for disposal problems.
Download and install it
There’s a new version of the popular dispose-check tool for SharePoint called SPDisposeCheck. You can find it here: http://code.msdn.microsoft.com/SPDisposeCheck
Grab your copy of the tool and hang on tight for the ride!
Configure it
When you’ve installed the tool, you can see a new menu option in the "Tools" menu:
Clicking the "SharePoint Dispose Check" menu item will bring up the SPDisposeCheck configuration menu like this:
In this dialog you can configure how the tool should behave, and if it should execute after each build. What’s even cooler is you can choose how to treat the problems.
When you’re building your Visual Studio project, the SPDisposeCheck will perform a post-build command (if you’ve ticked the Execute After Build checkbox) – and you’ll see the output directly in your Error-window:
Tip!
Always have this tool installed, and every now and then run the SPDisposeCheck to make sure your code is properly disposing your objects. Otherwise it’ll warn you like in the picture above![]()
False positives
When it comes to checking for dispose problems or leaks with this tool, it can sometimes give you something you’d refer to as "a false positive". What that generally means is that although the tool might report a problem, it really isn’t.
Ignoring reports
Sometimes with the SPDisposeCheck tool you’ll get quite a bunch of "false positives" reported, or for whatever other reason you’d like to ignore certain error messages from the SPDisposeCheck tool – you can do that by implementing the SPDisposeCheckIgnore attribute (available as source code in the SPDisposeCheck installation folder).
The following code snippet is taken from the "SPDisposeCheckIgnoreAttribute.cs" file in the SPDisposeCheck installation folder. Add this code to your project (you can change the namespace..):
using System;
namespace Zimmergren.SP2010.DisposePatterns
{
public enum SPDisposeCheckID
{
// SPDisposeCheckIDs.
SPDisposeCheckID_000 = 0,
SPDisposeCheckID_100 = 100,
SPDisposeCheckID_110 = 110,
SPDisposeCheckID_120 = 120,
SPDisposeCheckID_130 = 130,
SPDisposeCheckID_140 = 140,
SPDisposeCheckID_150 = 150,
SPDisposeCheckID_160 = 160,
SPDisposeCheckID_170 = 170,
SPDisposeCheckID_180 = 180,
SPDisposeCheckID_190 = 190,
SPDisposeCheckID_200 = 200,
SPDisposeCheckID_210 = 210,
SPDisposeCheckID_220 = 220,
SPDisposeCheckID_230 = 230,
SPDisposeCheckID_240 = 240,
SPDisposeCheckID_300 = 300,
SPDisposeCheckID_310 = 310,
SPDisposeCheckID_320 = 320,
SPDisposeCheckID_400 = 400,
SPDisposeCheckID_500 = 500,
SPDisposeCheckID_999 = 999
}
[AttributeUsage (AttributeTargets .Method | AttributeTargets .Assembly,
Inherited = false , AllowMultiple = true )]
public class SPDisposeCheckIgnore : Attribute
{
public SPDisposeCheckIgnore(SPDisposeCheckID Id, string Reason)
{
_id = Id;
_reason = Reason;
}
protected SPDisposeCheckID _id;
protected string _reason;
public SPDisposeCheckID Id
{
get { return _id; }
set { _id = Id; }
}
public string Reason
{
get { return _reason; }
set { _reason = Reason; }
}
}
}
Once you’ve done that, you can use the attribute on your methods and assemblies to tell them to ignore that specific item.
Example usage of the SPDisposeCheckIgnore attribute:
[SPDisposeCheckIgnore (SPDisposeCheckID .SPDisposeCheckID_110,
"False Positive, nothing to see here, move along!" )]
private static void MyAwesomeMethod()
{
// Your method code with false positives
}
What if I’m an awesome coder already?
Too many times have I encountered problems in projects due to not properly checking for memory leaks.
Better safe than sorry. That’s all I’m going to say about that
Summary & Links
What we’ve learned from this article is that you should always keep in mind how you handle your objects in your code – and especially when it comes to the SharePoint objects that are invoking unmanaged code like the SPWeb and SPSite objects (to name two common ones).
Make sure you’ve downloaded the latest version of the SPDisposeCheck tool to get the aforementioned fancy integration into Visual Studio 2010. It’s pretty awesome indeed!
Links / Resources
Enjoy!
- Posted in Technical
- 23 Comments
- Tags: Featured, How-To, Performance, SharePoint, SP2010
SP 2010: Developing for performance Part 1 – Developer Dashboard
December 18th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
SharePoint 2010 developing for performance article series:
In this series of articles I will briefly introduce you to some key concepts when it comes to developing for performance in our SharePoint 2010 applications.
Related articles in this article series
Part 1 – SP 2010: Developing for performance Part 1 – Developer Dashboard
Part 2 – SP 2010: Developing for performance Part 2 – SPMonitoredScope
Part 3 – SP 2010: Developing for performance Part 3 – Caching in SharePoint 2010
Part 4 – SP 2010: Developing for performance Part 4 – Logging
Part 5 – SP 2010: Developing for performance Part 5 – Disposal patterns and tools
Part 6 – SP 2010: Developing for performance Part 6 – CSS Sprites
Part 7 – SP 2010: Developing for performance Part 7 – Crunching those scripts
Part 8 – SP 2010: Developing for performance Part 8 – Control that ViewState
Part 1 (This article):
This is Part 1 of 5 where I will introduce you to the developer dashboard in SharePoint 2010. The reason for the developer dashboard being a key concept in your SharePoint development tasks is the quick and effective manner of which you can start looking for bottlenecks and problems in your installation without launching any additional tools.
SharePoint 2010 Developer Dashboard
The developer dashboard is a perfect tool for anyone who wants a quick way to access information about what goes on while rendering a page in SharePoint. It contains information about Web Parts, events, DB calls and a whole lot of nifty information.
Activating the Developer Dashboard
Developer Dashboard is a utility that is available in all SharePoint 2010 versions, and can be enabled in a few different ways:
- PowerShell
- STSADM.exe
- SharePoint Object Model (API’s)
Using these different approaches is very simple; All you will need to do is use one of the aforementioned methods to activate the dashboards, as described here:
Activate the Developer Dashboard using PowerShell:
$devdash =
Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashboardSettings;
$devdash.DisplayLevel = ‘OnDemand’;
$devdash.TraceEnabled = $true;
$devdash.Update()
Activate the Developer Dashboard using STSADM.EXE
STSADM.EXE -o setproperty -pn developer-dashboard -pv ondemand
Activate the Developer Dashboard using the SharePoint Object Model
using Microsoft.SharePoint.Administration;
SPWebService svc = SPContext.Current.Site.WebApplication.WebService;
svc.DeveloperDashboardSettings.DisplayLevel =
SPDeveloperDashboardLevel.Off;
svc.DeveloperDashboardSettings.Update();
Note that in the preceding samples I’ve used a property called "OnDemand". This can be set to the following values:
- Off (Disables the Developer Dashboard)
- On (Enables the Developer Dashboard)
- OnDemand (Enables the Developer Dashboard upon request by clicking the icon in the upper right corner)
If the Developer Dashboard is set to OnDemand, this button appears in the top right corner just next to your login name: ![]()
As a side note, you can also enable Tracing for your developer dashboard to enable your dashboard to display the asp.net page trace. I will cover this a bit further down.
Reading the Developer Dashboard information
When you click the small icon in the top right corner, the Developer Dashboard will be opened and displayed at the bottom of your page.
You can see that it has a Green border right now. That generally means it’s loading quick enough not to be a real problem. It can also render Yellow, which indicates that there’s a slight delay and then it could render a Red border which would mean you definitely need to look into it immediately!
So, what information can you read out of this?
Page Request to the left-hand side
You can read out the Page Request, and see what loads and how long it takes to load. This is perfect to use to track down heavy-loading apps or finding out what’s taking so long to render the page; ![]()
Web Server, Events, DB Queries, Service Calls, SPRequests, Web Part Events on the right-hand side
Dig deeper into the SQL DB queries by clicking on the link
If you’d like to get some more in-depth information about what query was shot away to the DB, click the hyperlink corresponding the query you want to find out about and you’ll see something like this;
Displaying ASP.NET Trace information
One thing that I absolutely love about this tool is the ability for the tool to enable Tracing (this should be enabled when you enable the Developer Dashboard using the SP Object Model or PowerShell by setting the following flag:
DeveloperDashboardSettings.TraceEnabled = true;
If you’ve done this, and you’ve got the Developer Dashboard enabled – you should see the following link in the bottom left area of the developer dashboard: ![]()
If you click it, you’ll see the full ASP.NET Page Trace like this (awesome, very very awesome): ![]()
The beauty about this is you don’t have to go and edit the web.config and enable tracing there – you just click this little button and it’s all done. I love it.
Developer Dashboard Visualizer – Extend your developer dashboard with diagrams
One of my friends Jaap Vossers wrote up a cool functionality to use in conjunction with the Developer Dashboard – Developer Dashboard Visualizer – which is a cool utility if you want to visualize what the rendering process looks like on your page.
If you’ve downloaded this awesome solution, you’ll see a new Site Collection feature that you’ll need to enable: ![]()
Once that’s done, next time you’ll visit the Developer Dashboard awesomeness it’ll look something like this: ![]()
Developer Dashboard activation as a Feature
My good friend Wictor Wilén wrote a quick and cool feature to ease the activation of the Developer Dashboard settings (find it here) which allows you to more easily change the settings of the developer dashboard without doing it by typing any scripts or code.
Once you’ve downloaded and installed the solution, you’ll find a new Farm feature that should be activated, which provides some functionality to Central Administration for administering the Dev Dashboard: ![]()
If you’ve deployed and got this feature activated, head on over to General Application Settings and you’ll see that you’ve got a new header called "Development Settings" containing a link to "Developer Dashboard Settings".
Click it and you’ll see this very awesome page that enables you to configure the Developer Dashboard without actually writing any code!
Summary
In this article you’ve read about the Developer Dashboard and how to enable it, and a few extra tips that you can download and install to make your experience with the Developer Dashboard even cooler.
This was part 1 in an article series talking about a few concepts we’ll need to understand in order to properly plan and design for performance in our SharePoint 2010 applications.
Stay tunes for parts 2-5.
Enjoy!
- Posted in Technical
- No Comments
- Tags: Debugging, Featured, How-To, Logging, Performance, SharePoint, SharePoint 2010
SP 2010: Introduction to programmatically working with Taxonomies in SharePoint Server 2010
August 28th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
One of the coolest new set of functionality for SharePoint 2010 is the Taxonomies (Term Store, Term Sets, Terms) that you can easily create using the amazing Managed Metadata Manager service application.
In this article I’ll talk briefly about how you can utilize the SharePoint API to programmatically work with Taxonomies and create terms and fetch the terms in your term store. This should give you some nice ideas on how to get going!
A simple example of a taxonomy
Let’s say we’ve got a taxonomy worked out and implemented in SharePoint. It could look something like this (I’m using some made up samples below):
So, if you’ve got a taxonomy configured in your Managed Metadata Service Application, you can work with those programmatically – and that’s what this little tip is about.
Work with the taxonomy API’s programmatically in SP 2010
In this article I will talk about some of the basics to get started with taxonomies in SharePoint 2010 programmatically. First, of course, we need to create a new project and add the references for the Taxonomy API.
Preparing for development
First of all, create a new project (In my case, I chose to create a Visual Web Part project).
You’ll need to add the following reference to your project:
You’ll find this reference here:
C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14ISAPIMicrosoft.SharePoint.Taxonomy.dll
Namespaces
So, the first thing we would like to do is to learn how we can read the taxonomies we’ve got in our store. To do this, we utilize Microsoft.SharePoint.Taxonomy.
There’s a few good-to-know classes in this namespace that we’re going to work with:
- Microsoft.SharePoint.Taxonomy.TaxonomySession
- Microsoft.SharePoint.Taxonomy.TermStore
- Microsoft.SharePoint.Taxonomy.Group
- Microsoft.SharePoint.Taxonomy.TermSet
- Microsoft.SharePoint.Taxonomy.Term
The above classes are stated in their hierarchically correct order, meaning means that you start out with the TaxonomySession which contains the TermStore, which contains the Groups.. and so on.
Reading the Metadata store (Managed Metadata Service) programmatically
Sample code from my Visual Web Part’s user control (I have a control called tvMetadataTree in the user control):
public partial class TaxonomyWebPartUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
SPSite thisSite = SPContext .Current.Site;
TaxonomySession session = new TaxonomySession (thisSite);
TreeNode treeNode = new TreeNode ();
treeNode.Text = "Metadata Awesomeness" ;
tvMetadataTree.Nodes.Add(treeNode);
foreach (TermStore termStore in session.TermStores)
{
var tsNode = new TreeNode (termStore.Name, null , null , "" , null );
treeNode.ChildNodes.Add(tsNode);
//treeNode = tsNode;
foreach (Group group in termStore.Groups)
{
var node = new TreeNode (group.Name, null , null , "" , null );
treeNode.ChildNodes.Add(node);
//treeNode = node;
foreach (TermSet termSet in group.TermSets)
{
node = new TreeNode (termSet.Name, null , null , "" , null );
treeNode.ChildNodes.Add(node);
treeNode = node;
foreach (Term term in termSet.Terms)
{
AddTermSet(term, treeNode);
}
}
}
}
}
void AddTermSet(Term term, TreeNode treeNode)
{
var node = new TreeNode (term.Name, null , null , "" , null );
treeNode.ChildNodes.Add(node);
treeNode = node;
foreach (Term t in term.Terms)
{
AddTermSet(t, treeNode);
}
}
}
The end result will be a simple TreeView control filled with the Metadata structure from the store, looking something like this:
That’s about what you would need to get started with this!
Summary
Alright, so I wrote this small article up due to some students asked me for some taxonomy sample code a while back. I hope everyone enjoys this tip on how to programmatically work with the Taxonomies in SharePoint Server 2010!
As always, enjoy!
- Posted in Technical
- 1 Comment
- Tags: How-To, SharePoint, SharePoint 2010, SPS, Taxonomy
SP 2010: How to create a PowerShell Snapin Cmdlet – Part 2
June 8th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
In my previous article (How to create a PowerShell Snapin – Part 1) I talked about the general approach to create a custom PowerShell Cmdlet. However, in Part 1 I did not talk about how you create SharePoint 2010 specific Cmdlets. That’s what this article is all about.
So without further ado, I will quickly brief you on how you can create a custom PowerShell Cmdlet for SharePoint 2010 using the SPCmdlet base class.
In my example I will create a very simple Cmdlet you can use to automatically create demo-sites for use in demo-purposes or development scenarios so you don’t have to go about creating all the different sites by hand, and without a need to create scripts to do the same.
Creating a custom PowerShell Cmdlet that talks with SharePoint 2010
I will add some functionality to my previous project (found in my previous article) and extend that project with some custom SharePoint 2010 specific Cmdlets to get your started with writing PowerShell cmdlets for SP 2010.
In order to do this, we should derive from a subclass of the type SPCmdletBase. The following base classes deriving from SPCmdletBase are available:
1. Create a new Cmdlet (SPNewCmdletBase)
- Create a new Class and name it something of your own preference (I chose this silly name: SPAwesomeness.cs)
- Add a reference to the following two namespaces:
using Microsoft.SharePoint;using Microsoft.SharePoint.PowerShell; - Add the following base code to your class:
using System;using System.Management.Automation;using Microsoft.SharePoint;using Microsoft.SharePoint.PowerShell;namespace Zimmergren.SP2010.PowerShell{[Cmdlet(VerbsCommon.New, "SPCreateDemoSites")]
public class SPAwesomeness : SPNewCmdletBase<SPWeb>
{protected override SPWeb CreateDataObject()
{throw new NotImplementedException();
}
}
}
As you can see in the code above I’ve got a class called SPAwesomeness which derives from the SPNewCmdletBase class which in turn derives from the SPCmdletBase. SPNewCmdletBase should be derived from when you create a Cmdlet that should create and save data to SharePoint.
Also note that we’re using the Attribute [Cmdlet] to set a name for our command, in this case SPCreateDemoSites.
When deriving from this class, you need to implement at least one method override, in this case CreateDataObject. This is where our magic will take place!
2. Add some logic to your custom SharePoint Cmdlet
Now that we’ve got the basic code up and out of the way, we need to add some logic to actually make something happen.
I’ve added some very simplistic code to create some Demo-sites based on the available templates in your installation. It looks like this:
using System;
using System.Management.Automation;
using Microsoft.SharePoint;
using Microsoft.SharePoint.PowerShell;
namespace Zimmergren.SP2010.PowerShell
{
[Cmdlet(VerbsCommon.New, "SPCreateDemoSites")]
public class SPAwesomeness : SPNewCmdletBase<SPWeb>
{
// Let's add a mandatory parameter that indicates that you need
// to specify a value for this property through the PS console
[Parameter(Mandatory = true,
ValueFromPipeline = true,
Position = 0,
HelpMessage = "Specify an existing site to extend with demo sites")]
public string SiteUrl { get; set; }
protected override SPWeb CreateDataObject()
{
var site = new SPSite(SiteUrl);
try
{
// SharePoint Server Publishing Infrastructure feature
site.Features.Add(new Guid("f6924d36-2fa8-4f0b-b16d-06b7250180fa"));
}catch(Exception ex)
{ /* Empty catch block is not recommended
*/}
SPWeb demoWeb = CreateBaseDemoSite(site);
// When we're done, you'll get this object returned to the PS console
return demoWeb;
}
private static SPWeb CreateBaseDemoSite(SPSite site)
{
// Creates a Blank Site which will host all the Demo-sites
SPWeb web = site.AllWebs.Add(
"DemoSite",
"Demo Sites",
"Demo Sites",
1033,
"STS#1",
false,
false);
web.QuickLaunchEnabled = true;
CreateDemoSites(web);
return web;
}
private static void CreateSite(SPWeb parentWeb, string url, string template)
{
string desc = " created by Tobias Zimmergren's custom cmdlets";
parentWeb.Webs.Add(url,
url + " demo",
url + desc,
1033,
template,
false,
false);
}
private static void CreateDemoSites(SPWeb web)
{
SPWebTemplateCollection webTemplates =
web.GetAvailableWebTemplates((uint)web.Locale.LCID, true);
foreach (SPWebTemplate template in webTemplates)
{
try
{
CreateSite(web,
template.Title.Replace(" ", ""),
template.Name);
}
catch (Exception ex)
{ /* Empty catch block is not recommended
*/ }
}
}
}
}
3. Test your custom SharePoint 2010 cmdlet
In order to test it, follow along with the steps I mentioned in my previous article (here) to deploy it – then call the new command you’ve created called New-SPCreateDemoSites like this:
It will ask you to supply the mandatory property (SiteUrl), so type in an existing url to an existing site collection and execute like this:
Now you’ll need to wait for a few minutes. What’s happening now is that your Cmdlet is creating a site called "Demo Sites" and will add a whole bunch of sub-sites to that new site.
Navigate to your new site called "Demo Sites" and you should see something like the following sub-sites created:
Summary & Download
Quite easily you’ve created your first SharePoint 2010 Cmdlet extension to operate with the SPCmdletBase classes. In this case we’ve created a new site called Demo Sites and added a bunch of sites to that new site, as per the available templates on your server.
Download project
You can download my sample project here
Enjoy this awesomeness!
- Posted in Technical
- No Comments
- Tags: How-To, PowerShell, SharePoint, SharePoint 2010
SP 2010: How to create a PowerShell Snapin – Part 1
June 7th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
In this article I will talk about how you can get started with creating custom PowerShell commands for SharePoint 2010 that you can use.
You will see how easy it actually is to build a custom class library that in turn is an extension to the PowerShell console and will add a couple of extra commands according to your preference.
The reasons for wanting to do this is an endless list, but as an example if you’ve got repeated tasks you’ll need to perform that are not available out of the box, you can create them yourself and then use normal PowerShell scripts to execute your code. That way you can easily build your own custom commands (CmdLet) for PowerShell which basically extends the functionality to support whatever scenario you’ve got.
You might remember that in SharePoint 2007 you could extend the STSADM.EXE command with something called STSADM Extensions. The approach I’m talking about in this article is pretty much the same concept – extending the build-in commands of your PowerShell console by adding custom code.
How to create a PowerShell Snapin
Download the Windows SDK in order to get the
System.Management.Automation.dll file for PowerShell easily accessible.
1. Create a new Class Library project
Start out by creating a new Visual Studio 2010 Class Library project and give it a proper name.
I’ve named mine Zimmergren.SP2010.PowerShell.
Add assembly references
- Add a reference to System.Management.Automation
- This DLL is located in:
C:Program FilesReference AssembliesMicrosoftWindowsPowerShellv1.0
(if you installed the Windows SDK as I told you earlier on in this article) - Add a reference to System.Configuration.Installation
You should now have the following reference added:
2. Create a PowerShell Installer class
In order for our PowerShell Cmdlet to work, we need to create an installer-class. This class is called when you install the SnapIn/Cmdlet and will provide the system with some information like where it comes from and what it’s supposed to do.
Start out by creating a new class in your project, I named mine PowerShellInstallerClass.cs. Next, add the following code to that class:
using System.ComponentModel;
using System.Management.Automation;
namespace Zimmergren.SP2010.PowerShell
{
[RunInstaller(true)]
public class PowerShellInstallerClass : PSSnapIn
{
public override string Name
{
get
{
return "Zimmergren.SP2010.PowerShell";
}
}
public override string Vendor
{
get
{
return "Tobias Zimmergren";
}
}
public override string Description
{
get
{
return "Tobias Zimmergren's awesome PowerShell Cmdlets";
}
}
}
}
This essentially provides some information to the system upon installation of your SnapIn.
3. Create a PowerShell Cmdlet class
Now you need to continue this venture by creating a new class in your project. I named mine TestCmdlet1.cs.
Use the [Cmdlet()] attribute on your class to tell the system that it’s going to be a Cmdlet for PowerShell like this:
using System.Management.Automation;
namespace Zimmergren.SP2010.PowerShell
{
[Cmdlet(VerbsCommon.Get, "TestCmdlet1")]
public class TestCmdlet1 : PSCmdlet
{
}
}
Next, you should override the methods you want to execute your code and add some dummy-code. There’s a couple of different methods to use here:
- BeginProcessing()
- EndProcessing()
- ProcessRecord()
- StopProcessing()
You should make sure your class looks like this so we can test the first part out:
using System.Management.Automation;
namespace Zimmergren.SP2010.PowerShell
{
[Cmdlet(VerbsCommon.Get, "TestCmdlet1")]
public class TestCmdlet1 : PSCmdlet
{
protected override void BeginProcessing()
{
WriteObject("BeginProcessing() method - Execution has begun");
}
protected override void ProcessRecord()
{
WriteObject("ProcessRecord() method - Executing the main code");
}
protected override void EndProcessing()
{
WriteObject("EndProcessing() method - Finalizing the execution");
}
}
}
4. Deploy the new PowerShell Snap-ins
Since this is a generic Class Library-project, we need to create some kind of deployment script to make sure that our Cmdlet gets deployed when we build our project.
There are two requirements for deploying and installing our PowerShell Cmdlet:
- Deployed to the server (Using GACUTIL)
- Installed on the server (using INSTALLUTIL)
In this sample project I’m simply adding two lined in the Post-Build actions like this::
You’ll find the post-build events if you click project properties and go to this box:
5. Project overview
Your project should look something like this:
6. Test your PowerShell Snapin
In order to test our project, we now just need to build the Visual Studio project and the post build scripts will automatically hook up our assembly in the GAC and use INSTALLUTIL to install the Cmdlet.
To try the commands out, you need to launch a powershell console and type in the following command:
Add-PSSnapin Zimmergren.SP2010.PowerShell
Now you should be able to just call your command (in my case, it’s called TestCmdlet1) like this:
TestCmdlet1
This should bring your the following output in your PowerShell console window:
Great, our very first PowerShell cmdlet is created – and we have validated that it works!
Summary & Download
In this article we talked about how you create a general PowerShell Cmdlet in order to extend the capabilities in your PowerShell consoles. There’s no business logic incorporated in this sample, that’s up to you to implement in your projects. You’ve got the starting point to get sailing on the great PowerShell seas right here!
In my next article (Part 2) I will talk about the SharePoint 2010 specific details for creating a custom Cmdlet for your SharePoint installations. It will cover how you create custom Cmdlets to interact with the SharePoint 2010 object model in a nice way.
Download
Enjoy!
- Posted in Technical
- No Comments
- Tags: How-To, PowerShell, SharePoint, SharePoint 2010
SP 2010: SharePoint Server 2010 – Creating a custom Document ID provider
April 13th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
In this article I will talk about how you can create your custom Document ID provider for your SharePoint Server 2010 installation. Sometimes I’ve been getting the question weather or not it’s possible to change the behavior or change the way the Document ID’s are generated, and some people have a tendency to say no to that question, just because there’s no interface or out of the box functionality to do so.
I’ll give you a quick walkthrough of how you can extend your Site Collection by adding a custom Document ID provider, that will automatically generate custom ID’s based on your own algorithms entirely!
Recommended reading about Document ID’s before proceeding:
http://msdn.microsoft.com/en-us/library/ee559302(office.14).aspx
Document ID overview
This section will give you a very brief conceptual overview of Document ID’s in SharePoint Server 2010.
What is Document ID’s?
Document ID’s in SharePoint Server 2010 provide you with the ability to tag documents with a unique identification number. Something a lot of my clients have done manually or by implementing custom solutions to take care of in SharePoint 2007. With this new feature, you get all the required functionality to tag documents with unique identification numbers based on a specific pre-set formula with a custom prefix.
See this sample screenshot for an example:
Where do I enable Document ID’s for my Site Collection?
In order to enable Document ID’s in your Site Collection, you’ll need to activate the Site Collection Feature called Document ID Service.
See this screenshot for an example:
How do I change the way my Document ID’s are generated?
If you want to alter the way the Document ID’s are generated for your documents in your Site Collection, you can do that by navigating to:
Site Actions – Site Settings – Document ID Settings, like so:
From this new settings page, you’ll get the possibility to tell SharePoint how it should generate your unique ID’s. You can specify a prefix for all the generated ID’s:
I want to take it one step further!
If you’re not quite satisfied with the way SharePoint 2010 generates your Document ID’s for you, then you should most definitely follow along with the rest of this article as I will guide you through the steps to create your very own Document ID provider to generate exactly the kind of ID’s you want – based on your very own code/algorithms!
Bring it on!
Learning about a SharePoint 2010 Custom Document ID provider
This section will give you an overview of what you will need in order to create a custom Document ID provider for SharePoint Server 2010!
Note: As of this writing MSDN isn’t fully updated on these new SharePoint Server namespaces. Some details may or may not change when SharePoint Server 2010 is released into the wild (RTM)
Microsoft.Office.DocumentManagement
The namespace Microsoft.Office.DocumentManagement contains a class called DocumentIdProvider, which will be the base for our upcoming project!
Microsoft.Office.DocumentManagement.DocumentIdProvider
This is the class we will derive from when creating our custom provider. It contains three (3) abstract methods and one (1) abstract method that we need to implement:
- GenerateDocumentId (Method)
- GetDocumentUrlsById (Method)
- GetSampleDocumentIdText (Method)
- DoCustomSearchBeforeDefraultSearch (Property)
A description of each of these methods and the property will be made inline in my code in the samples!
Creating a SharePoint Server 2010 Custom Document ID provider
Let’s code this little piece of functionality, shall we. The final project (very basic) will look something like this:
So, let’s get coding.
1. Create a class and derive from DocumentIdProvider
public class CustomDocumentIdProvider :
Microsoft.Office.DocumentManagement.DocumentIdProvider
{
// Method to generate the actual document ID. Awesomeness lives here!
public override string GenerateDocumentId(SPListItem listItem)
{
// In this method we will tell SharePoint how it should generate
// the unique ID we want.
// In my case, I’ve just created a dummy-generator.
// Normally you would perhaps want to fetch this from another system or
// generate it properly instead of like this..// Points to a method I’ve created that generates foo-ID’s
return FooSampleIDGenerator.GetFooUniqueID();
}public override bool DoCustomSearchBeforeDefaultSearch
{
// If set to true: It will call the GetDocumentUrlsById method before search
// If set to false: It will use SharePoint Search before custom methods
get { return false; }
}public override string[] GetDocumentUrlsById(SPSite site, string documentId)
{
// Returns an array of URLs pointing to
// documents with a specified DocumentId
// An empty string array// This is where you will implement your logic to find
// documents based on a documentId if you don’t want to use
// the search-approach.
return new string[] { };
}public override string GetSampleDocumentIdText(SPSite site)
{
// Returns the default Document ID value that will be initially
// displayed in the Document ID search web part as a help when searching
// for documents based on ID’s.
// This should correspond with the way you’ve designed your ID pattern
return "AWESOME-12345-67890-SharePointRules";
}
}
2. Create a Feature Receiver to hook up your custom provider with your Site Collection
public class ProvisionCustomDocIdProviderEventReceiver : SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
DocumentId.SetProvider(properties.Feature.Parent as SPSite,
new CustomDocumentIdProvider());
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
DocumentId.SetDefaultProvider(properties.Feature.Parent as SPSite);
}
}
Actually, you’re all done with the code for now.
3. Go to Document ID Settings page and see this message appear
This basically means that your custom provider has been successfully enabled (as per our Feature Receiver).
4. See that the Document ID’s on your documents now is using your custom provider
(Please allow for some time to pass so the Timer Jobs can do their magic, or manually go into Central Admin and run the timer jobs instantaneously)
Behold, awesome custom Document ID provider in action:
Summary and Download
What did we just do?
What we just did was to create a custom Document ID provider that generates our very own custom Document ID’s based on whatever algorithm or pattern we want. There’s no need to follow the built-in format for your generated IDs – which some people have presented in their seminars and blogs. So there you go, step by step!
This could be especially awesome if you’ve got an external system generating Document ID’s already, and you want SharePoint to use those ID’s alongside whatever other system is running. Use your own imagination as to what can be done. The code is in your hands, Obi Wan Coder!
Download project
Enjoy, and please don’t be afraid to leave comments!
- Posted in Technical
- 10 Comments
- Tags: Document ID, How-To, SharePoint, SharePoint 2010, SPS
SP 2010: Getting started with LINQ to SharePoint in SharePoint 2010
February 19th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
In SharePoint 2010 you now have the ability to use LINQ syntax to fetch items from your lists instead of using the "traditional" approach of CAML queries. (Including SPSiteDataQuery and SPQuery objects)
In this article I will give you a brief introduction to how you can get started using LINQ queries in SharePoint, also known as LINQ to SharePoint.
Basics of LINQ?
As a prerequisite to this article, I’m going to imply that you know what LINQ is and how to write basic LINQ queries in any .NET application already. I’m not going to dive into the details about LINQ or the syntax itself here – please see MSDN for that!
LINQ to SharePoint!
In order to work with LINQ in SharePoint 2010, we need use a tool called SPMetal.exe which resides in the 14bin folder. This tool is used to generate some entity classes which Visual Studio 2010 can use to get IntelliSense, and allows for LINQ-based queries to be performed on your lists.
Noteworthy:
- LINQ to SharePoint queries are translated to proper CAML queries
- CAML queries are in turn later translated to SQL queries
SPMetal.exe
Using the tool called SPMetal, we generate our entity-classes that are needed to perform these object oriented queries toward our SharePoint server.
These are the required steps to get hooked up:
- Launch a cmd-window and navigate to C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14bin
- Run the following command to utilize the SPMetal.exe tool with the following syntax:
- Now navigate to C: (or wherever you chose to output your file) and make sure the file has been generated:
- Open up the file and take a look at the content that SPMetal now have provided us with:
Note that the class name is now MyEntitiesDataContext. It’s based on the name you specify as your code file in the SPMetal.exe command line tool.If you were to use /code:C:Awesome.cs instead, it would generate a class called AwesomeDataContext.
With that done – all we need to do is import it to one of our projects and use it!
Visual Studio 2010 – Let’s create a sample Web Part that utilizes LINQ to SharePoint
In this sample I will create a simple Web Part that will use LINQ to SharePoint syntax to fetch some information from the Announcements list. A basic sample I use in my training classes as well, and should be fairly easy to grasp!
- Create a new project (I’m going to create a new Visual Web Part project)
- Import your DataContext-file by choosing your Project -> Add -> Existing Item:
- Specify your file (mine is called MyEntities.cs):
- Make sure it’s properly placed in your project structure – then we’re good to go:
Alright – that’s easy enough. Thus far we have created an entity file using SPMetal.exe and now we have successfully imported it into our project.
Add proper references
Now in order to use LINQ to SharePoint, you also need to reference the Microsoft.SharePoint.Linq assembly. Point to references, right-click and choose "Add Reference" and select the Microsoft.SharePoint.Linq.dll file:
In your code, reference the assemblies:
Ready to code?
What you should’ve done up until now is this:
- Generate your entities using the SPMetal.exe tool
- Reference the newly created file from your SharePoint project
- Make sure you’re using the proper references for System.Linq and Microsoft.SharePoint.Linq
- Be ready to code
Code!
In my example I will have a Visual Web Part that will use LINQ to SharePoint to fetch all Announcements from my Announcement-list and work with those results. If you want to see the entire project, look at the bottom of this article where you can download it.
IntelliSense!
While you code your queries using LINQ to SharePoint, you will now have access to IntelliSense, which you did not have with CAML queries:
I’m going to leave it at that – very (very) easy to get started with LINQ to SharePoint, and all you really need to know is to start using the SPMetal tool to generate your entity classes and hook’em up with Visual Studio to start coding.
Summary & Download
As you can see, there’s not a lot of things you need to do in order to work with LINQ in your SharePoint applications with your SharePoint-data.
I’ve been pinged plenty of times on how you can get started with this, and there you have it. More in-depth articles to come later – this is just to get your wagon rolling!
To download the sample project, click here: [Download]
Enjoy!
- Posted in Technical
- 36 Comments
- Tags: How-To, LINQ, SharePoint, SharePoint 2010, SPF, SPS
SP 2010: Getting started with Business Connectivity Services (BCS) in SharePoint 2010
January 18th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
Article 1 in the small BCS-series:
1. SP 2010: Getting started with the Business Connectivity Services (BCS)
2. SP 2010: Programmatically work with External Lists (BCS) in SharePoint 2010
3. SP 2010: Programmatically work with External Lists (BCS) using the Client Object Model
BCS in SharePoint 2010 is an awesome refinement of the Business Data Catalog from MOSS 2007. With BCS – or Business Connectivity Services – you get the possibility to connect external data and work with it from SharePoint.
In this article I will not cover the basics of what BCS is all about (MSDN/TechNet does this very well) – I will rather give you a walkthrough of how you can setup a BCS connection to an external database, and then work with this information directly from a SharePoint list – without the user actually knowing anything about the connection to the database.
BCS Poster: Business Connectivity Services Poster
BCS Team Blog: http://blogs.msdn.com/bcs/
A sample SQL database
I’ll just show you how my sample database is set up – simply create a new database in your SQL Server and have it filled with some example data. In my case, this is the data in my SQL database, called Zimmergren_DB:
In this sample database, I’ve added a table called ProductList which in theory will represent some products in this database, like this:
I’m filling the database with some sample data, so we will be familiar with this data when we later watch this information from SharePoint:
Alright – we have some sample data in our SQL Server. Nothing fancy, just some very simple data. Great, let’s get going with the fun stuff!
Creating an external content type
The most effective and easy way to set up a simple BCS connection, is to use SharePoint Designer 2010. You heard me, we can now get up and running with BCS by using SPD instead of modeling complex ADF files and things like that.
In order to do this, we need to create a new External Content Type!
Here’s how do create our External Content Type and hook it up with our database, step by step:
- Open the site you want to work with using SharePoint Designer 2010
- Select "External Content Types" in the left hand navigation:
Loading this page might take some time, be patient! - Click to create a new External Content Type like this:
- Click the link that reads: "Click here to discover external data sources and define operations":
- Click "Add Connection"
- Select "SQL Server" as your Data Source Type:
- Enter the details about your connection to your SQL Server:
- When the connection is made, your Data Source Explorer will be filled with the database you have specified. Now choose the table you want to work with, and right-click and select "Create All Operations":
You’ll be presented with a wizard-like dialog where you can specify the operations, elements and other properties for your BCS connection.
- Click "Next" to get to the Parameters page
- Select the field that you want to act as an Identifier. In my case I’ve selected my ProductID just to get on with it:
- Click "Finish"
- You’ll be presented with a list of operations that your External Content Type can do, like this:
That’s it. A few points, a few clicks – and you’re done. Let’s create an external list (using the Browser to show how simple it is..) and hook up our external content type with it!
Creating an external list
There’s a few ways to create an external list in SharePoint 2010. We will create it using the Browser UI to show you how simple it can be.
- Open your site and choose Site Actions - More Options…
- Select the External List template, and click Create
- Enter a name for your list, e.g. Product List
- You’ll see a field in this list called External Content Type, click the browse-button beside it:
What is really awesome here, is that you’re now presented with a dialog where you simply can choose the data source for this list. That means, you’ll select the data source you’ve created (mine is called Zimmergren_DB). Then your list will automatically work against the SQL database, but still have the look and feel of a SharePoint 2010 list.
- Select your data source and click OK:
- Now simply click the button called Create:
Would you look at that! You’re now working with external data, from your (what looks to be) normal SharePoint list! This is brilliant!
You now have the ability to create new items, update existing items, delete items and do all your normal CRUD-operations (CRUD = Create, Read, Update, Delete) straight from the SharePoint 2010 list.
Proof of concept – Adding a new product
Let’s just for the fun of it add a new product called "Awesome Product 1.0" like the following screenshot:
Now go to your SQL Server and see the changes take effect immediately. The data is NOT stored in SharePoint, it’s stored in your SQL Database.
This is what my table now looks like in the SQL Server, after adding a new item in the SharePoint list:
Summary
With a few points, followed by a few clicks – you’ve set up your external data connection. Basically it’s that simple.
Of course there’s a lot of things to consider when doing these configurations – and you might not want to auto-generate the CRUD-operations, but rather create them one by one and specify more fine-grained permissions etc.
This is merely a sample to show you how easy it is to actually get up and running with the SharePoint 2010 Business Connectivity Services (BCS) and work with external data!
Enjoy
- Posted in Technical
- 17 Comments
- Tags: BCS, How-To, SharePoint, SharePoint 2010, SPF, SPS
SP 2010: How To – Relational lists in SharePoint 2010
January 5th, 2010 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
One of the new cool things in SharePoint 2010 is the fact that we now have relational lists. In my previous article about List Joins, I talked about how you programmatically can fetch and join information from more than one list with the improved SPQuery object.
In this article I will give you an overview of what capabilities you get out of the box when installing SharePoint 2010 – in terms of relational data in lists.
Relational Lists in SharePoint 2010 – Overview
By utilizing Lookup fields in SharePoint 2010, we can enforce a relationship behavior that we previously would have to work very hard to achieve.
Microsoft have now provided us with a few new options when working with Lookup Fields:
- Joins between lists
- Projected Fields
- Relational integrity
Joins between lists
As mentioned, we have the capability to create relationships between lists in SharePoint 2010. This is quite easy to do using the browser UI, which I will soon demonstrate step-by-step.
Projected Fields
With projected fields we have the capability to pull information from a parent list into the view of the child list.
This basically mean that you can reference and display information from a parent list, in your child list. The fields are Read-Only but enables you to get a much nicer joined view.
Relational integrity
With SharePoint 2010 and relations in lists, you would of course wonder how it handles the relational integrity. E.g. what happens if I delete or try to delete something in the parent list?
Well, there’s generally two relational integrity options:
- Restricted delete
Basically the restricted delete option enables you to enforce a behavior that means that you can’t delete any items that have relations from the list. E.g. if the item you’re trying to delete have a bunch of child-items, you cannot delete them. - Cascade delete
Cascade delete on the other hand, means that when you’re trying to delete an item which has relations – it’ll delete the related items as well.
Delete and Recover related items – Recycle Bin
A question I got the other day was:
"If I delete an item in my parent list and have cascading delete so all my child items are deleted, how do I restore them if I made a mistake?"
Quite simple my dear Watson, you utilize the recycle bin. When you delete an item using Cascading Delete, the item and it’s related items are placed in the Recycle Bin. From there you can obviously easily recover the items as well. This is what an item with relations looks like in the recycle bin:
[PIC]
Step by step – Do it yourself
Alright – so we’ve covered some of the basics of relational lists, nothing fancy. But now we want to create some lists and have relationships between them – so let’s get on with it!
1. Create a parent list
- Create a new Custom List named "ParentList"
- Create a new Coumn in that list as per the following settings:
- Add some sample items in the list like this:
2. Create a child list
- Create a new Custom List named "ChildList"
- Create a new Column in that list as per the following settings:
Please note that I checked the City checkbox. This will create a Projected Field against the lookup automatically so you can view that information which exist in the parent list – directly in the child list.
3. Test out the projected fields functionality
Add some new items in the ChildList to see that when you add an item and choose a company from the ParentList it will automatically show the projected field ("City") as a read-only field in the child-list:
4. What about enforcing relational behavior?
I’m glad you asked. When you create (or change settings for) a lookup field (like the "ParentLink" field), you have the ability to change settings for the relational behavior.
Go to your "ParentLink" column, or when you create a new lookup field – and see the following dialog:
From this dialog as you can see, you have the ability to make the necessary settings for your fields.
Restricted Delete
If you choose the "Restricted Delete" option, you will see the following behavior when trying to delete an item that has related items:
Cascade Delete
If you choose the "Cascade Delete" option for your lookup field instead, you’ll be sending the items directly to the Recycle Bin instead. Then it’ll look like this in the recycle bin:
Note, that you have the icon that looks like a relational diagram in your recycle bin – this means that you’ve deleted an item that may have deleted linked items. If you restore this item (in our case, TOZIT) it will automatically restore all of the items that were originally deleted.
So, we have the kind of enforced relationships we’ve longed for since the dawn of days!
Summary
Voila. Easy as 1-2-3, you have created two very simple lists and created a relationship between them – and optionally you can enforce this relationship using the "Enforce relationship behavior" settings for Restrict Delete or Cascade Delete.
Enjoy!
- Posted in Technical
- 17 Comments
- Tags: How-To, SharePoint, SharePoint 2010
SP 2010: Getting started with the Client Object Model in SharePoint 2010
November 30th, 2009 by Tobias Zimmergren
Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren
Introduction
In this article I will talk about how you can get started with using the Client Object Model in SharePoint 2010. This new object model is introduced in SharePoint Foundation 2010, and does not require SharePoint Server 2010 to be installed.
The Client Object Model is a new object model introduced in SharePoint 2010 which is aimed at making things easier for the developer when developing client-side applications for SharePoint 2010.
Three new client APIs
With the Client Object Model, Microsoft has introduced a set of new APIs to work with to ease the daily tasks of developers.
- .NET Managed Applications (using the .NET CLR)
- Silverlight Applications
- ECMAScript (JavaScript, JScript)
The client APIs provide you as a developer with a subset of the Microsoft.SharePoint namespace which is based on the server-side object model.
Naming conventions
As a small side-note I would like to mention that the objects you are comfortable with calling “SPWeb”, “SPSite”, “SPList” and so on are now named “Web”, “Site”, “List”.
So to conclude the naming convention, the “SP” in the objects has been dropped. Easy enough to remember, right?
Good, let’s move on to some actual code samples to get things fired up!
SharePoint 2010 Client Object Model – Creating your first client-side application
With some fundamental knowledge about the Client OM mentioned above, I would like to take this one step further and actually demonstrate how you can utilize the Client OM in order to create your first client-side application and work with data from SharePoint, instead of using the built-in Web Services.
Step 1 – Creating the Visual Studio project
To be able to follow along with this article, the prerequisites are that you have SharePoint 2010 and Visual Studio 2010 installed in a development environment.
- Launch Visual Studio 2010
- Create a new project
- Choose “Windows Application” and apply the following settings to your project:
- Target Framework: .NET 3.5
- Build output: AnyCpu (or x64)
As you can see we are specifically targeting .NET 3.5 since this is the version of the framework that SharePoint 2010 is based on.
Also notice that we are changing the build output from x86 (unsupported!) to AnyCpu or x64 in order to be able to compile and run this project properly.
You should now have an empty Windows Application project like so:
Step 2 – Adding the Client Object Model references
Next, we need to add references to the Client Object Model in order to be able to work with the client-side APIs from our awesome Windows Application.
- Right click the “References” node and choose “Add Reference”
- Choose “Browse”
- Make sure they are included in the references of your project:
Alright – that was easy enough. Adding the references shouldn’t be any problems. Moving on the the more interesting part – getting our first client object model application up and running!
Step 3 – Make our Windows Application pull out some data from SharePoint
Now that you’ve created your Windows Application, targeted the correct framework and platform, added the Client object model references – we’re ready to take on some Client Object Model action!
Adding the necessary controls to the form
- Add the following controls to your Windows Application:
- A new ListBox control
- A new Button control
- A new TextBox control (Set multiline = true, readonly = true etc to make it look like mine if you want..)
Adding some code-logic to fetch the lists on a particular site and populate the ListBox
- Double-click the Button that you’ve created and add the following code logic:
private void btnGetLists_Click(object sender, EventArgs e)
{
lbLists.Items.Clear();using (SP.ClientContext ctx = new SP.ClientContext("http://zimmer"))
{
var web = ctx.Web;ctx.Load(web);
ctx.Load(web.Lists);ctx.ExecuteQuery();
foreach (SP.List list in web.Lists)
{
lbLists.Items.Add(list.Title);
}
}
}
- Double-click the ListBox that you’ve created and add the following code logic:
private void lbLists_SelectedIndexChanged(object sender, EventArgs e)
{
using (SP.ClientContext ctx = new SP.ClientContext("http://zimmer"))
{
var list = ctx.Web.Lists.GetByTitle(lbLists.SelectedItem.ToString());ctx.Load(list);
ctx.ExecuteQuery();string infoAboutList =
string.Format("Title: {0}ItemCount: {1}IsHidden: {2}",
list.Title + Environment.NewLine,
list.ItemCount + Environment.NewLine,
list.Hidden.ToString());textBox1.Text = infoAboutList;
}
}
Things to note:
- You use the ClientContext object to connect and work with the SharePoint server
- You use ClientContext.Load() to load the objects you need to work with
- You use the ClientContext.ExecuteQuery() to execute the query and fetch the objects
Running the simple application
When you decide to run this awesomely simple application, it will look something like this:
With a few simple lines of code you have created your first Client-side application for SharePoint 2010.
Of course we could elaborate this sample to make it way more complex, but this is a teaser for you to get started with the client object model.
Step 4 – Authentication Options for our application
Quite naturally, the question of how you can authenticate to SharePoint often pops up when I do my SP 2010 training and seminars. With that said, I’ll walk you through the different authentication options you’ve got for your client application.
Basically there are three (3) authentication options you can use when you’re working with the Client Object Model in SharePoint 2010:
- Anonymous
- Default
- FormsAuthentication
If you do not choose an authentication method in your code, the application will default to using the client’s Windows Credentials (DefaultCredentials)
Example 1: Using anonymous authentication
ctx.AuthenticationMode = SP.ClientAuthenticationMode.Anonymous;
Example 2: Using Forms Authentication with the Client Object Model
SP.FormsAuthenticationLoginInfo formsLoginInfo =
new SP.FormsAuthenticationLoginInfo("TobiasZimmergren", "SecretPassword");ctx.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;
ctx.FormsAuthenticationLoginInfo = formsLoginInfo;
When you call the Forms Authentication, it will automatically call the Authentication Web Service for you and return the authenticated cookie.
Summary & Downloads
With very little effort, we have created a new Windows Form application that can be run as a client-side application – without the need of SharePoint to be installed on that machine.
Easy enough we have done so without calling any Web Services.
With that said, you should now at least be updated on how you create your first few Client Object Model applications, and be able to start your own project(s) using this new awesome OM.
ENJOY!
Download my sample project
- Posted in Technical
- 21 Comments
- Tags: Client Object Model, How-To, SharePoint, SharePoint 2010





