sharepoint object model, web services and events

49
SharePoint Object Model, Web Services, and Events Mohan

Upload: mohan-arumugam

Post on 01-Jun-2015

1.624 views

Category:

Technology


1 download

DESCRIPTION

SharePoint Object Model, Web Services and Events

TRANSCRIPT

Page 1: SharePoint Object Model, Web Services and Events

SharePoint Object Model, Web Services, and EventsMohan

Page 2: SharePoint Object Model, Web Services and Events

Consultant

Certification

Mohan ArumugamTechnologies SpecialistE-mail : [email protected] : +91 99406 53876 Profile

Blogger

Trainer

Who Am I ?

Page 3: SharePoint Object Model, Web Services and Events

Agenda• NET Object model• Development Options• Development Environment• Managing Apps with

PowerShell• Managing Office 365 &

SharePoint Online

Page 4: SharePoint Object Model, Web Services and Events

.NET Object Model & Security

Page 5: SharePoint Object Model, Web Services and Events

.NET Object Model Managed code object model on the server Accessible via ASP.NET or any other server

process Implemented in C# Exposes almost of all of the data stored in

WSS Examples of what can be done with the

Object Mode: 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!

Page 6: SharePoint Object Model, Web Services and Events

ASP.Net Security For content stored in WSS, only registered set of web

custom controls will run in pages

Inline script in the page will not execute Code behind in pages can be made to work

All Executable code (e.g. web custom controls, web parts, and code-behind classes) needs to be installed on physical web server

Page 7: SharePoint Object Model, Web Services and Events

SharePoint• SharePoint Foundation(WSS)

Site and Workspace Provisioning Engine Out-of-the-box Collaboration Services

• SharePoint Server User Profiles, Search, Workflows, WCM BCS, Excel Services, Forms Services, Access, ECM

SharePoint 2013 Foundation

Browser Clients

MS Word Clients

MS Outlook Clients

SharePoint 2013 Server

Windows Server 2008 R2 / Windows 2012

Internet Information Services 7.0 or Above

.NET Framework 4.5

Page 8: SharePoint Object Model, Web Services and Events

Development Options

Page 9: SharePoint Object Model, Web Services and Events

SharePoint 2013 Development Options• Farm-Trust Solutions

Introduced in SharePoint 2007 Hosted in the same process as SharePoint Full server-side SharePoint API access

• Sandbox Solutions For existing SharePoint 2010 solutions only

• SharePoint App Model Introduced in SharePoint 2013 Provides for highest level of app isolation Much cleaner & simpler install & upgrade process

Page 10: SharePoint Object Model, Web Services and Events
Page 11: SharePoint Object Model, Web Services and Events

Development environment Requires x64 operating system

Windows Server 2008/2012 Windows Server 2008R2/2013

SharePoint 2010 must be installed locally SharePoint Foundation or SharePoint Server

Visual Studio 2010/2012 Additional software as required in the

project

Page 12: SharePoint Object Model, Web Services and Events

Getting Started with OM Build a web part

This is the best option to write code that functions are part of a WSS site or solution

There will be lots of documentation with the beta on how to build a web part.

Web Part is reusable and can be managed using all of the web part tools and UI.

Page 13: SharePoint Object Model, Web Services and Events

Getting Started with the OM Build an ASPX page

Code cannot live inline in a page within the site. Creating pages underneath the /_layouts directory is often the best

option for custom ASPX apps on top of SharePoint This lets your page be accessible from any web. For example, if you build

mypage.aspx in _Layouts, it is accessible from the following URLs: http://myweb/_layouts/myapp/mypage.aspx http://myweb/subweb1/_layouts/myapp/mypage.aspx

ASPX page will run using the context of the web under which it is running.

Page 14: SharePoint Object Model, Web Services and Events

Getting Started with the OM Windows Executable or any other application

Object model can be called from pretty much any code context. It is not limited to just web parts or ASP.Net

For example, you could build a command-line utility to perform certain actions

Page 15: SharePoint Object Model, Web Services and Events

Working with the OM The object model has three top-level objects:

SPWeb (represents an individual site) SPSite (represents a site collection, which is a set of web sites) SPGlobalAdmin (used for global administration settings)

In order to perform actions on data within a web, you must first get an SPWeb object.

Page 16: SharePoint Object Model, Web Services and Events

Adding our namespace You should add references to the WSS namespaces to your source files

using Microsoft.SharePoint;using Microsoft.SharePoint.WebControls;using Microsoft.SharePoint.Administration;…

