wss object model
DESCRIPTION
TRANSCRIPT
Programming SharePoint Programming SharePoint Object Model, Web Object Model, Web Services, and EventsServices, and Events
Michael MortonMichael Morton4/15/034/15/03
Summary of .NET supportSummary of .NET support SharePoint will use ASP.NET instead of SharePoint will use ASP.NET instead of
ISAPI for base page executionISAPI for base page execution Web Part FrameworkWeb Part Framework Server Object Model for programmatic Server Object Model for programmatic
access to SharePoint dataaccess to SharePoint data We offer functionality as XML web We offer functionality as XML web
services for access from remote services for access from remote machinesmachines
.NET Object Model.NET Object Model Managed code object model on the Managed code object model on the
serverserver Accessible via ASP.NET or any other Accessible via ASP.NET or any other
server processserver process Implemented in C#Implemented in C# Exposes almost of all of the data Exposes almost of all of the data
stored in WSSstored in WSS
NET Object modelNET Object model Examples of what can be done with the Object Examples of what can be done with the Object
Mode:Mode: Add, edit, delete, and retrieve data from SharePoint Add, edit, delete, and retrieve data from SharePoint
Lists Lists Create new lists and set list metadata (e.g. the fields in Create new lists and set list metadata (e.g. the fields in
a list) a list) Set web properties Set web properties Work with documents in document libraries. Work with documents in document libraries. Perform administrative tasks such as creating webs, Perform administrative tasks such as creating webs,
adding users, creating roles, etc. adding users, creating roles, etc. Pretty much any functionality in the UI can be Pretty much any functionality in the UI can be
automated through the OM!automated through the OM!
Example ObjectsExample Objects
List DataList Data SPFieldSPField SPFieldCollectionSPFieldCollection SPListCollectionSPListCollection SPListSPList SPListItemCollectionSPListItemCollection SPListItemSPListItem SPViewSPView
AdministrationAdministration SPGlobalAdminSPGlobalAdmin SPQuotaSPQuota SPVirtualServerSPVirtualServer
SecuritySecurity SPGroupSPGroup
SPGroupCollectionSPGroupCollection SPSiteSPSite SPUserSPUser
SPUserCollectionSPUserCollection
DocumentsDocuments SPDocumentLibrarySPDocumentLibrary SPFileSPFile SPFileCollectionSPFileCollection SPFolderSPFolder
ASP.Net SecurityASP.Net Security For content stored in WSS, only registered For content stored in WSS, only registered
set of web custom controls will run in pagesset of web custom controls will run in pages Inline script in the page will not executeInline script in the page will not execute
Code behind in pages can be made to workCode behind in pages can be made to work All Executable code (e.g. web custom All Executable code (e.g. web custom
controls, web parts, and code-behind controls, web parts, and code-behind classes) needs to be installed on physical classes) needs to be installed on physical web serverweb server
Getting Started with OMGetting Started with OM Build a web part Build a web part
This is the best option to write code that This is the best option to write code that functions are part of a WSS site or functions are part of a WSS site or solutionsolution
There will be lots of documentation with There will be lots of documentation with the beta on how to build a web part.the beta on how to build a web part.
Web Part is reusable and can be managed Web Part is reusable and can be managed using all of the web part tools and UI.using all of the web part tools and UI.
Getting Started with the OMGetting Started with the OM Build an ASPX pageBuild an ASPX page
Code cannot live inline in a page within the site.Code cannot live inline in a page within the site. Creating pages underneath the /_layouts Creating pages underneath the /_layouts
directory is often the best option for custom directory is often the best option for custom ASPX apps on top of SharePointASPX apps on top of SharePoint This lets your page be accessible from any web. For This lets your page be accessible from any web. For
example, if you build mypage.aspx in _Layouts, it is example, if you build mypage.aspx in _Layouts, it is accessible from the following URLs:accessible from the following URLs: http://myweb/_layouts/myapp/mypage.aspxhttp://myweb/_layouts/myapp/mypage.aspx http://myweb/subweb1/_layouts/myapp/mypage.aspxhttp://myweb/subweb1/_layouts/myapp/mypage.aspx
ASPX page will run using the context of the web under ASPX page will run using the context of the web under which it is running.which it is running.
Getting Started with the OMGetting Started with the OM Windows Executable or any other Windows Executable or any other
applicationapplication Object model can be called from pretty Object model can be called from pretty
much any code context. It is not limited much any code context. It is not limited to just web parts or ASP.Netto just web parts or ASP.Net
For example, you could build a command-For example, you could build a command-line utility to perform certain actionsline utility to perform certain actions
DemoDemo Hello World Web PartHello World Web Part
Working with the OMWorking with the OM The object model has three top-level objects:The object model has three top-level objects:
SPWeb (represents an individual site)SPWeb (represents an individual site) SPSite (represents a site collection, which is a SPSite (represents a site collection, which is a
set of web sites)set of web sites) SPGlobalAdmin (used for global administration SPGlobalAdmin (used for global administration
settings)settings) In order to perform actions on data within a In order to perform actions on data within a
web, you must first get an SPWeb object.web, you must first get an SPWeb object.
Adding our namespaceAdding our namespace You should add references to the You should add references to the
WSS namespaces to your source WSS namespaces to your source filesfilesusing Microsoft.SharePoint;using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;using Microsoft.SharePoint.Administration;
……
Key Object – SPWebKey Object – SPWeb Starting point to get at the Lists, Items, Starting point to get at the Lists, Items,
Documents, Users, Alerts, etc. for a web site.Documents, Users, Alerts, etc. for a web site. Example Properties:Example Properties:
Web.Lists (returns a collection of lists)Web.Lists (returns a collection of lists) Web.Title (returns the title of the site)Web.Title (returns the title of the site) Web.Users (returns the users on the site)Web.Users (returns the users on the site)
In a web part or ASPX page, you can use the In a web part or ASPX page, you can use the following line to get a SPWeb:following line to get a SPWeb:SPWeb myweb = SPControl.GetContextWeb(Context);SPWeb myweb = SPControl.GetContextWeb(Context);
DemoDemo Showing Web and List PropertiesShowing Web and List Properties
Accessing data in a WSS Accessing data in a WSS ListList Get a SPList or SPDocumentLibrary object.Get a SPList or SPDocumentLibrary object.
SPList mylist = web.Lists[“Events”];SPList mylist = web.Lists[“Events”];
You can then call the .Items property to get You can then call the .Items property to get all of the items:all of the items:SPListItemCollection items = mylist.Items;SPListItemCollection items = mylist.Items;
If you only want a subset of the items, call If you only want a subset of the items, call the GetItems method and pass a SPQuery the GetItems method and pass a SPQuery objectobjectSPListItemCollection items = SPListItemCollection items =
mylist.GetItems(query);mylist.GetItems(query);
Accessing data in a listAccessing data in a list To get data for a field, specify the field To get data for a field, specify the field
name in the indexer for an SPListItemname in the indexer for an SPListItemforeach(SPListItem item in items)foreach(SPListItem item in items)
{{
Response.Write(item["Due Date"].ToString());Response.Write(item["Due Date"].ToString());
Response.Write(item["Status"].ToString());Response.Write(item["Status"].ToString());
Response.WRite(item["Title"].ToString());Response.WRite(item["Title"].ToString());
}}
Full ExampleFull ExampleSPWeb web = SPControl.GetContextWeb(Context);SPWeb web = SPControl.GetContextWeb(Context);
SPList tasks = web.Lists["Tasks"];SPList tasks = web.Lists["Tasks"];SPListItemCollection items=tasks.Items;SPListItemCollection items=tasks.Items;foreach(SPListItem item in items)foreach(SPListItem item in items){{output.Write(item["Title"].ToString() + output.Write(item["Title"].ToString() + item["Status"].ToString() + "<br>");item["Status"].ToString() + "<br>");}}
Updating dataUpdating data Most objects in WSS do not immediately Most objects in WSS do not immediately
update data when you change a propertyupdate data when you change a property You need to first call the Update() method on You need to first call the Update() method on
the objectthe object This helps performance by minimizing SQL queries This helps performance by minimizing SQL queries
underneath the coversunderneath the covers
Example:Example:SPList mylist = web.Lists[“Tasks”];SPList mylist = web.Lists[“Tasks”];
mylist.Title=“Tasks!!!”;mylist.Title=“Tasks!!!”;
mylist.Description=“Description!!”;mylist.Description=“Description!!”;
Mylist.Update();Mylist.Update();
Updating List DataUpdating List Data SPListItem is another example of an SPListItem is another example of an
object where you need to call update:object where you need to call update: Example:Example:
SPListItem item = items[0];SPListItem item = items[0];
item["Status"]="Not Started";item["Status"]="Not Started";
item["Title"]="Task Title";item["Title"]="Task Title";
item.Update();item.Update();
FormDigest SecurityFormDigest Security By default, the object model will not allow data By default, the object model will not allow data
updates if the form submitting the data does not updates if the form submitting the data does not contain the ‘FormDigest’ security key.contain the ‘FormDigest’ security key.
FormDigest is based on username and site. It will FormDigest is based on username and site. It will time out after 30 minutes.time out after 30 minutes.
Best solution is to include <FormDigest Best solution is to include <FormDigest runat=“Server”/> web folder control in ASPX page.runat=“Server”/> web folder control in ASPX page.
If you do not need the security the FormDigest If you do not need the security the FormDigest provides, you can set to provides, you can set to SPWeb.AllowUnsafeUpdates to bypass this check.SPWeb.AllowUnsafeUpdates to bypass this check.
Adding Users to a webAdding Users to a web Get the appropriate SPRole object:Get the appropriate SPRole object:
SPRole admins = web.Roles["Administrator"];SPRole admins = web.Roles["Administrator"];
Call the AddUser method:Call the AddUser method:admins.AddUser("redmond\\admins.AddUser("redmond\\gfoltz","[email protected]","Greg Foltz","");gfoltz","[email protected]","Greg Foltz","");
DemoDemo Adding users to the site via the OMAdding users to the site via the OM
Keep objects aroundKeep objects around If you create and destroy objects frequently, you If you create and destroy objects frequently, you
may do extra SQL queries and have code that is may do extra SQL queries and have code that is incorrect:incorrect:
Bad Example:Bad Example:SPWeb web = SPControl.GetContextWeb(Context);SPWeb web = SPControl.GetContextWeb(Context);
web.Lists["Tasks"].Title="mytitle";web.Lists["Tasks"].Title="mytitle";
web.Lists["Tasks"].Description="mydescription";web.Lists["Tasks"].Description="mydescription";
web.Lists["Tasks"].Update();web.Lists["Tasks"].Update();
Good Example:Good Example:SPWeb web = SPControl.GetContextWeb(Context);SPWeb web = SPControl.GetContextWeb(Context);
SPList mylist = web.Lists["Tasks"];SPList mylist = web.Lists["Tasks"];
mylist.Title="mytitle";mylist.Title="mytitle";
mylist.Description="mydescription";mylist.Description="mydescription";
mylist.Update();mylist.Update();
SharePoint will have web services APIs for SharePoint will have web services APIs for accessing content. The web services layer accessing content. The web services layer will be built on top of the server OM.will be built on top of the server OM.
Allows manipulation of Lists, Webs, Views, Allows manipulation of Lists, Webs, Views, List Items, etc.List Items, etc.
Functionality will be similar to server object Functionality will be similar to server object model, but with fewer interfaces optimized to model, but with fewer interfaces optimized to minimize transactions.minimize transactions.
Office11 (e.g. Excel, DataSheet, Work, Office11 (e.g. Excel, DataSheet, Work, Outlook, FrontPage, etc) use web services to Outlook, FrontPage, etc) use web services to access data from WSS.access data from WSS.
Web Services in WSSWeb Services in WSS
Web Service MethodsWeb Service Methods GetListCollectionGetListCollection GetListItemsGetListItems GetWebCollectionGetWebCollection UpdateListUpdateList UpdateListItemsUpdateListItems GetWebInfoGetWebInfo GetWebPartGetWebPart GetSmartPageDocumentGetSmartPageDocument And more… And more…
Getting Started With Web ServicesGetting Started With Web Services
Create a Windows ApplicationCreate a Windows Application In Visual Studio, choose ‘Add Web In Visual Studio, choose ‘Add Web
Reference’Reference’ Enter Enter http://<server>/_vti_bin/lists.asmxhttp://<server>/_vti_bin/lists.asmx to to
access the lists web serviceaccess the lists web service Other services include:Other services include:
UserGroups.asmx – users and groupsUserGroups.asmx – users and groups Webs.asmx – Web informationWebs.asmx – Web information Views.asmx – View informationViews.asmx – View information Subscription.asmx – SubscriptionsSubscription.asmx – Subscriptions
Getting Started with Web ServicesGetting Started with Web Services
To send the logged on users’ To send the logged on users’ credentials from the client, add the credentials from the client, add the following line in the web reference following line in the web reference object’s constructor:object’s constructor: public Lists() {public Lists() {
this.Url = this.Url = "http://mikmort3/_vti_bin/lists.asmx";"http://mikmort3/_vti_bin/lists.asmx";
this.Credentials=System.Net.CredentialCache.Dethis.Credentials=System.Net.CredentialCache.DefaultCredentials;faultCredentials;
}}
DemoDemo Building a Web Service ClientBuilding a Web Service Client
EventsEvents We support events on document We support events on document
libraries.libraries. Operations such as add, update, delete, Operations such as add, update, delete,
check-in, check-out, etc.check-in, check-out, etc. Events are asynchronousEvents are asynchronous Events call IListEventSink managed Events call IListEventSink managed
interface. interface.
Documentation and Sample in the SDKDocumentation and Sample in the SDK
Optimizing Performance of Optimizing Performance of OMOM The biggest goal is to minimize the number The biggest goal is to minimize the number
of SQL queries. of SQL queries. It may be helpful to use the SQL profiler to It may be helpful to use the SQL profiler to
monitor what the OM is doing underneath the monitor what the OM is doing underneath the coverscovers
Minimizing managed/unmanaged transitions Minimizing managed/unmanaged transitions also a goal, though this is mostly taken care also a goal, though this is mostly taken care within the OM.within the OM.
What about CAML?What about CAML? Page Execution will no longer be Page Execution will no longer be
driven by CAML (XML schema used in driven by CAML (XML schema used in SharePoint)SharePoint)
CAML is still used in several placesCAML is still used in several places Field Type DefinitionsField Type Definitions Site and List TemplatesSite and List Templates View definitionsView definitions
SDK AvailableSDK Available Documentation about V2 available at Documentation about V2 available at
http://msdn.microsoft.com/sharepoint/http://msdn.microsoft.com/sharepoint/
Questions?Questions?
Code Example -- Enumerate Lists and Code Example -- Enumerate Lists and WebsWebs
private void ShowSubWebs(HtmlTextWriter output)private void ShowSubWebs(HtmlTextWriter output){{
SPWeb web = SPControl.GetContextWeb(Context);SPWeb web = SPControl.GetContextWeb(Context);SPWebCollection mywebs = web.Webs;SPWebCollection mywebs = web.Webs;foreach (SPWeb myweb in mywebs)foreach (SPWeb myweb in mywebs){{
output.Write(myweb.Title + "<br>");output.Write(myweb.Title + "<br>");}}
}}
private void ShowSubWebsWithLists(HtmlTextWriter output)private void ShowSubWebsWithLists(HtmlTextWriter output){{
SPWeb web = SPControl.GetContextWeb(Context);SPWeb web = SPControl.GetContextWeb(Context);SPWebCollection mywebs = web.Webs;SPWebCollection mywebs = web.Webs;foreach (SPWeb myweb in mywebs)foreach (SPWeb myweb in mywebs){{
output.Write("<b>" + myweb.Title + "<br>" + "</b>");output.Write("<b>" + myweb.Title + "<br>" + "</b>");SPListCollection lists = myweb.Lists;SPListCollection lists = myweb.Lists;foreach (SPList list in lists)foreach (SPList list in lists){{
if (list.ItemCount>10)if (list.ItemCount>10){{output.Write(list.Title + ": " + output.Write(list.Title + ": " +
list.ItemCount + "<br>");list.ItemCount + "<br>");}}
}}
}}}}
Code Snippet – Copy FilesCode Snippet – Copy Filesprivate SPWeb web;private SPWeb web;
private void Page_Load(object sender, System.EventArgs e)private void Page_Load(object sender, System.EventArgs e){{
web = SPControl.GetContextWeb(Context);web = SPControl.GetContextWeb(Context);}}
private void Button1_Click(object sender, System.EventArgs e)private void Button1_Click(object sender, System.EventArgs e){{
int maxsize = Convert.ToInt32(TextBox1.Text);int maxsize = Convert.ToInt32(TextBox1.Text);SPFolder myfolder=web.GetFolder("Shared Documents");SPFolder myfolder=web.GetFolder("Shared Documents");SPFileCollection myfiles = myfolder.Files;SPFileCollection myfiles = myfolder.Files;foreach (SPFile file in myfiles)foreach (SPFile file in myfiles){{
if (file.Length>(maxsize*1024))if (file.Length>(maxsize*1024)){{
Response.Write(file.Name + ": " + Response.Write(file.Name + ": " + file.Length/1024 + "kb<br>");file.Length/1024 + "kb<br>");
file.CopyTo("Archive/"+file.Name,true);file.CopyTo("Archive/"+file.Name,true);}}
}}}}
Code Snippet – Add usersCode Snippet – Add usersprivate void Button1_Click(object sender, private void Button1_Click(object sender,
System.EventArgs e)System.EventArgs e){{
SPWeb web = SPWeb web = SPControl.GetContextWeb(Context);SPControl.GetContextWeb(Context);
string username = TextBox1.Text;string username = TextBox1.Text;string displayname = TextBox2.Text;string displayname = TextBox2.Text;string email = TextBox3.Text;string email = TextBox3.Text;
SPRole admins = SPRole admins = web.Roles["Administrator"];web.Roles["Administrator"];
try try {{
admins.AddUser(username,email,displayname,"");admins.AddUser(username,email,displayname,"");Label4.Text="Successfully added Label4.Text="Successfully added
user";user";}}catch(Exception ex)catch(Exception ex){{
Label4.Text=ex.ToString();Label4.Text=ex.ToString();}}
}}