Nick Grattan's Blog

About Microsoft SharePoint, .NET, Natural Language Processing and Machine Learning

Introducing the SharePoint object model

with 24 comments

As an alternative to programming against the SharePoint web services you can use the SharePoint object model. The object model can be used when the application will run on the server where SharePoint is installed (such as a console or WinForm application) or in assemblies that are run within a site (such as a Web Part).  

This sample shows how to display the sites and sub sites within a site collection as a hierarchy in a tree view control within a WinForm application.

Treeview

First, you will need to create a reference to “SharePoint.dll” assembly in your Visual Studio 2005 project. This is located at:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll

A recursive function nicely solves the problem of loading the site hierachy into a tree view control. The method below is passed the tree node into which the site list will be loaded, and a SPWeb object representing the site whose sub-sites will be loaded:

       private void FillSubWeb(TreeNode tn, SPWeb webSite)

        {

            foreach (SPWeb theWeb in webSite.Webs)

            {

                TreeNode subTN = new TreeNode(theWeb.Name);

                tn.Nodes.Add(subTN);

                FillSubWeb(subTN, theWeb);

            }

        }

This method iterates over the “Webs” collection which returns each sub-site. A new TreeNode object is created with the site name. The node is added to the tree view  control. Lastly, the FillSubWeb method is called recursively, passing the TreeNode and theWeb object to load the sub-sites for the current site.