Page 17: SharePoint Object Model, Web Services and Events

Example Objects List Data

◦ SPField◦ SPFieldCollection◦ SPListCollection◦ SPList◦ SPListItemCollection◦ SPListItem◦ SPView

Administration◦ SPGlobalAdmin◦ SPQuota◦ SPVirtualServer

Security◦ SPGroup◦

SPGroupCollection◦ SPSite◦ SPUser◦

SPUserCollection

Documents◦ SPDocumentLibrary◦ SPFile◦ SPFileCollection◦ SPFolder

Page 18: SharePoint Object Model, Web Services and Events

Hierarchical Overview of Objects in SharePoint

SPFarmSPFarm

SPServiceSPService

SPWeb ApplicationSPWeb Application

SPSiteSPSite

SPWebSPWeb

SPListSPList

SPWebSPWeb

SPListSPList

Page 19: SharePoint Object Model, Web Services and Events

SPFarm Objects SPFarm represents the highest-level object in the hierarchy It is a class AND a global, static object

SPFarm has no constructors Cannot be created or disposed Must be set to an existing static object

SPFarm.Local provides the entry point to the current farm

SPFarm exposes properties, methods, and events that affect farmwide settings For example: DefaultServiceAccount, Servers, Services, Solutions, OnBackup,

OnRestore, Upgrade

SPFarm thisFarm = SPFarm.Local;if (thisFarm.CurrentUserIsAdministrator){

...}

Page 20: SharePoint Object Model, Web Services and Events

SPService Objects SPService objects represent farmwide services For example: Forms Services, Access Services, PerformancePoint

Services, SharePoint Server Search Service, Excel Calculation Services, User Profile Service, Business Data Connectivity Service, Managed Metadata Services

SPWebService is a type of SPService Each Web Application belongs to an SPWebService

SPFarm thisFarm = SPFarm.Local;if(thisFarm.CurrentUserIsAdministrator){

foreach (SPService svc in thisFarm.Services){

if (svc is SPWebService){

SPWebService webSvc = (SPWebService)svc;...

}}

}

Page 21: SharePoint Object Model, Web Services and Events

SPWebApplication Objects SPWebApplication objects map to IIS Web sites Not the same as a SharePoint Site or SharePoint Web

Each SPWebApplication has its own Web.config

Administrators typically create Web Applications by using SharePoint Central Administration Developers can also create Web Applications by adding to the

WebApplications collection of a SPWebService object, but this is not a typical action

More typically, developers work with an existing SPWebApplication For example, to control Alert settings, create new site collections,

or to control maximum file size settings Developers can also delete Web Applications, but this is not a typical

action Exercise caution

Page 22: SharePoint Object Model, Web Services and Events

SPWebApplication ExampleSPFarm thisFarm = SPFarm.Local;if(thisFarm.CurrentUserIsAdministrator){ foreach(SPService svc in thisFarm.Services) { if(svc is SPWebService) { SPWebService webSvc = (SPWebService)svc; foreach (SPWebApplication webApp in webSvc.WebApplications) { if (!webApp.IsAdministrationWebApplication) { ... } } } }}

Page 23: SharePoint Object Model, Web Services and Events

SPSite Objects SPSite objects represent site collections Each SPSite has a RootWeb property (SPWeb)

Typically a security boundary and a container for users, groups, rights, permissions

SPSite objects can contain site-level features and solutions

Instantiate SPSite objects: By using its constructor As a member of the Sites collection of an SPWebApplication By referencing the current context site

Different instantiation approaches require different disposal strategies

Page 24: SharePoint Object Model, Web Services and Events

SPSite Examples

...foreach (SPSite site in webApp.Sites){ site.CatchAccessDeniedException = false; try { ... site.CatchAccessDeniedException = false; } finally { site.Dispose(); }}

SPSite remoteSite = new SPSite("http://sharepoint");...remoteSite.Dispose();

SPSite thisSite = SPContext.Current.Site;...// Do NOT dispose thisSite

Page 25: SharePoint Object Model, Web Services and Events

SPWeb Objects SPWeb objects represent SharePoint sites

Can contain pages, lists, and libraries Can contain other objects (subwebs)

Instantiating SPWeb objects: As the RootWeb property of an SPSite object As a member of the AllWebs collection of an SPSite object As the return value of the OpenWeb method of an SPSite object By referencing the current context Web

Different instantiation approaches require different disposal strategies

Page 26: SharePoint Object Model, Web Services and Events

SPWeb ExamplesSPSite knownSite= new SPSite("http://sharepoint");SPWeb knownWeb = knownSite.RootWeb;SPWeb knownSubWeb = knownSite.OpenWeb("/projects");...knownSubWeb.Dispose();knownWeb.Dispose();knownSite.Dispose();

SPWeb thisWeb = SPContext.Current.Web;...// Do NOT dispose thisWeb

...foreach (SPWeb childWeb in site.RootWeb.Webs){ try { ... } finally { childWeb.Dispose(); }}

Page 27: SharePoint Object Model, Web Services and Events

SPList Objects SPList objects are the primary container for data Native data Documents Images and other media Lookups

SPList objects can be referenced as members of the Lists collection from an SPWeb object Developers can create SPList objects by adding to the Lists collection

SPList objects expose many properties that affect list behaviors, such as versioning settings, content type support, and visibility

Page 28: SharePoint Object Model, Web Services and Events

SPList Example...foreach (SPSite site in webApp.Sites){ site.CatchAccessDeniedException = false; try { foreach (SPWeb childWeb in site.RootWeb.Webs) { try {

foreach (SPList list in childWeb.Lists) { if(!list.Hidden) { ... } } } finally { childWeb.Dispose(); } } site.CatchAccessDeniedException = false; } finally { site.Dispose(); }}

Page 29: SharePoint Object Model, Web Services and Events

Key Object – SPWeb Starting point to get at the Lists, Items, Documents, Users,

Alerts, etc. for a web site.

Example Properties: Web.Lists (returns a collection of lists) Web.Title (returns the title of the site) Web.Users (returns the users on the site)

In a web part or ASPX page, you can use the following line to get a SPWeb:SPWeb myweb = SPControl.GetContextWeb(Context);

Page 30: SharePoint Object Model, Web Services and Events

Accessing data in a WSS List Get a SPList or SPDocumentLibrary object.SPList mylist = web.Lists[“Events”];

You can then call the .Items property to get all of the items:SPListItemCollection items = mylist.Items;

If you only want a subset of the items, call the GetItems method and pass a SPQuery objectSPListItemCollection items = mylist.GetItems(query);

Page 31: SharePoint Object Model, Web Services and Events

Accessing data in a list To get data for a field, specify the field name in the indexer for an SPListItem

foreach(SPListItem item in items){Response.Write(item["Due Date"].ToString());Response.Write(item["Status"].ToString());Response.WRite(item["Title"].ToString());}

Page 32: SharePoint Object Model, Web Services and Events

Full ExampleSPWeb web = SPControl.GetContextWeb(Context);

SPList tasks = web.Lists["Tasks"];SPListItemCollection items=tasks.Items;foreach(SPListItem item in items){output.Write(item["Title"].ToString() + item["Status"].ToString() + "<br>");}

Page 33: SharePoint Object Model, Web Services and Events

Updating data Most objects in WSS do not immediately update data when you change a property

You need to first call the Update() method on the object This helps performance by minimizing SQL queries underneath the

covers

Example:SPList mylist = web.Lists[“Tasks”];mylist.Title=“Tasks!!!”;mylist.Description=“Description!!”;Mylist.Update();

Page 34: SharePoint Object Model, Web Services and Events

Updating List Data SPListItem is another example of an object where you

need to call update: Example:SPListItem item = items[0];item["Status"]="Not Started";item["Title"]="Task Title";item.Update();

Page 35: SharePoint Object Model, Web Services and Events

FormDigest Security By default, the object model will not allow data updates if the form

submitting the data does not contain the ‘FormDigest’ security key.

FormDigest is based on username and site. It will time out after 30 minutes.

Best solution is to include <FormDigest runat=“Server”/> web folder control in ASPX page.

If you do not need the security the FormDigest provides, you can set to SPWeb.AllowUnsafeUpdates to bypass this check.

Page 36: SharePoint Object Model, Web Services and Events

Adding Users to a web Get the appropriate SPRole object:SPRole admins = web.Roles["Administrator"];

Call the AddUser method:admins.AddUser("redmond\\gfoltz","[email protected]","Greg Foltz","");

Page 37: SharePoint Object Model, Web Services and Events

Keep objects around If you create and destroy objects frequently, you may do extra SQL queries

and have code that is incorrect: Bad Example:

SPWeb web = SPControl.GetContextWeb(Context);web.Lists["Tasks"].Title="mytitle";web.Lists["Tasks"].Description="mydescription";web.Lists["Tasks"].Update();

Good Example:

SPWeb web = SPControl.GetContextWeb(Context);SPList mylist = web.Lists["Tasks"];mylist.Title="mytitle";mylist.Description="mydescription";mylist.Update();

