Posts Tagged ‘How-To’

Author: Tobias Zimmergren
www.zimmergren.net | www.sharepointdiscussions.com | www.pointbird.com@zimmergren

Introduction to the problem

It’s not uncommon when upgrading to SharePoint 2013 from a previous version of SharePoint that you’ll get encoded claims usernames in the places you may have seen normal usernames (DOMAIN\Username) syntaxes before. In my case it was a matter of finding a ton of custom code and have it check whether the username was a claims encoded username or not.

This is what we saw:

i:0#.w|POINTBIRD\tobiaszimmergren

However, what we really wanted our code to output was this:

POINTBIRD\tobiaszimmergren

There’s a good reason for why the username that is claims encoded look the way it does. The format tells us what type of claim it is. Wictor has done a nice breakdown and explained the claims here: http://www.wictorwilen.se/Post/How-Claims-encoding-works-in-SharePoint-2010.aspx

The solution to this problem

There’s a pretty simple solution for this that it looks like a lot of people are missing out on. The code snippets I’ve seen in the last project are all parsing the string manually with custom logic and then trying to determine on a string.split() if it is a claim and what type of claim it is.

Instead of going down that dark and horrible road, you should take a look at the built-in functions in the API that does this just fine for us:

private string GetUsernameFromClaim(string claimsEncodedUsername)
{
    using (new SPMonitoredScope("GetUsernameFromClaim method start"))
    {
        try
        {
            SPClaimProviderManager spClaimProviderManager = SPClaimProviderManager.Local;
            if (spClaimProviderManager != null)
            {
                if (SPClaimProviderManager.IsEncodedClaim(claimsEncodedUsername))
                {
                    // return the normal domain/username without any claims identification data
                    return spClaimProviderManager.ConvertClaimToIdentifier(claimsEncodedUsername);
                }
            }
        }
        catch (Exception ex)
        {
            // You should handle any exceptions in here instead of ignoring them!
            // Logger.Log("An exception occured in the GetUsernameFromClaim() method");
            return claimsUsername; // Or just return the original username.
        }

        // Return the original username value if it couldn't be resolved as a claims username
        return claimsUsername;
    }
}

Summary

Since I saw so many places in the previous few projects where people have been referencing custom methods for string-splits to sort out the claims usernames into default domain\username formats, I thought you’d benefit from knowing that there’s a built-in method for that. Nothing fancy, but worth to know about it.

Check out these resources for additional and more in-depth information about related things:

Programmatically converting login name to claim and vice versa, by Waldek Mastykarz

How claims work in SharePoint 2010, by Wictor Wilén

Enjoy this quick tip.

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"?

http://en.wikipedia.org/wiki/Dispose

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.

Zimmergren Sample Memory Consumption Chart

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:

image

Clicking the "SharePoint Dispose Check" menu item will bring up the SPDisposeCheck configuration menu like this:

image

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:

image

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!

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:
image

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.

Developer Dashboard example:
image

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;
image

Web Server, Events, DB Queries, Service Calls, SPRequests, Web Part Events on the right-hand side

image

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;

image

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:
image

If you click it, you’ll see the full ASP.NET Page Trace like this (awesome, very very awesome):
image

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:
image

Once that’s done, next time you’ll visit the Developer Dashboard awesomeness it’ll look something like this:
image

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:
image

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!

image

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!

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):

image

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:

image 

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:

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:

image

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!

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:

image

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:

image

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:

image

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!

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

  1. Add a reference to System.Management.Automation
    1. 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)
  2. Add a reference to System.Configuration.Installation

You should now have the following reference added: 
image

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:

  1. Deployed to the server (Using GACUTIL)
  2. Installed on the server (using INSTALLUTIL)

In this sample project I’m simply adding two lined in the Post-Build actions like this::

"C:Program Files (x86)Microsoft SDKsWindowsv7.0Abingacutil.exe" -if "$(TargetPath)" "C:WINDOWSMicrosoft.NETFramework64v2.0.50727InstallUtil.exe" "$(TargetPath)"

You’ll find the post-build events if you click project properties and go to this box:

image

5. Project overview

Your project should look something like this:

image

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:

image

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

Download this project here

Enjoy!

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:
image

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:
image

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:
image

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:
image

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:

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:
image

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

image

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:
image 

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

