jeudi 21 avril 2011

Working with SharePoint Objects


This article shows how to work with SharePoint objects in order to retrieve, update and persist their properties, moreover how to create, delete or dispose SharePoint objects.

I-                   Retrieve properties

To retrieve a property is similar like with any .NET object. For example to retrieve properties for list and list collection:

SPWeb  myWeb = SPContext.Current.Web;
String title = myWeb.Title;  // simple property
SPListCollection listCollection = myWeb.Lists; // collection property

II-                Updating and persisting properties

To update a property is similar like with any .NET object. For example to update properties for a Web:

SPWeb myWeb = SPContext.Web;
myWeb.title = “My updated Title”;  
myWeb.Update();  // to persist changes

III-             Creating SharePoint Objects
To create a SharePoint object, we can instantiate a new object or add a object to a collection. Example:

SPSite  mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.AllWebs.Add(‘’myProjectFolder ‘’) ;


IV-             Deleting SharePoint Objects
To delete a SharePoint object, we call the function Delete(). The Delete() method sends some objects to the recycle bin (as SPList) and delete other permanently (as SPSite). To ensure that the object will be sent to recycle bin, use the method Recycle().

Example:  
SPWeb  myWeb = SPContext.Current.Web;
myWeb.Delete(); //

V-                Disposing SharePoint Objects
To dispose a SharePoint object, call the Dispose() method. It ensures that the object is destroyed and release data correctly. Only SPSite and SPWeb objects support the dispose functionality. The other objects are managed by the garbage collector. If you set an object variable to a existing instance that you did not create, do not dispose this object, for example SPWite.Current.Web.  
You have 3 approaches to dispose objects:
-          With try-catch-finally block
-          With foreach loop
-          With the “using block”. When a using-block has completed execution, the object will be dispose automatically. Remind not to dispose instance that your code did not create.

Example:
Using (SPSite mySite = new SPSite(http://sharepoint))
{
}



Aucun commentaire:

Enregistrer un commentaire