The following code kicks off the loading of the sites:

           

      SPSite site = new SPSite

           (“http://moss2007:8100/sites/intranet”);

      SPWeb rootWeb = site.AllWebs[0];

 

      TreeNode tn = new TreeNode

            (“http://moss2007:8100/sites/intranet”);

      tvSites.Nodes.Add(tn);

      FillSubWeb(tn, rootWeb);

The code gets a reference to the site collection from the URL, and then obtains a reference to the top-level web (site) for the site collection. A tree node is created and added to the tree view control to represent the site collection, and then the FillSubWeb method is called to start the recursive process.

 

About these ads

Written by Nick Grattan

August 10, 2007 at 4:01 pm

24 Responses

Subscribe to comments with RSS.

  1. How can I use the above code in windows application?
    where do I have to write the code…..? in Page_load event handler?

    Developer

    November 7, 2007 at 8:19 pm

  2. It’s really up to you! The Page_load event handler makes sense if you want the list displayed by the time the form is displayed. If you wanted to fill the list after the user had entered the site URL you might do it in click event for a button. Nick.

    nickgrattan

    November 16, 2007 at 2:12 pm

  3. i tested your code and new spsite never works in windows application. i am able to use the same code in web application or console application but windows application always error out by saying that web application not found at URL etc. while it is the same line of code that works in my web app. any idea what i am missing

    test

    January 18, 2008 at 10:36 pm

  4. I have a question. I’ll post my code below, just to make sure i’m doing this right. I’m curious on where the “tvSites” came from…it wasn’t declared anywhere above so i’m not sure. i tried using “tnSites.Nodes.Add(tn)” but that didn’t work either. Any help please?

    SPSite site = new SPSite(“http://moss2007:8100/sites/intranet”);
    SPWeb rootWeb = site.AllWebs[0];

    TreeNode tn = new TreeNode(“http://moss2007:8100/sites/intranet”);

    // Where are you getting “tvSites” from?
    tvSites.Nodes.Add(tn);

    FillSubWeb(tn, rootWeb);

    private void FillSubWeb(TreeNode tn, SPWeb webSite)

    {

    foreach (SPWeb theWeb in webSite.Webs)

    {

    TreeNode subTN = new TreeNode(theWeb.Name);

    tn.Nodes.Add(subTN);

    FillSubWeb(subTN, theWeb);

    }

    }

    Ken

    February 26, 2008 at 3:10 am

  5. TreeNode tn;
    shd be declared as >> TreeNode tvSites

    anil

    June 11, 2008 at 1:45 am

  6. Thanks for the post. I found a list of code snippets that can be made use of:
    http://sharepointobjectmodel.blogspot.com/

    Rags

    October 13, 2008 at 12:05 pm

  7. […] SharePoint Object Model allows external applications or hosted WebParts to query, modify and create the content which is […]

  8. […] are different ways to retrieve list data with the SharePoint Object Model. It provides mechanisms to specifically query the data that you really need in your use case. Its […]

  9. […] Items There are multiple ways to iterate through the items of a SharePoint list by using the SharePoint Object Model. One approach – which I’ve seen before in a real life SharePoint Application – may work fine […]

  10. […] you need can take a lot of pressure of the SharePoint Content Database. Additionally to that the SharePoint Object Model provides additional features to enhance access to list […]

  11. […] SharePoint对象模型(Object Model)允许外部应用程序或托管的WebPart来查询、编辑和创建存储在SharePoint内容数据库(Content Database)中的内容。有很多博客文章、知识库文章和最佳实践中,都谈到如何在不同的用例场景中使用对象模型。 […]

  12. […] Nick Grattan: “As an alternative to programming against the SharePoint web services you can use the SharePoint object model. The object model can be used when the application will run on the server where SharePoint is installed (such as a console or WinForm application) or in assemblies that are run within a site (such as a Web Part).” Okay, this does not sound like ‘bypassing’ SharePoint and more like tight coupling from the 1990s… This is not a superior loose-coupling option over SharePoint Web Services. […]

  13. So this Example that is shown above dose not work.
    I wrote a code that works Great Check this:

    protected void Page_Load(object sender, EventArgs e)
    {
    if(!IsPostBack)
    {
    //Get All My Sites And Sub Sites
    SPSite Site = new SPSite(“Your URL”);
    SPWeb rootWeb = Site.AllWebs[0];//Main Root
    TreeNode tn = new TreeNode(“All SharePoint Sites”);
    Trv.Nodes.Add(tn);
    FillSubWeb(tn, rootWeb);
    }
    }
    private void FillSubWeb(TreeNode tn, SPWeb webSite)
    {
    int WebCount = 0;
    foreach (SPWeb theWeb in webSite.Webs)
    {
    TreeNode subTN = new TreeNode(theWeb.Title);
    tn.ChildNodes.Add(subTN);
    //GetChilds(theWeb);
    SPNavigationNodeCollection qlNodes = theWeb.Navigation.QuickLaunch;
    foreach (SPNavigationNode node in qlNodes)
    {
    TreeNode SubTn = new TreeNode(node.Title);
    tn.ChildNodes[WebCount].ChildNodes.Add(SubTn);
    }
    WebCount++;
    FillSubWeb(subTN, theWeb);
    }
    }

    Nir

    October 27, 2009 at 2:53 pm

  14. Hello Nick,
    I Have developed a windows application to create site.
    I need to give the site template code as one of the parameter. For all templates it is going well but i have downloaded some templates from Microsoft. My question is HOW CAN I GIVE THE SITE TEMPLATE CODE FOR THOSE TEMPLATES. (OR) IS THERE ANY WAY TO FIND OUT THE SITE TEMPLATE CODE FOR THOSE DOWNLOADED TEMPLATES.
    SORRY IF MY QUESTION IS A STUPID ONE……..

    THANKS IN ADVANCE
    KAMUJU.SATISH
    HYDERABAD
    INDIA.

    Kamujusatish

    November 24, 2009 at 2:10 pm

    • You should create a SharePoint Solutions Package (WSP) and deploy with STSADM. Nick

      Nick Grattan

      November 24, 2009 at 2:39 pm

  15. HELLO NICK
    IS THERE ANY WAY TO INTEGRATE PEOPLE SOFT WITH SHAREPOINT

    Kamujusatish

    November 24, 2009 at 2:13 pm

    • Don’t know PeopleSoft … If it provides a Web Service you might try calling this from InfoPath or forms created with SharePoint Designer. You also be able to create a Business Data Catalog (BDC) to access the database directly or to call into web services. Creating custom Web parts may allow you to call into an API if one exists. Nick.

      Nick Grattan

      November 24, 2009 at 2:41 pm

  16. Hi, I found this article while searching for help with Microsoft Silverlight. I have recently changed internet browser from Opera to Microsoft IE 6. After the change I seem to have a problem with loading websites that use Microsoft Silverlight. Every time I go on a page that needs Microsoft Silverlight, the site doesn’t load and I get a “npctrl.dll” error. I cannot seem to find out how to fix the problem. Any help getting Microsoft Silverlight to function is greatly appreciated! Thanks

    Johnson Desanti

    March 7, 2010 at 3:19 am

  17. Hi,
    How can achieve the same tree view in client object model? I want to show all the documents only to select one of the document folder so that people can save thier outlook attachments to sharepoint site.

    using (var ctx = new SP.ClientContext(siteURL))
    {
    ctx.Load(ctx.Web);
    ctx.Load(ctx.Web.Lists);
    ctx.AuthenticationMode = ClientAuthenticationMode.Default;
    ctx.ExecuteQuery();
    TreeNode node = new TreeNode(siteURL);
    foreach (SP.List list in ctx.Web.Lists)
    {
    if (list.BaseTemplate == 101)
    {
    node.Nodes.Add(list.Title);
    }
    }
    treeView1.Nodes.Add(node);
    treeView1.Show();
    }

    Im doing this.. it shows only documents. tel me a recursive function cal the same..

    Guruprasad marathe

    July 30, 2010 at 4:28 am

  18. Hi,
    I have created a web application and included Microsoft.Sharepoint.dll in the references.
    But when i try to access Sharepoint Site using
    SPSite spsite= new SPSite(“http://…”);
    it gives a Could not found web application at… error.

    The same thing works fine with a window app but fails for a web app.

    Can you provide with some solution on the same

    Dhaval Pandya

    October 27, 2010 at 5:30 am

    • Most probably this is a security error – SharePoint reports file not found if you don’t have permissions on the site. Ensure you’ve set authentication credentials before connecting to the site. Regards, Nick.

      Nick Grattan

      October 27, 2010 at 6:46 am

      • I have the same error when Targeted .Net FW is 3.5, target platform is Any Cpu and I am a farm admin.

        I have fixed this error in the past by adding my account (with dbo) to 2 of the content databases (configuration and ? [the main db]). I ‘m having trouble believing that this is a normal way to be able to do development.

        codepilgrimage

        July 8, 2011 at 3:59 pm

  19. Thank you for taking time to write this write-up. It’s been quite valuable. It couldn’t have come at a superior time for me!

    Homer Vanduyn

    September 14, 2011 at 11:58 am

  20. […] that you need can take a lot off pressure of the SharePoint Content Database. Additionally, the SharePoint Object Model provides additional features to enhance access to list […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 60 other followers

%d bloggers like this: