SharePoint 2007: Accessing a SharePoint List programmatically

17 December, 2010 | | 0 comments |

Share |
Microsoft SharePoint 2007 offers the best portal, collaboration and content management for an enterprise. Teams using a SharePoint portal can collaborate using Document libraries, lists, picture libraries, discussion boards, surveys, etc. Amongst those I mentioned, document libraries are the most used allowing a team to share documents(of Office 2003/07) and stay synchronized with the latest one allowing real-time collaboration. These lists and libraries can be accessed programmatically in C# using the SharePoint Object Model(SOM). Though SOM can also be used to access different entities like Workflows, Site Features, etc; in this post I'll be focusing on accessing lists/libraries using SOM.


Following will give you a quick gist of how we can access a SharePoint list present in a SharePoint site based on the hierarchy.


Hierarchy Class

• SharePoint Site Collection
(i.e. top-level or parent site)

SPSite

• SharePoint Site
(i.e. target or sub-site)

SPWeb

• SharePoint List under the target site

SPList

• List Items in the List

SPListItem


In my following example, I’m trying to access images in a Picture Library named ‘PictureLibrary1’ present at the URL http://ram2003svr:8080/PictureLibrary1. The List Items existing in the ‘PictureLIbrary1’ are ‘Name’, ‘Title’. I have used an ASP.Net website for this example, so make sure you have the following three libraries added as a reference to your project.


• Microsoft.SharePoint
• Microsoft.SharePoint.Security
• Microsoft.SharePoint.intl

You can copy the DLL’s from your GAC using this link Here.


CODE Snippet:


  • using System;
  • using System.Web;
  • using System.Web.UI;
  • using System.Web.UI.HtmlControls;
  • using System.Web.UI.WebControls;
  •  
  • using Microsoft.SharePoint;
  • using Microsoft.SharePoint.WebControls;
  • using Microsoft.SharePoint.WebPartPages;
  •  
  • public partial class Image_Library_Webpart_Default : System.Web.UI.Page
  • {
  •     
  •     /*
  •         We're trying to access a 'Picture Library' located at below URL.
  •         URL: http://ram2003svr:8080/PictureLibrary1
  •       
  •         The below process is similar for accessing a Document Library or Lists like 'Tasks','Announcements', etc.
  •     */
  •     
  •     protected void Page_Load(object sender, EventArgs e)
  •     {
  •  
  •         //SPSecurity.RunWithElevatedPrivileges() is mandatory since a user might not have sufficient privileges to access this list.
  •  
  •         SPSecurity.RunWithElevatedPrivileges(delegate()
  •         {
  •  
  •             //SPSite returns the Site Collection object for the URL
  •  
  •             using (SPSite spSite = new SPSite("http://ram2003svr:8080/"))    
  •             {
  •                 /* Returns the object of the site (takes relative site URL after the top-site) which we want to access.
  •                 In this case, it is BLANK since the site is a top-level site */
  •  
  •                 using (SPWeb spWeb = spSite.AllWebs[""])
  •                 {   
  •                     //Returns the List object for the Picture Library. Takes the List Name as an argument.
  •  
  •                     SPList spList = spWeb.Lists["PictureLibrary1"];
  •  
  •                     //Iterate through the SPListItems in the List.
  •  
  •                     foreach (SPListItem spListItem in spList.Items)
  •                     {
  •                         
  •                         //You can access the various attributes in the list like 'Name','Title'
  •  
  •                         Response.Write("Name of image file : " + spListItem["Name"].ToString() + "<br /><br />");
  •  
  •                         Response.Write("Title of image file : " + spListItem["Title"].ToString() + "<br /><br />");
  •  
  •                         Response.Write("URL of image file : " + "http://ram2003svr:8080/PictureLibrary1/" + spListItem["Name"].ToString() + "<br /><br />");
  •                         
  •                     }
  •  
  •                 }
  •             }
  •  
  •         });
  •  
  •     }
  • }






You can download the source code Here:





Source code for accessing a SharePoint 2007 List programmatically






SharePoint 2007: Creating WebParts using ASP.Net Web User Controls

10 December, 2010 | | 1 comments |

Share |
WebParts can be used as an add-on in MOSS (Microsoft Office SharePoint Server) 2007 or WSS (Windows SharePoint Services) 3.0. You can include ASP.Net functionality into SharePoint using Web Parts as well. Web Parts as developers know, does not have a front end when developed, we have to add controls to it dynamically for it to be displayed on SharePoint page. In such cases, to make the development effort easier and faster, ASP.Net Web User Controls (i.e. .ascx) can bear the Web Form layout. The Web Part can be made to use this Web User Control for displaying it on a SharePoint page. A matter of fact, developing, deploying and maintaining WebParts is one of the most tedious tasks for a SharePoint developer. Following steps will help you leverage a ASP.Net Web User Control with a Web Part.


Step 1: Creating the ASP.Net Web User Control


Create an ASP.Net web site and get your Web User Control (.ascx and .ascx.cs files) developed and tested as per your requirements. If you want your Web User Control to interact with SharePoint Object Model then you have to add references to the following 3 DLL’s:

• Microsoft.SharePoint
• Microsoft.SharePoint.Security
• Microsoft.SharePoint.intl

You can copy these three DLL’s from GAC using this link Here.


Keep the following points included in mind for certain cases:

◘ If you want to insert a custom JavaScript file specially for the ASP.Net User Control you can either use the <script></script> block in the .ascx file or use the following approach:

• Place an ASP.Net Placeholder in the section of the SharePoint Master page. Name it as per your convention.
• Use a Literal control (say 'Literal1') and add the <script src=" ... " type="text/javascript"></script> code for JavaScript or <link href=" ... " rel="Stylesheet" /> code for CSS to the ‘Literal1.Text’ attribute in the Page_Load event of the ASP.Net User Control.
• Access the Placeholder with the ID from the Page_Load event and add the Literal1 control to it.

◘ The JavaScript or CSS file so referenced in the Web User Control can either be a file visible in SharePoint 2007 Designer or in the ‘_layouts’ folder. Choosing the former option would be wiser.

◘ If you need to access a <ConnectionString> or <AppSetting> attribute from the Web User Control, make sure you make the required entry in the 'web.config' file.


Step 2: Placing the Web User Control in the '_layouts' folder


Place the ASP.Net Web User Control files (i.e. .ascx and .ascx.cs) in a folder created (name it wisely) in the ‘_layouts’ folder of your 12 hive where Microsoft SharePoint 2007 is installed. Place your JavaScript or CSS files here as well if you have chosen to reference them from your Web User Control here.

A majority of posts on the Internet will advice to keep the Web User Control files in the ‘_controltemplates’ virtual directory but believe me and my experience; I prefer the ‘_layouts’ virtual directory. In my example mentioned below, I have used a Web User Control named 'Photo_Gallery.ascx' placed in the folder 'PhotoGallery' in the '_layouts' folder.


Step 3: Creation of WebPart


Assuming you have your development environment ready, create a Web Part project in VS 2005/2008 using SharePoint Extensions for Visual Studio with the following code snippet:


  •  
  • using System;
  • using System.IO;
  • using System.Runtime.InteropServices;
  • using System.Web.UI;
  • using System.Web.UI.WebControls;
  • using System.Web.UI.WebControls.WebParts;
  • using System.Xml.Serialization;
  •  
  • using Microsoft.SharePoint;
  • using Microsoft.SharePoint.WebControls;
  • using Microsoft.SharePoint.WebPartPages;
  •  
  • namespace WP_PhotoGallery
  • {
  •  
  •     [Guid("c3417aa5-e282-42c8-a8b8-769d1f66af31")]
  •     public class SogetiPhotoGallery : System.Web.UI.WebControls.WebParts.WebPart
  •     {
  •  
  •         Control c;              //Variable for the Web Part Control
  •         String err;             //Will store the Exception
  •  
  •         public SogetiPhotoGallery()
  •         {
  •             /* Will allow to export the WebPart. Not mandatory. */
  •  
  •             this.ExportMode = WebPartExportMode.All;
  •         }
  •         
  •         protected override void Render(HtmlTextWriter writer)
  •         {
  •             
  •             /* SPSecurity.RunWithElevatedPrivileges block is required to run the Web Part with additional privilegs.
  •              * This BLOCK is recommended to avoid user authentication/authorization issues. */
  •  
  •             SPSecurity.RunWithElevatedPrivileges(delegate()
  •             {
  •  
  •                 try
  •                 {
  •                     /* Render the Web User Control */
  •                     
  •                     c.RenderControl(writer);
  •                 }
  •  
  •                 catch (Exception e)
  •                 {
  •                     /* Store the Exception in 'err' is any */
  •                     
  •                     writer.Write(e.Message + " : " + err);
  •                 }
  •         
  •             });
  •             
  •         }
  •  
  •         protected override void CreateChildControls()
  •         {
  •  
  •             SPSecurity.RunWithElevatedPrivileges(delegate()
  •             {
  •                 
  •                 //Create all associated child controls necessary for display //
  •                 
  •                 base.CreateChildControls();
  •                 
  •                 try
  •                 {
  •  
  •                     this.Controls.Clear();
  •                     
  •                     //Load the Web User Control (.ascx) and add it to the Page. //
  •  
  •                     c = this.Page.LoadControl("~/_layouts/PhotoGallery/Photo_Gallery.ascx");
  •                     this.Controls.Add(c);
  •                 }
  •                     
  •                 catch (Exception e)
  •                 {
  •                     err = e.Message;
  •                 }
  •                 
  •             });
  •             
  •         }
  •  
  •     }
  •  
  • }


Step 4: Deployment of Web Part, populating it in Web Part Gallery and using a Web Part page to display the Web Part on a SharePoint page


Make sure you follow the required steps for deployment of Web Part. If you face any issues, please post it in the comments section.

As a reference for beginners, you can learn how to create, deploy and install Web Parts using this article Here.






You can download the source code Here:





Source code for Creating WebParts using ASP.Net Web User Controls in SharePoint 2007