Page 38: SharePoint Object Model, Web Services and Events

Web Services in WSS SharePoint will have web services APIs for accessing content.

The web services layer will be built on top of the server OM.

Allows manipulation of Lists, Webs, Views, List Items, etc.

Functionality will be similar to server object model, but with fewer interfaces optimized to minimize transactions.

Office11 (e.g. Excel, DataSheet, Work, Outlook, FrontPage, etc) use web services to access data from WSS.

Page 39: SharePoint Object Model, Web Services and Events

Web Service Methods GetListCollection GetListItems GetWebCollection UpdateList UpdateListItems GetWebInfo GetWebPart GetSmartPageDocument And more…

Page 40: SharePoint Object Model, Web Services and Events

Getting Started With Web Services

Create a Windows Application In Visual Studio, choose ‘Add Web Reference’

Enter http://<server>/_vti_bin/lists.asmx to access the lists web service

Other services include: UserGroups.asmx – users and groups Webs.asmx – Web information Views.asmx – View information Subscription.asmx – Subscriptions

Page 41: SharePoint Object Model, Web Services and Events

Getting Started with Web Services

To send the logged on users’ credentials from the client, add the following line in the web reference object’s constructor: public Lists() { this.Url = "http://mikmort3/_vti_bin/lists.asmx";this.Credentials=System.Net.CredentialCache.DefaultCredentials;

}

Page 42: SharePoint Object Model, Web Services and Events

Events We support events on document libraries.

Operations such as add, update, delete, check-in, check-out, etc. Events are asynchronous Events call IListEventSink managed interface.

Documentation and Sample in the SDK

Page 43: SharePoint Object Model, Web Services and Events

Optimizing Performance of OM The biggest goal is to minimize the number of SQL queries.

It may be helpful to use the SQL profiler to monitor what the OM is doing underneath the covers

Minimizing managed/unmanaged transitions also a goal, though this is mostly taken care within the OM.

Page 44: SharePoint Object Model, Web Services and Events

What about CAML? Page Execution will no longer be driven by

CAML (XML schema used in SharePoint) CAML is still used in several places

Field Type Definitions Site and List Templates View definitions

Page 45: SharePoint Object Model, Web Services and Events

Code Example -- Enumerate Lists and Websprivate void ShowSubWebs(HtmlTextWriter output){

SPWeb web = SPControl.GetContextWeb(Context);SPWebCollection mywebs = web.Webs;foreach (SPWeb myweb in mywebs){

output.Write(myweb.Title + "<br>");}

}

private void ShowSubWebsWithLists(HtmlTextWriter output){

SPWeb web = SPControl.GetContextWeb(Context);SPWebCollection mywebs = web.Webs;foreach (SPWeb myweb in mywebs){

output.Write("<b>" + myweb.Title + "<br>" + "</b>");SPListCollection lists = myweb.Lists;foreach (SPList list in lists){

if (list.ItemCount>10){output.Write(list.Title + ": " + list.ItemCount + "<br>");}

}

}}

Page 46: SharePoint Object Model, Web Services and Events

Code Snippet – Copy Filesprivate SPWeb web;

private void Page_Load(object sender, System.EventArgs e){

web = SPControl.GetContextWeb(Context);}

private void Button1_Click(object sender, System.EventArgs e){

int maxsize = Convert.ToInt32(TextBox1.Text);SPFolder myfolder=web.GetFolder("Shared Documents");SPFileCollection myfiles = myfolder.Files;foreach (SPFile file in myfiles){

if (file.Length>(maxsize*1024)){

Response.Write(file.Name + ": " + file.Length/1024 + "kb<br>");file.CopyTo("Archive/"+file.Name,true);

}}

}

Page 47: SharePoint Object Model, Web Services and Events

Code Snippet – Add usersprivate void Button1_Click(object sender, System.EventArgs e){

SPWeb web = SPControl.GetContextWeb(Context);string username = TextBox1.Text;string displayname = TextBox2.Text;string email = TextBox3.Text;

SPRole admins = web.Roles["Administrator"];try {

admins.AddUser(username,email,displayname,"");Label4.Text="Successfully added user";

}catch(Exception ex){

Label4.Text=ex.ToString();}

}

Page 48: SharePoint Object Model, Web Services and Events

Q & A

Page 49: SharePoint Object Model, Web Services and Events

Mohan ArumugamTechnologies SpecialistE-mail : [email protected] : +91 99406 53876 Profile

Thank You