You can download my sample project here

Enjoy, and please don’t be afraid to leave comments!

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:

  1. Launch a cmd-window and navigate to C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14bin
    image
  2. Run the following command to utilize the SPMetal.exe tool with the following syntax:
    1. SPMetal.exe /web:http://yoursite /code:C:YourEntityFile.cs
    2. Example:
      image
  3. Now navigate to C: (or wherever you chose to output your file) and make sure the file has been generated:
    image
  4. Open up the file and take a look at the content that SPMetal now have provided us with:
    image
    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!

  1. Create a new project (I’m going to create a new Visual Web Part project)
  2. Import your DataContext-file by choosing your Project -> Add -> Existing Item:
  3. Specify your file (mine is called MyEntities.cs):
  4. Make sure it’s properly placed in your project structure – then we’re good to go:
    image

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:
image

In your code, reference the assemblies:
image

Ready to code?

What you should’ve done up until now is this:

  1. Generate your entities using the SPMetal.exe tool
  2. Reference the newly created file from your SharePoint project
  3. Make sure you’re using the proper references for System.Linq and Microsoft.SharePoint.Linq
  4. 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.

image

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:
image

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!

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:
image

In this sample database, I’ve added a table called ProductList which in theory will represent some products in this database, like this:
image

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:
image

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:

  1. Open the site you want to work with using SharePoint Designer 2010
  2. Select "External Content Types" in the left hand navigation:
    image
    Loading this page might take some time, be patient!
  3. Click to create a new External Content Type like this:
    image
  4. Click the link that reads: "Click here to discover external data sources and define operations":
    image
  5. Click "Add Connection"
    image
  6. Select "SQL Server" as your Data Source Type:
    image
  7. Enter the details about your connection to your SQL Server:
    image
  8. 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":
    image 

    You’ll be presented with a wizard-like dialog where you can specify the operations, elements and other properties for your BCS connection.

  9. Click "Next" to get to the Parameters page
  10. 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:
    image
  11. Click "Finish"
  12. You’ll be presented with a list of operations that your External Content Type can do, like this:
    image

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.

  1. Open your site and choose Site Actions - More Options…
    image
  2. Select the External List template, and click Create
    image
  3. Enter a name for your list, e.g. Product List
  4. You’ll see a field in this list called External Content Type, click the browse-button beside it:
    image

    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.

  5. Select your data source and click OK:
    image
  6. Now simply click the button called Create:
    image

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:
image

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:
image

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

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:

  1. Joins between lists
  2. Projected Fields
  3. 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:

  1. 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.
  2. 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

  1. Create a new Custom List named "ParentList"
  2. Create a new Coumn in that list as per the following settings:
    image 
  3. Add some sample items in the list like this:
    image

2. Create a child list

  1. Create a new Custom List named "ChildList"
  2. Create a new Column in that list as per the following settings:
    image
    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:
image

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:
image

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:
image 

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:
image

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!

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:   
ScreenShot001

 

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.

  1. Right click the “References” node and choose “Add Reference”  
    ScreenShot002
  2. Choose “Browse
    1. Navigate to this folder:
      C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14ISAPI
    2. Select these two files:
      1. Microsoft.SharePoint.Client.dll
      2. Microsoft.SharePoint.Client.Runtime.dll 

         ScreenShot004
  3. Make sure they are included in the references of your project: 
    ScreenShot005
  • Add the following using-statement in your class (note the last line!): 
    ScreenShot008

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..)

ScreenShot006

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:

Running the simple application

When you decide to run this awesomely simple application, it will look something like this: 
ScreenShot009

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

ScreenShot010

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

Download my awesome sample project here

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

Now after the SharePoint Conference 2009 is over, we’re free to publish and disclose a lot of content around SharePoint 2010.

The first thing that I’ll do is to link to these awesome Hands-On-Labs that I stumbled upon ;-)

SharePoint 2010 Hands On Labs

  • HOL01 – Developing a Visual Web Part in Visual Studio 2010
    This hands-on lab introduces the Visual Studio 2010 SharePoint development environment. It shows how to build a Visual Web Part using LINQ to SharePoint, and how to connect one Web Part to another Web Part on the page.
  • HOL02 – Developing a List Definition and Event Receiver in Visual Studio 2010
    This hands-on lab walks you through building a list definition for SharePoint 2010 in Visual Studio 2010. It also shows how to build an event receiver for the list in Visual Studio 2010 and deploy it to SharePoint. After the list and event receiver are deployed, you can use the developer dashboard to evaluate the performance of the event receiver.
  • HOL03 – Developing Advanced Web Parts for SharePoint 2010 with Visual Studio 2010
    This hands-on lab shows how to build a Web Part using several SharePoint-specific controls in Visual Studio 2010. Investigate advanced built-in Web Parts, including the Data View Web Part.
  • HOL04 – Developing with LINQ to SharePoint in Visual Studio 2010
    This hands-on lab explores a variety of LINQ queries on SharePoint 2010, going into more depth than the introductory hands-on lab. It also walks you through an exercise of creating a custom content type in Visual Studio 2010.
  • HOL05 – Developing for SharePoint 2010 with the Client OM and REST in Visual Studio 2010
    This hands-on lab introduces the Client object model for use in calling SharePoint 2010 APIs from a client machine. It also shows the use of ADO.NET Data Services to call REST services in SharePoint 2010.
  • HOL06 – Developing a BCS External Content Type with Visual Studio 2010
    This hands-on lab walks you through building an external content type for Business Connectivity Services using Visual Studio 2010. It also builds a form for Microsoft Outlook and shows the data being edited offline in Outlook.
  • HOL07 – Developing a SharePoint 2010 Workflow with Initiation Form in Visual Studio 2010
    This hands-on lab walks you through building a workflow in Visual Studio 2010 for SharePoint 2010. You add an initiation form to the workflow and use an external data exchange activity in the workflow.
  • HOL08 – Developing SharePoint 2010 User Interface with Silverlight in Visual Studio 2010
    This hands-on lab walks you through building Microsoft Silverlight applications for use in SharePoint 2010. You will access SharePoint 2010 data in Silverlight using the Client object model.
  • HOL09 – Developing SharePoint 2010 Sandboxed Solutions in Visual Studio 2010
    This hands-on lab walks you through building a Sandboxed Solution Web Part for SharePoint 2010. It will also add code to the Web Part that overloads the limits placed by the sandboxed solution, and you will review how the solution is shut down.
  • HOL10 – Developing SharePoint 2010 User Interface Ribbon and Dialog Customizations
    This hands-on lab walks you through adding a custom action to the SharePoint 2010 ribbon, and creating a Web Part that uses the Dialog Framework.

Download

Please visit http://www.microsoft.com/downloads/details.aspx?FamilyID=C010FC68-B47F-4DB6-B8A8-AD4BA33A35C5&displaylang=en#filelist to download the HOL for SharePoint 2010.

Enjoy :-)

SharePoint BDC Part 2: Creating your first BDC Web Part

July 25th, 2009 by Tobias Zimmergren

Author: Tobias Zimmergren
URL: http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In my previous article (SharePoint BDC Part 1: Getting started with the Business Data Catalog) I talked about what you’ll need to do in order to begin to work with the BCD in SharePoint (MOSS 2007 specifically, as it’s an Enterprise feature).

In this article I will briefly guide you through the process of creating your first BDC Web Part that will communicate with the BDC.

Note: You can download the source code for this sample project here [Download]

Prerequisites

You need to have your BDC set up and ready to use before you can start creating your own BDC Web Parts to communicate with the BDC. (See my previous article for a walkthrough)

We will also use Microsoft Visual Studio (2005/2008) to create the Web Part.

Enjoy!

What we had -> where we’re going

In the previous article I talked about using the built-in Web Parts for your BDC needs. Although they fill a lot of requirements, sometimes you just might want to write your custom Web parts instead.

This is what the standard BDC list looks like:

image

This is what the final result will look like: (Note, this is a custom Web Part which you’ll develop in the following steps)
image

Step 1 – Create a new Web Part project

I will expect that you already know how to create a new Web Part project (either using the VSeWSS or using WSPBuilder, or any other tool of preference).

See this article for a WSPBuilder complete walkthrough: WSPBuilder – Walkthrough of the Visual Studio Add-in

Step 2 – Add the BDC references to your project

Once you’ve got a Web Part project up and running, you should add some references that are needed for the BDC Object Model.

You should add the "Microsoft® Office SharePoint® Server component" reference to your project:
image

Once you’ve added this reference to your project, you have a GO for using the BDC namespaces.

Add the following using-statements to the top of your Web Part:

using Microsoft.Office.Server.ApplicationRegistry.MetadataModel;
using Microsoft.Office.Server.ApplicationRegistry.SystemSpecific.Db;
using Microsoft.Office.Server.ApplicationRegistry.Runtime; (if you need it..)

This is what my Visual Studio project looks like when using the WSPBuilder to create my Web Parts (notice the reference to microsoft.sharepoint.portal which comes from the reference we added):
image

Now we’re good to go! Let’s start coding then!

Step 3 – Utilize the BDC object model to access data

Note, you can download the complete Visual Studio Project at the end of this article with the source code.

Fetches all the LOB instances from the metadata repo:

var myInstances = ApplicationRegistry.GetLobSystemInstances();

 

Fetch the HR instance for Human Resources:

var humanRecourcesInstance = myInstances["HR"];

 

Pick out the Department entity from the HR instance:

var departmentEntity = humanRecourcesInstance.GetEntities()["Department"];

 

Fetches the method GetDepartments which is specified in our ADF file (Application Definition File) for our BDC connection:

var getDepartmentMethod = departmentEntity.GetMethods()["GetDepartments"];

 

Fetches the MethodInstance DepartmentFinderInstance:

var deptFinderInstance =
      getDepartmentMethod.GetMethodInstances()["DepartmentFinderInstance"];

 

We call the departmentEntity.Execute() method to fetch DbEntityInstance’s:

var foundEntities = 
     (DbEntityInstanceEnumerator)departmentEntity.Execute(
                                                                          deptFinderInstance, 
                                                                          humanRecourcesInstance);

 

Simply loop the DbInstances and then shoot out their name in a bunch of literal controls.
In a real scenario, we would most likely add those intances to an SPGridView instead of printing Literals to enable Views, Sorting, Paging and a whole set of awesome features that comes with the Grid View.:

while (foundEntities.MoveNext())
{
    var currentDepartment = (DbEntityInstance)foundEntities.Current;
    Controls.Add(new Literal{Text =
              "<div style=’border-bottom:1px dashed #c0c0c0; width:100%;’>"});

    Controls.Add(new Literal {Text =
              currentDepartment.GetFormatted("Name")+ "<br/>"}); 

    Controls.Add(new Literal { Text=
currentDepartment.GetFormatted("DepartmentID").ToString() }); 

    Controls.Add(new Literal{ Text = "</div>" });
}

When you’ve written the aforementioned code, you will have the base set up for retreiving data from your BDC connection. You will (of course) have to dig a whole lot deeper if you want to master the arts of BDC and the object model that comes with that. But at least it’s a start for you to get to know the namespace, and learn what namespaces to use – and see that it actually works!

Step 4 – Finalize and deploy your Web Part

Once you’ve created the project, build it and deploy to your SharePoint development machine and add your Web part to see the action:

image
(Yes, the Web Part is called SharePointRules BDC Web Part – and for a good reason too!)

Step 5 – May your creation shine upon SharePoint! (aka. Final result)

This is what the creation looks like (wow..), which basically only utilize the most basic aspects of the BDC Object Model to get started – but here you have it in action, fetching data immediately from your back-end SQL server (Adventure Works database in this case) using the BDC:

image

Summary

That’s a wrap for this article. I have walked you through the few simple steps needed to create your own first BDC Web Part.

In my next BDC article I will talk about what alternative tools I find suitable to use for generating your ADF (Application Definition File).

 

Author: Tobias Zimmergren 
URL: http://www.zimmergren | http://www.tozit.com

Introduction

Sometimes the only option you’ve got is to alter things using the object model of SharePoint. In this particular case I wanted to change the RSS-settings for a specific list.

So that’s what this little tip is about – customizing the RSS settings of any SPList object using the SharePoint API.

Problem

Today I wanted to change and/or customize the RSS settings for a specific list that exist on my site though the API. I found that this wasn’t as obvious as you’d like it to be, and hence I’m writing it down.

The SPList object has a .EnableSyndication property which you can use to turn on RSS for the list, but there’s no obvious property to access if you want to change the RSS settings itself.

Get it working

On your SPList objects, you’ve got the RootFolder property that contains a collection called "Properties" in which you’ll find all sorts of useful information for the list itself.

In my case I wanted to fetch all the settings related to RSS, and made a simple console application to iterate the items in the Properties collection and ended up with the following:

imagee

 

 

 

 

 

 

 

 

This is the code  to list the properties:

imagee

Alrighty, so we have the code to see the properties (or use the SharePoint Manager tool from CodePlex). Now we want to alter those properties. Simple:

imagee 

Conclusion

In order to accomplish the simple task of reading, changing or setting the properties in regards to RSS settings for your list (or any other property, for that matter) – all you need to do is utilize the RootFolder.Properties collection and access the vti_rss_ properties:

vti_rss_DayLimit
vti_rss_DisplayOnQuickLaunch
vti_rss_DisplayRssIcon
vti_rss_LimitDescriptionLength
vti_rss_ChannelTitle
vti_rss_ItemLimit
vti_rss_ChannelDescription

I’d like to shout out a thanks to Andrew Burns for being quick on twitter and pulling an answer out of his sleeve for this.

Enjoy.

Author: Tobias Zimmergren
URL: http://www.zimmergren.net | http://www.tozit.com 

Introduction

In this article I will guide you through the very basics of getting started with Business Data Catalog, BDC:

  1. Install the AdventureWorks 2008 Sample Databases
    1. We will use this database as our example for retrieving data using the BDC.
  2. I will step you through the simple process of creating your ADF (Application Definition File)
    1. We will use this file as our import connection
  3. I will guide you through how we can import this ADF file and create our BDC Application
  4. Lastly, I will guide you through the process of creating a basic site and use some of the basic BDC Web Parts

Install the AdventureWorks sample database

  • You’ll need to go and download the AdventureWorks sample databases
    image
  • Just finish the installation by clicking next a couple of times and let the installer do it’s normal Microsoft-installer magic.
  • You should now see a couple of new databases in your SQL Server Management Studio:
    image
    AdventureWorks, AdventureWorks2008, AdventureWorksDW, AdventureWorksDW2008, AdventureWorksLT, AdventureWorksLT2008

Alright – We’ve got our databases, now we need to start thinking about how we will get data from our SQL server into SharePoint. This is done by creating/generating an Application Definition File (ADF) as you will see in the next section.

Creating the ADF (Application Definition File)

Alright, there’s a few different options to create your ADF (Application Definition File). I will show you how to get started with using the free tool called "Application Definition Editor" that comes with the latest SharePoint Server SDK.

Note: See the bottom section in this article for a summary of links to all resources mentioned in the article.

After you have installed the latest SDK, you can choose to install the "Microsoft BDCTool" located here by default: "C:Program Files2007 Office System Developer ResourcesToolsBDC Definition Editor". Which will give you the following item in your Start Menu:
image

Launch the BDC Application Definition Designer

Click the application and launch the editor. You will see an interface like this:
image

Create or import your ADF file

There’s basically two alternatives when it comes to editing an ADF (Application Definition File).
One is to create a new one (which I will guide you through first), and the other is to import an existing one (which I will show you after the first alternative).

Alt 1) Creating our own ADF file
Now we’re going to connect to our newly created sample-databases and create an ADF file for use with those databases.
  • Click on ADD LOB System
  • Choose Connect To Database
  • You will see a nice popup-dialog where you will be able to enter the connection details to your desired database
    • Enter your connection details, example:
       image
  • You are presented with the "Designer Surface" that looks something like this:
    image
  • In our case, we’re going to use the table called "vEmployee" which exist in the AdventureWorks database in order to pull out some information about our employees.
    • Search for the table called vEmployee and drag it out to the Design Surface
    • Search for the table called vEmployeeDepartments and drag it out to the Design Surface
    • It should look something like this:
      image
    • Make any necessary changes, then click OK
    • You’ll see a view similar to this one after some tweaking:
      image 
    • After you’ve done the necessary changes to your configuration, making sure it’s a valid ADF with proper filters, enumerators and methods or whatever you need in your application then smile, because we’re done with that part!
Alt 2) Importing an existing ADF file

If you don’t want to do everything from scratch or you’ve already got an ADF file that you wish to modify, you can do so by importing an existing ADF file into the Definition Editor. Here’s how:

  • Open the BDC Definition Editor tool, then click the "Import" button in the menu:
    image
  • Browse to your existing ADF file and choose to import it. Simple as that.
    (I am importing a file called BDCAWDW.xml, which contains definitions for Product, Reseller, ProductSubcategory, ProductCategory as shown below)
  • You’ll see the imported ADF file’s structure immediately in the designer, under the prerequisite that your SQL connection string in the ADF file is valid:
    image 

Note: I will not detail how you create filters, finders, methods etc. in this article. You can read more about that here:
http://msdn.microsoft.com/en-us/library/ms145931(SQL.90).aspx

I may cover the topic of ADF-functionality in another article later on.

Generate the ADF file from the designer

I really don’t need to tell you this, but there’s a button called "Export" which you use to export the definition you’ve created using the definition editor to an xml file:
image

Import the ADF file

If we have gotten this far, we might as well get the last few bits in place.
What we now need to do is to import our ADF file into SharePoint, since that’s where it should reside. Follow along with these few simple steps to make sure you’re properly importing your file into SharePoint.

  • Navigate to your Shared Services Provider Administration site (You can access your SSP through Central Administration)
  • You are presented with a section called "Business Data Catalog" where you’ll find a bunch of different alternatives.
  • Make sure you have the permissions to modify the BDC (See the link Business Data Catalog permissions)
  • Click "Import application definition"
    image  
  • Browse for your .xml file and click "OK":
    image
  • You’ll see a progress bar (You don’t see that a lot in SharePoint. I love it!), telling your how the import process is going:
    image
  • When it’s done, you’ll click "OK" and be presented with an overview of your imported BDC Application:
    image
Configure permissions on the BDC Application Definition

In order for all users to be able to select/read data from your BDC Application, you’ll need to make sure they’ve got the appropriate permissions to actually do so.

Usually I do this setting on each of the imported entities, in case you want specific permissions on different entities – instead of on the entire application.

  • Select the DropDown list on your first entity and choose "Manage Permissions":
    image 
  • Choose "Add Users/Group":
    image
  • Enter "NT AUTHORITYAUTHENTICATED USERS" and choose "Select in Clients":
    image
  • Repeat these steps for the other entity as well.
  • You’re done.

Now we have created or imported an ADF file with the Business Data Catalog Definition Editor tool, exported it to an .xml file, imported it into SharePoint, set basic permissions on the entities.

Next, we should make sure that the application works in SharePoint by adding a Business Data Catalog-WebPart to a page.

Use the basic built-in BDC Web Parts

Awesome. Now that we have gotten this far by importing an ADF file into SharePoint and set appropriate permissions on the entities – We’re ready to actually use the ADF connection to view stuff in our database.

Note: I have created a new blank site where I can easily show the built-in BDC Web Parts – so that’s where I am adding my Web Parts.

 

  • Add two Web Parts to your page called "Business Data List" and "Business Data Item":
    (Note that when you’ve configured a BDC application, you’ll see the Business Data web parts)
    image
  • Choose to edit the properties of the Business Data List Web Part:
    image
  • Click the Browse-icon to the right to pop up the BDC entity chooser:
    image
  • It will present you with the following interface (note, BDC applications will of course vary depending on what you have imported..):
    image 
  • Double click the "Employee" type, and then click "OK" in your Web Part property window.
  • Repeat this process for the "Business Data Item" Web Part, and select "Employee" in the BDC Type Picker as well.

Now we’ve got one BDC List Web Part which will list all employees, and one BDC Item Web Part that will display details about the employee we select.

In order for this to work we must connect the two Web Parts.

  • Edit menu of your Web Part -> Connections -> Send Selected item To -> Employee
    image

Test our BDC Application out, and make sure it works!

  • Choose "LastName" then "contains" and enter "smith":
    image
  • Select one of the results by clicking the radiobutton to the left, and see that the result (details) about the Employee shows up in the connected Web Part:
    image 

Resources and links

Summary

This article is a basic step-by-step guide to getting started with BDC in MOSS 2007. I’ve shown you every step from creating the databases required (in our case some sample databases) to creating the ADF file and to finally utilize the BDC connection from a site, using the BDC Web Parts.

In an upcoming post I will talk about how you can create your own BDC Web Parts! Keep your eyes open!