Each of these levels has its own SharePoint API class. Instances of this class can be used to talk to these entities and do stuff with them.
When you start using these objects, it's important to dispose them when necessary. I lot of them implement the IDisposable interface, meaning you can use them in a so called 'using' statement. In the 'using' statement you create an instance of the class, do stuff with it and dispose of it when the 'using' statement comes to its end. This is important because a lot of these objects are quiet heavy and could cause a lot of memory usage or even memory leaks.
For example:
(using code example)
The respective classes
SPFarm - SharePoint farm
SPWebApplication - Web application
SPSite - Site collection
SPWeb - Site
SPList - List
SPListItem - Item
Some good things to know
Opening a web directly from the URL
1: using (SPSite site = new SPSite("http://sitecollection1/subsite1"))
2: {
3:
4: using (SPWeb web = site.OpenWeb()) 5: {
6:
7: // Use the site/web object
8:
9: }
10:
11: }
Using the ‘TryGetList’ method: new in SharePoint 2010 is the ‘TryGetList’ method to try to get a list in a given web. In the past, this could throw an exception and it was the only way to find out that the list did not exist.
1: using (SPSite site = new SPSite("http://sitecollection1/subsite1"))
2: {
3:
4: using (SPWeb web = site.OpenWeb())
5: {
6:
7: SPList list = web.Lists.TryGetList("ListTitle");
8:
9: if (list != null)
10: {
11:
12:
13: // List exist so you can safely use it
14:
15: }
16:
17: }
18: 19: }
1: using (SPSite site = new SPSite("http://sitecollection1/subsite1"))
2: {
3:
4: using (SPWeb web = site.OpenWeb()) 5: {
6:
7: SPList list = web.Lists.TryGetList("ListTitle");
8:
9: if (list != null)
10: {
11:
12: SPQuery query = new SPQuery();
13: query.Query = "<Where>" +14: "<Eq>" +
15: "<FieldRef Name='Title' />" +
16: "<Value Type='Text'>TitleYouWantToFind</Value>" +
17: "</Eq>" +
18: "</Where>";
19:
20: SPListItemCollection iColl = list.GetItems(query);
21:
22: // Loop the collection
23:
24: } 25:
26: }
27:
28: }
Geen opmerkingen:
Een reactie posten