Tuesday, September 29, 2009

SharePoint object Model



SharePoint ObectModel Code Samples

SPSite and SPContext SPSite:
Represents a collection of sites in a Web application, including a top-level Web site and all its subsites. Each SPSite object, or site collection, is represented within an SPSiteCollection object that consists of the collection of all site collections in the Web application.
To instantiate an SPSite object for a specific site collection on an ASP.NET page, or for a specific site collection within a console application, use the SPSite constructor as follows:
SPSite oSiteCollection = new SPSite("Absolute_URL");
Within an ASP.NET application, you can use the Site property of the SPContext class to return an SPSite object that represents the current site collection, as follows:
SPSite oSiteCollection = SPContext.Current.Site;
If you create your own SPSite object, you can use the Dispose method to close the object. You can also instead implement a using statement so that the .NET Framework common language runtime (CLR) automatically releases the memory that is used to store the site collection as follows:
using (SPSite oSiteCollection = new SPSite("Absolute_URL")
{ ... }
However, if you have a reference to a shared resource, such as when the object is provided by the GetContextSite method in a Web Part, do not use either method to close the object. Using either method on a shared resource causes an Access Violation error to occur. In scenarios where you have a reference to a shared resource, instead let Windows SharePoint Services or your portal application manage the object.
Note:- Some Important properties are AllWebs ,WebApplication ,Owner etc



SPContext :-Represents the context of an HTTP request in Windows SharePoint ServicesUse the SPContext class to return context information about such objects as the current Web application, site collection, site, list, or list item.The following examples illustrate how to use properties of the SPContext class to return the current list, site, and site collection.SPList oListCur = SPContext.Current.List;SPWeb oWeb = SPContext.Current.Web;SPSite oSite = SPContext.Current.Site;SPWebApplication oWebApplicationCur = SPContext.Current.Site.WebApplication;Cast the value of the Item property as an SPListItem object to return the current list item follows:SPListItem item = (SPListItem)SPContext.Current.Item;

Properties:-

  1. Current Gets the context of the current HTTP request in Windows SharePoint Services.
  2. Fields Gets the fields metadata associated with the item or content type of the Windows SharePoint Services context.
  3. File Gets the file that is associated with the list item object of the given Windows SharePoint Services context.
  4. Item Gets either the SPListItem object that is determined by the given list and item ID, or the SPItem object that is set when the SPContext object is created.
  5. ItemId Gets the ID of the item that is associated with the Windows SharePoint Services context.
  6. List Gets the list that is associated with the Windows SharePoint Services context.
  7. ListId Gets the GUID of the list that is associated with the Windows SharePoint Services context
  8. ListItem Gets the list item associated with the Windows SharePoint Services context.
  9. ListItemServerRelativeUrl Gets or sets the server-relative URL for the list item in the current HTTP context of Windows SharePoint Services.
  10. Site Gets the site collection that is associated with the Windows SharePoint Services context.
  11. SiteFeatures Gets the activated site collection features of the Windows SharePoint Services context.
  12. Web Gets the Web site that is associated with the Windows SharePoint Services context.
  13. WebFeatures Gets the activated site features of the Windows SharePoint Services context.

SPSiteDataQuery How we can use SPSiteDataQuery SPSiteDataQuery object is used to perform the crosslist queries. As we have seen before that SPQuery is used to perform the query on a single list at a time, what if We want to run the same Query on multiple list on the websites in the site collection ? SPSiteDataQuery solves this purpose .It runs the query on multiple list and give all the results merged in a datatable. We Use SPWeb.GetSiteData(SPSiteDataQueryObj) to get the final Datatable.Properties :-

  1. Lists Gets or sets the inner XML that specifies which lists to include in the query.
  2. Query Gets or sets the inner XML that defines the query.
  3. RowLimit Gets or sets a limit for the number of items in the query that are returned per page.
  4. ViewFields Gets or sets the inner XML that describes the view fields used in the query.
  5. Webs Gets or sets the inner XML that specifies which Web sites to include in the query as specified by the Scope attribute on the Webs tag in the query. By default, the query considers the current Web site, that is, the Web site from which the GetSiteData method was invoked.

Note: Webs Possible values of the Scope attribute include Recursive and SiteCollection. When the Scope attribute is set to Recursive, the query considers all Web sites that are descended from the current SPWeb object. For example: When the Scope attribute is set to SiteCollection, the query considers all Web sites that are in the same site collection as the current Web site. Lists Attributes Supported optional attributes for the Lists tag include the following:

  • ServerTemplate -- Limits the query to lists of the specified server template. Example: <Lists ServerTemplate="104" />
  • BaseType -- Limits the query to lists of the specified base type. Example: <Lists BaseType="1" /> The following table lists possible values for the default base types. Value Description 0 Generic list 1 Document library 3 Discussion forum 4 Vote or Survey 5 Issues list
  • Hidden -- Determines whether the query will include hidden lists. Example: <Lists Hidden = "TRUE />By default, the query will consider all non-hidden lists of base type 0.· MaxListLimit -- Limits the query to the total number of lists specified. If the query would exceed the limit, the query will instead fail and raise an SPException. By default, the limit is 1000. When set to 0, there is no limit to the number of lists that will be considered. Example: <Lists MaxListLimit="500" />
  • Lists Subelements Possible subelements of the Lists tag include List and With Index. · The List tag allows the query to include specific lists, instead of returning all lists of a particular type. The ID attribute identifies each list. Example: <Lists> <List ID="7A9FDBE6-0841-430a-8D9A-53355801B5D5" /> <List ID="3D18F506-FCA1-451e-B645-2D720DC84FD8" /></Lists> Code Snipet Example :- SPWeb oWebsite = SPContext.Current.Web; SPSiteDataQuery oQuery = new SPSiteDataQuery(); string strWhere = "<Where><Gt>" + "<FieldRef Name=\"ID\" />" + "<Value Type=\"Number\">1</Value>" + "</Gt></Where>"; string strOrderBy = "<OrderBy><FieldRef Name=\"FileRef\" /></OrderBy>"; oQuery.Query = strWhere + strOrderBy; oQuery.Lists = "<Lists ServerTemplate=\"101\" />"; oQuery.ViewFields = "<FieldRef Name=\"Title\" />"; DataTable dtResults = oWebsite.GetSiteData(oQuery);

SPQuery What is SPQuery SPQuery class is used to instantiate objects which can are used to query the list and document libraries. The Query is prepared using a xml language called CAML.The Query returns all the records from the list which meets the criteria.Public Properties :-

  1. Folder Microsoft.SharePoint.SPFolder
    Gets or sets the folder within a document library from which to return items in the query.
  2. ListItemCollectionPosition Microsoft.SharePoint.SPListItemCollectionPosition
    Gets or sets an object that is used to obtain the next set of rows in a paged view of a list.
  3. Query String Gets or sets the inner XML used in the query.
  4. RowLimit UInt32 Gets or sets a limit for the number of items returned in the query per page.
  5. ViewAttributes String Gets or sets the attributes of the view used in the query.
  6. ViewFields String Gets or sets the fields that are displayed in the query. Code Snippet example:- //****** SPQuery Example and Adding Atachments to List Item********// SPSite site = new SPSite("http://gpchbs-s6137:92"); SPWeb web = site.OpenWeb(); SPQuery query = new SPQuery(); SPList dlist=web.Lists["Dlist"]; SPListItemCollection collection = null; SPListItem item = null; query.Query = "" + "" + "" + "0"+ ""+ ""+ "" + ""+ "" + ""+ ""; query.RowLimit = 10; //query.ViewFields = "" + // ""; query.ViewAttributes = "Scope=\"Recursive\""; collection = dlist.GetItems(query); if (collection != null) { if (collection.Count > 0) { dlist.EnableAttachments = true; dlist.Update(); for (int i = 0; i < collection.Count - 1; i++) { item = collection[i]; byte[] barr1 = File.ReadAllBytes("C:\\Arijit\\PracticeDemos\\backupkmlist.txt"); byte[] barr2=File.ReadAllBytes("C:\\Arijit\\PracticeDemos\\Copybackupkmlist.txt"); item.Attachments.AddNow("backupkmlist.txt", barr1); item.Attachments.AddNow("Copybackupkmlist.txt", barr2); } for (int j = 0; j < item.Attachments.Count; j++) { Console.WriteLine("Leaf Name: " + item.Attachments[j]); } Console.ReadLine();}} //****** SPQuery Example With Forward only Pagination********// SPSite site = new SPSite("http://gpchbs-s6137:92"); bool nextPage = true; SPWeb web = site.OpenWeb(); SPQuery query = new SPQuery(); SPList dlist=web.Lists["Dlist"]; SPListItemCollection collection = null; SPListItem item = null; query.Query = "" + "" + "" + "0"+ ""+ ""+ "" + ""+ "" + ""+ ""; query.RowLimit = 2; //query.ViewFields = "" + // ""; query.ViewAttributes = "Scope=\"Recursive\""; while (nextPage) { collection = dlist.GetItems(query); if (collection != null) { if (collection.Count > 0) { Console.WriteLine("**********************"); Console.WriteLine("Title " + "\t" + "ID "); //dlist.EnableAttachments = true; //dlist.Update(); //for (int i = 0; i < collection.Count - 1; i++) //{ // item = collection[i]; // byte[] barr1 = File.ReadAllBytes("C:\\Arijit\\PracticeDemos\\backupkmlist.txt"); // byte[] barr2=File.ReadAllBytes("C:\\Arijit\\PracticeDemos\\Copybackupkmlist.txt"); // item.Attachments.AddNow("backupkmlist.txt", barr1); // item.Attachments.AddNow("Copybackupkmlist.txt", barr2); //} //for (int j = 0; j < item.Attachments.Count; j++) //{ // Console.WriteLine("Leaf Name: " + item.Attachments[j]); //} for (int i = 0; i < collection.Count; i++) { Console.WriteLine(collection[i].Title + "\t" + collection[i].ID); }} } if (collection.ListItemCollectionPosition != null) { if (!string.IsNullOrEmpty(collection.ListItemCollectionPosition.PagingInfo)) { query.ListItemCollectionPosition = collection.ListItemCollectionPosition; Console.WriteLine("Press Enter for Next Page..."); Console.ReadLine(); }else { Console.WriteLine("Last Page Reached"); Console.ReadLine(); }} else { nextPage = false; Console.WriteLine("Last Page Reached"); Console.ReadLine(); }}

SPDocumentLibrary

What is SPDocumentLibrary /What are the methods and properties of SPDocumentLibrary /How can we use SPDocumentLibrary SPDocumentLibrary represents the SharePoint document library lists.Properties:-

  1. CheckedOutFiles Gets the collection of files that are checked out of the document library.

Methods:-

  1. GetItemsInFolder Returns a collection of items from the document library based on the specified view and folder. Note:- All other properties are inherited from SPList. Some Code Snippets:- //*******code snippet which shows the uploading of document SPSite site = new SPSite("http://gpchbs-s6137:92"); SPWeb web = site.OpenWeb(); SPDocumentLibrary docLib1=null; SPDocumentLibrary docLib2=null; if ((web.Lists["Audio"].BaseType == SPBaseType.DocumentLibrary) && (web.Lists["Awards"].BaseType == SPBaseType.DocumentLibrary)) { docLib1 = (SPDocumentLibrary)web.Lists["Audio"]; docLib2 = (SPDocumentLibrary)web.Lists["Awards"]; } if (docLib1 != null && docLib2 != null) { docLib1.ContentTypesEnabled = true; SPFolder folder1 = docLib1.RootFolder.SubFolders.Add("FirstChild"); folder1.Item["Title"]= "FirstFolder1"; folder1.Item.Update(); folder1.SubFolders.Add("FirstSF"); folder1.Update(); docLib1.Update(); //Create the stream object to add a file FileStream fstream = new FileStream("C:\\KMLists.txt", FileMode.Open, FileAccess.Read); SPFile file1= folder1.Files.Add("KMLists.txt", fstream); folder1.Update(); fstream.Close(); file1.Item["Title"] = "KMDetails"; file1.Item.Update(); file1.Update(); folder1.CopyTo(docLib2.RootFolder.Url + "/" + folder1.Name+"_Copy"); docLib2.Update(); foreach (SPFolder folder in docLib2.RootFolder.SubFolders) { Console.WriteLine("Folder Names at root level :" + folder.Name); Console.WriteLine(folder.ServerRelativeUrl); Console.WriteLine(folder.Url); Console.WriteLine(folder.SubFolders.Count); foreach (SPFile file in folder.Files) { Console.WriteLine("File length is :" + file.Length.ToString()); Console.WriteLine(file.ServerRelativeUrl); Console.WriteLine(file.Url); Console.WriteLine(file.Name); } Console.ReadLine(); }} //********which shows downloading a document and displaying the versions SPSite site = new SPSite("http://gpchbs-s6137:92"); SPWeb web = site.OpenWeb(); SPFile file1 = web.GetFile("/Audio/FirstChild/KMLists.txt"); if (file1 != null) { byte[] barr = file1.OpenBinary(); FileStream fstream = new FileStream("C:\\Arijit\\PracticeDemos\\backupkmlist.txt", FileMode.CreateNew, FileAccess.Write); fstream.Write(barr, 0, Convert.ToInt32(file1.Length)); fstream.Close(); FileStream fstream2 = new FileStream("C:\\screenshot.doc", FileMode.Open, FileAccess.Read); file1.SaveBinary(fstream2); file1.Update(); fstream2.Close(); foreach (SPFileVersion ver in file1.Versions) { Console.WriteLine(ver.CheckInComment); Console.WriteLine(ver.CreatedBy.LoginName); Console.WriteLine(ver.ID.ToString()); Console.WriteLine(ver.VersionLabel); Console.WriteLine(ver.Url); Console.WriteLine(ver.Level.ToString()); } Console.ReadLine(); }

SPFolder And SPFile
SPFolder SPFolder class represents a folder in Sharepoint site.Public Methods :-The following table shows the public methods of the SPFolder class and a brief description of each.

  1. CopyTo Copies the folder and its contents into a new folder at the specified URL.
  2. MoveTo Moves the folder to the specified URL.
  3. ToString Returns the relative URL of the folder based on the parent Web site.Public Properties :-The following table shows the public properties of the SPFolder class, the data type of each property, and a brief description of each.
  4. ContainingDocumentLibrary System.Guid
    Gets the document library that contains the folder.
  5. Exists Boolean Gets a Boolean value that indicates whether the folder exists.
  6. Files Microsoft.SharePoint.SPFileCollection
    Gets the collection of all files contained in the folder.
  7. Name String Gets the name of the folder.
  8. ParentFolder Microsoft.SharePoint.SPFolder Gets the parent folder of the folder.
  9. ParentWeb Microsoft.SharePoint.SPWeb Gets the parent Web site of the folder.
  10. ServerRelativeUrl String Gets the server-relative URL of the folder.
  11. SubFolders Microsoft.SharePoint.SPFolderCollection Gets the collection of subfolders contained within the folder.
  12. Url String Gets the site-relative URL of the folder.

SPFile :- The SPFile class represents a file in a SharePoint Web site that can be a Web Part Page, an item in a document library, or a file in a folder.Public MethodsThe following table shows the public methods of the SPFile class and a brief description of each.

  1. CheckIn Checks in the file to a document library.
  2. CheckOut Checks out the file from a document library.
  3. CopyTo(String) Copies the file to the destination URL but does not overwrite an existing file of the same name.
  4. CopyTo(String, Boolean) Copies the file to the destination URL but overwrites an existing file of the same name only if bOverwrite is true.
  5. MoveTo(String) Moves the file to the destination URL but does not overwrite an existing file of the same name.
  6. MoveTo(String, Boolean) Moves the file to the destination URL but overwrites an existing file of the same name only if bOverwrite is true.
  7. OpenBinary Opens the file in binary format.
  8. SaveBinary Saves the file in binary format.
  9. UndoCheckOut Undoes the file check-out.

Public Properties The following table shows the public properties of the SPFile class, the data type of each

  1. CheckedOutBy Microsoft.SharePoint.SPUser
    Gets the user who has checked out the file.
  2. CheckedOutDate System.DateTime
    Gets the date and time that the file was checked out.
  3. CheckInComment String
    Gets the comment used when a document is checked into a document library.
  4. Exists Boolean
    Gets a Boolean value that indicates whether the file exists.
  5. InDocumentLibrary Boolean
    Gets a Boolean value that indicates whether the file belongs to a document library.
  6. Item Microsoft.SharePoint.SPListItem
    Gets the list item object that corresponds to the file if the file belongs to a doc library.
  7. Length Int64
    Gets the size of the file in bytes, including the size of any supporting files, but excluding Web Parts.
  8. Name String Gets the internal name of the file.
  9. ParentFolder Microsoft.SharePoint.SPFolder
    Gets the parent folder of the file.
  10. ServerRelativeUrl String
    Gets the relative URL of the file based on the URL for the server.
  11. TimeCreated System.DateTime
    Gets a date and time value indicating when the file was created.
  12. TimeLastModified System.DateTime
    Gets a date and time value indicating when the file was last modified.
  13. Title String
    Gets the display name of the file.
  14. Url String
    Gets the site-relative URL of the file
  15. Versions Microsoft.SharePoint.SPFileVersionCollection Gets a collection of file version objects representing the versions of the file.

    https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4i8a6SxkdvlY5dFhcLv1gWkrRb55_iqfjt9FxEUCtfTyyuRUe2sVOYwg02S1a2iBoodNLuYbMC0eL55QYf-ZLXL696fIt1W2V1SCu4i_hzxayS6Ky8HHzgwTM8xQx_8u98m-cZ3vqSjoR/s400/2.JPG


SPContentTypeWhat is SPContentType/What are the method and properties of SPContentType/How can we use SPContentType You create a content type at the site level. This site content type acts as a template that is independent of any specific list or library. That site content type is then available on any child site. For example, if you create a site content type at the root site of a site collection, that site content type becomes available on any site in that site collection, so that you can add it to any list in the site collection.When you add a site content type to a list, Windows SharePoint Services 3.0 copies a local copy of the site content type onto the list itself. This local instance is called a list content type and applies only to the list onto which it was copied.Because Windows SharePoint Services stores a copy of the site content type as a list content type on each list to which that site content type is added, you can make changes to a list content type without affecting the site content type itself. The changes to a list content type are limited to that list and do not affect the site content type, or any other content types that inherit from that same site content type.The following figure shows this relationship. Two site content types, Memo and Spec, are defined for a site. When the Spec content type is added to the list of a child site list, Windows SharePoint Services copies an instance of the site content type locally onto the list.The Memo site content type is also available to be added to lists on the child site. However, this content type has not been added to the list, so no copy of it resides on the list.

Properties :-

  1. FieldLinks Gets an SPFieldLinkCollection that represents the collection of column, or field, references in the content type.
  2. Fields Gets an SPFieldCollection that represents collection of column references included in the content type.
  3. Group Gets and sets the content type group to which the content type is assigned.
  4. Hidden Gets an SPContentTypeId that represents the content type ID of the content type.
  5. Id Gets an SPContentTypeId that represents the content type ID of the content type.
  6. Name Gets or sets the content type name. Note:- There is a 1-to-1 correlation between the items in the SPFieldLinkCollection and SPFieldCollection objects. For each SPFieldLink you add to a content type, Windows SharePoint Services adds a corresponding SPField object that represents the merged view of that column as it's defined in the content type. You cannot directly add or delete items from an SPFieldCollection object in an SPContentType object; trying to do so throws an error.

Methods:- The Two most important methods are Delete and Update. Small Code Snippet Example:- //* Create a text field dynamically. //* Create a contenttype dynamically. //* Add field to a content type //* Add content type to a list //*Enable the content type on the list and make it vailable on New Menu Items. namespace FieldAddDemo { class Program { static void Main(string[] args) { SPSite site = new SPSite("site Url"); SPWeb web = site.OpenWeb(); string fieldName = web.Fields.Add("CustomF1", SPFieldType.Text, false); web.Update(); SPField fieldCustom1 = web.Fields["CustomF1"]; fieldCustom1.Group = "Extended Columns"; fieldCustom1.ShowInNewForm = true; fieldCustom1.Update(); SPContentType contentNew = new SPContentType(web.ContentTypes["Item"], web.ContentTypes, "NewDemoContent"); web.ContentTypes.Add(contentNew); web.Update(); contentNew.FieldLinks.Add(new SPFieldLink(fieldCustom1)); contentNew.Update(); SPList dlist = web.Lists["list-Name"]; dlist.ContentTypesEnabled = true; dlist.ContentTypes.Add(web.ContentTypes["NewDemoContent"]); dlist.Update(); SPContentType[] contentCol = new SPContentType[1]; contentCol[0] = dlist.ContentTypes["NewDemoContent"]; SPFolder fld = dlist.RootFolder; fld.UniqueContentTypeOrder = contentCol; fld.Update(); }}}

SPFieldWhat is SPField/How can we use SPField/What are the method and properties of SPFieldSPField object represent a field in a list in Sharepoint web site.Properties:-

  1. Group Gets or sets the column group to which the field belongs.
  2. Hidden Gets or sets a Boolean value that specifies whether the field is display in the list.
  3. Id Gets the GUID of the field.
  4. InterName Gets the internal name that is used for the field.
  5. StaticName Gets or sets the internal name of the field.
  6. ShowInNewForm Gets or sets a Boolean value that specifies whether the field is displayed in the form that is used to create list items
  7. ShowInEditForm Gets or sets a Boolean value that specifies whether the field is displayed in the form that is used to edit list items.
  8. ShowInDisplayForm Gets or sets a Boolean value that specifies whether the field is displayed in the form for displaying list items.Method:-
  • Delete
  • Update
  • OnAdded Occurs after a field is added.
  • OnUpdated Occurs after changes are made to a field.
  • OnDeleting Occurs when a field is being deleted.

SPListItem What is SPListItem/What are the method and properties of SPListItem/How can we use SPListItem SPListItem object represents a list item or row in a sharepoint list.Properties:-

  1. Attachments Gets the collection of attachments that are associated with the item.
  2. ContentType Gets the content type that is associated with the item.
  3. Fields Overridden. Gets or sets the collection of all fields in the parent of the item.
  4. File Gets the file that is represented by the item from a document library.
  5. Folder Gets a folder object that is associated with a folder item.
  6. ID Overridden. Gets the integer that identifies the item.
  7. ListItems Gets the parent collection of list item objects to which the item belongs.
  8. MissingRequiredFields Gets a Boolean value that specifies whether required fields are missing from the item's properties.
  9. Name Gets the name of the item.
  10. ParentList Gets the parent list of the list item.
  11. Tasks Gets the collection of workflow tasks for the item.
  12. Title Gets the title of the item.
  13. UniqueId Gets the GUID that uniquely identifies the item for the internal database.
  14. Url Gets the site-relative URL of the item.

Methods:-

  1. Copy Overloaded. Copies an item.
  2. CopyFrom Overloaded. Overwrites the current item.
  3. CopyTo Copies the item to the specified destination.
  4. Delete Overridden. Deletes the item.
  5. Update Overridden. Updates the database with changes that are made to the list item.

SPList What is SPList/What are the properties and method of SPList/How can we use SPList SPList :- SPList object represent a Sharepoint list in a Sharepoint site.Properties:-

  1. ContentTypes Gets the content types that are associated with the list.
  2. ContentTypesEnabled Gets or sets a Boolean value specifying whether content types are enabled for the list.
  3. DefaultView Gets the default view for the list.
  4. Description Gets or sets the description for the list.
  5. EmailAlias If e-mail notification is enabled, gets or sets the e-mail address to use to notify to the owner of an item when an assignment has changed or the item has been updated.
  6. EnableAssignToEmail Gets or sets a Boolean value specifying whether e-mail notification is enabled for the list.
  7. EnableAttachments Gets or sets a Boolean value that specifies whether attachments can be added to items in the list.
  8. EventReceivers Gets the collection of event receivers that have been registered for the list.
  9. Fields Gets the collection of field objects that represents all the fields in the list.
  10. FoldersGets the collection of folder items for the list.
  11. Forms Gets a collection of form objects that represent the forms that are used in creating, editing, or displaying items in the list.
  12. Hidden Gets or sets a Boolean value that specifies whether the list is hidden.
  13. ID Gets the GUID that identifies the list in the database.
  14. ItemCount Gets the number of items in the list.
  15. Items Gets the collection of all items in the list.
  16. Lists Gets the parent collection of lists to which the list belongs.
  17. RoleAssignments Gets the collection of role assignments for the list.
  18. RootFolder Gets the folder that contains all the files that are used in working with the list.
  19. Views Gets the collection of view objects that represents all the views of the list.

Methods :-

  1. BreakRoleInheritance Breaks the role assignment inheritance for the list and gives the current list its own copy of the role assignments.
  2. Delete Deletes the list.
  3. GetItemById Returns the list item with the specified integer ID.
  4. GetItemByUniqueId Returns the list item that is associated with the specified global unique identifier (GUID).
  5. GetItems Overloaded. Returns a collection of items from the list.
  6. GetView Returns a view of the list based on the specified GUID.
  7. Update Overloaded. Updates the database with changes that are made to the list.

SPWeb What is SPWeb/What are the method and properties of SPWEB:- SPWeb object represent a Sharepoint WebSite. SPWeb object can be obtained using SPSite and SPContext. Ex:- · SPWeb website = SPContext.Current.Web; · SPWeb webSite1 = site.OpenWeb(“URl”); Here site is an SPSite Object.Properties:-

  1. Alerts Gets the collection of alerts for the site or subsite.
  2. AllowUnsafeUpdates Gets or sets a Boolean value that specifies whether to allow updates to the database as a result of a GET request or without requiring a security validation.
  3. AllUsers Gets the collection of user objects that represents all users who are either members of the site or who have browsed to the site as authenticated members of a domain group in the site.
  4. AvailableContentTypes Gets the collection of all content type templates for the current scope, including those of the current Web site, as well as of any parent sites.
  5. AvailableFields Gets the collection of the available fields of the Web site.
  6. ContentTypes Gets the collection of content types for the Web site.
  7. CurrentUser Gets the current user of the site.
  8. EventReceivers Gets the collection of event receiver definitions that are currently available on the Web site.
  9. Exists Gets a Boolean value that indicates whether the Web site exists.
  10. Features Gets the collection of Features that are currently activated in the Web site.
  11. Fields Gets the collection of field objects that represents all the fields in the Web site.
  12. Files Gets the collection of all files in the root directory of the Web site.
  13. Folders Gets the collection of all first-level folders in the Web site.
  14. Groups Gets the collection of cross-site groups for the site.
  15. ID Gets the GUID for the site.
  16. IsRootWeb Gets a Boolean value that indicates whether the site is the top-level Web site of the site collection.
  17. Site Gets the parent site collection for the Web site.
  18. SiteGroups Gets the collection of cross-site groups for the site collection.
  19. SiteUsers Gets the collection of all users that belong to the site collection.
  20. Url Gets the absolute URL for the Web site.
  21. Users Gets the collection of user objects that are explicitly assigned permissions on the Web site.
  22. Lists Gets the collection of all lists that are contained in the Web site

Methods:-

  1. Close Closes the Web site at the end of a request and releases resources.
  2. Delete Deletes the Web site.
  3. EnsureUser Checks whether the specified login name belongs to a valid user of the Web site, and if the login name does not already exist, adds it to the Web site.
  4. GetFile Overloaded. Returns the file object with the specified GUID or the file object that is located at the specified URL.
  5. GetFolder Overloaded. Returns the folder object with the specified GUID or the folder object that is located at the specified URL.
  6. GetList Returns the list that is associated with the specified site-relative URL.
  7. GetListItem Returns the list item that is associated with the specified server-relative URL.
  8. GetSiteData Performs a query for list items across multiple lists, which can be located in multiple Web sites in the same Web site collection.
  9. Update Updates the database with changes that are made to the Web site.

Sharepoint Object Model Overview Windows SharePoint Services offers a highly structured server-side object model that makes it easy to access objects that represent the various aspects of a SharePoint Web site. From higher-level objects, you can drill down through the object hierarchy to obtain the object that contains the members you need to use in your code.What can be done with OM :-

  • Add, edit, delete, and retrieve data from SharePoint Lists
  • Create new lists and set list metadata (e.g. the fields in a list)
  • Set web properties
  • Work with documents in document libraries.
  • Perform administrative tasks such as creating webs, adding users, creating roles, etc.
  • Pretty much any functionality in the UI can be automated through the OM!

Important Classes of Object Model:-

  1. SPSite
  2. SPContext
  3. SPWeb
  4. SPList
  5. SPListItem
  6. SPListItemCollection
  7. SPField
  8. SPDocumentLibrary
  9. SPFile
  10. SPFolder
  11. SPContentType
  12. SPQuerySPSiteDataQuery

Example:-

  • If you are creating a Web Part, custom Web service, or Web application to work with site collections, individual sites, or lists, you can use members of the Microsoft.SharePoint.SPContext class to obtain the current site collection, Web site, or list.
  • Outside of an HTTP context, such as in a console application or a Windows application, use a constructor of the SPSite class to obtain a specific site collection and to reach various objects within the collection

Create SPList programmatically Creating a new list instance using the WSS object model : To Create the SPList programmatically,first take a console application "AccessList" and take a reference of Microsoft.Sharepoint.dll Write the following code and to create a Custom List "CustList2" which has a two column EmpID and EmpName. using System; using System.Collections.Generic; using System.Text; using Microsoft.SharePoint; namespace AccessList { class Program { static void Main(string[] args) { using (SPSite site = new SPSite("http://manab:36069/sites/DevSite/")){ using (SPWeb web = site.OpenWeb()){ string listName = "CustList2"; SPList list = null; foreach (SPList currentList in web.Lists){ if (currentList.Title.Equals(listName, StringComparison.InvariantCultureIgnoreCase)){ list = currentList; break; }} if (list == null){ Guid listID = web.Lists.Add(listName, "List for big news items", SPListTemplateType.GenericList); list = web.Lists[listID]; list.OnQuickLaunch = true; list.Fields.Add("EmpID", SPFieldType.Text, true); list.Fields.Add("EmpName", SPFieldType.Text, false); list.Update(); } // add a few news items SPListItem newItem; newItem = list.Items.Add(); newItem["Title"] = "Title1"; newItem["EmpID"] = "160040"; newItem["EmpName"] = "Manab"; newItem.Update(); newItem = list.Items.Add(); newItem["Title"] = "Title 2"; newItem["EmpID"] = "160041"; newItem["EmpName"] = "Ranjan"; newItem.Update(); }}}}}


1

0 comments: