Developing Applications for SharePoint 2010
Chris KeyserPrincipal Program Managerpatterns & [email protected]
Objectives• Understand the concepts guidance addresses• See examples of what’s in the guidance• Gain a high level understanding of where and
how to apply the guidance
Microsoft SharePoint 2010The Business Collaboration Platform for the Enterprise and the Web
Connect and Empower People
Cut Costs with a Unified Infrastructure
Rapidly Respond to Business Needs
Communities
Search
Sites
Composites
ContentInsights
SharePoint Application and Platform
Base Platform
Core Services
Applications
Operating System Services
Web Parts | Personalization | Master Pages | Provider Framework (Navigation, Security…)
Database services Workflow servicesSearch services
Core Services
Composites Sites Communities Search Content Insignts
Site Model
RenderingTemplatesNavigationVisual Blueprint
Storage
RepositoryMetadataVersioningBackup
Security
Rights\RolesPluggable Auth.Per ItemRights Trimming
Management
DelegationProvisioningMonitoringStaging
Topology
Config. Mgmt.Farm ServicesFeature PolicyExtranet
APIs
Fields\Forms OM and SOAPEventsDeployment
ASP.NET Identity ManagementIIS
New Decisions with New Features
Guidance Overview
SharePoint Development
Client
Execution
Data
Application Foundations
Execution Models Overview
SharePoint Development
Client
Execution
Data
Application Foundations
IIS(WPW3.EXE)
Full Trust Architecture
Global Assembly Cache
FRONT END
Application Assembly
SharePoint Object Model
External Resources (other APIs, WCF services,
databases, etc
IIS(WPW3.EXE)
What Happens when Things Go Wrong?
Global Assembly Cache
FRONT END
Application Assembly
SharePoint Object Model
External Resources (other APIs, WCF services,
databases, etc
Request
A Word About “Sandbox”Sandbox Solution Sandbox Execution
p a tt e r n s & p r a c ti c e sp a tt e r n s & p r a c ti c e s
Sandbox Architecture
Sandbox Worker Process(SPUCWorkerProcess.exe)
User Code Service (SPUCHostService.exe)Execution Manager
(Inside Application Pool)
IIS(WPW3.EXE)
FRONT END BACK END
Sandbox Worker Proxy Process(SPUCWorkerProcessProxy.exe)
Full SP Object Model
SP Object Model Subset
Untrusted Code
Web.config / CAS Policies
Access restricted
by CAS policy
p a tt e r n s & p r a c ti c e sp a tt e r n s & p r a c ti c e s
Processing a Request in Sandbox
Sandbox Worker Process(SPUCWorkerProcess.exe)
User Code Service (SPUCHostService.exe)Execution Manager
(Inside Application Pool)
IIS(WPW3.EXE)
FRONT END
Sandbox Worker Proxy Process(SPUCWorkerProcessProxy.exe)
Full SP Object Model
SP Object Model Subset
Untrusted Code
Web.config / CAS Policies
RequestAccess
restricted by CAS policy
BACK END
Custom Code Logic
Allowed API Calls
p a tt e r n s & p r a c ti c e sp a tt e r n s & p r a c ti c e s
Handling Bad Code in the Sandbox
Sandbox Worker Process(SPUCWorkerProcess.exe)
User Code Service (SPUCHostService.exe)Execution Manager
(Inside Application Pool)
IIS(WPW3.EXE)
FRONT END
Sandbox Worker Proxy Process(SPUCWorkerProcessProxy.exe)
Full SP Object Model
SP Object Model Subset
Untrusted Code
Web.config / CAS Policies
Request
Run for30sec
Access restricted
by CAS policy
BACK END
Resource Wasting custom Logic
while(true) { //Do a Bad Bad Thing! }
Example Reference Implementation – Sandbox with Workflow
Scenario: You have designed and implemented a system that tracks the progress of statements of work (SOWs) and budget estimations. The IT manager, Cristian Petculescu wants you to extend this solution to automate the creation of project sites. When the approval status of a project estimate is set to Approved, a site is created to collaborate on the project.
Sample Execution Model Topics
• Understanding SharePoint Execution Models– What Are the SharePoint Executio
n Models?
– Examples and Scenarios• Farm Solutions• Sandboxed Solutions
– How Does the Sandbox Execution Model Work?
– What Can I Do with Sandboxed Solutions?
– Code Access Security Restrictions– Using Event Receivers
– Accessing External Data– Using Workflows– How Do I Manage Sandboxed
Solutions?– What Are the Core Issues for
Sandboxed Solutions?• Hybrid Approaches
– Hybrid Execution with a Full Trust Proxy
– Hybrid Execution with External Content Types
– Hybrid Execution with Custom Workflow Activities
– How Do I Manage Hybrid Solutions?
– What Are the Core Issues for Hybrid Solutions?
Data Models Overview
SharePoint Development
Client
Execution
Data
Application Foundations
How is a List Model Defined?• Database is the container• A database contains one or more tables,
and tables contain entities• Columns define the fields of an entity• A row in a table is an entity instance• Tables have Primary keys• Triggers fire on data events• Foreign Keys relationships relate entities• DDL representation
SharePoint Site
SharePoint List
ItemList
ColumnSh
areP
oint
Lis
t
LookupcolumnEvent
Receiver
No Equivalent Concepts
Site Columns, Content Types and Lists
Content Type
Site Columns
ListList Content Type
Parent Content
Type
Contains references to site columns
Content Types support Inheritance
When a content types is added to a list, a copy is placed in the list, and that content type inherits from the original content type
Lists can contain multiple content types
List Content TypeList Content Type
OrderLines list
List Relationships: Lookup Column
List Relationships build off of Lookup Columns
Orders list
ID(built in)
OrderNo Amount Cost
List Item Relationship
Show Column
Lookup Column: Order
ID(built in)
Order(lookup column)
Total SKU Quantity Price
Projected Column
Cascading and restricted delete behaviors based upon lookup relationship
Practices
Good Practices
• Using site columns and content types
• Defining site columns in the root site collection
• Defining lookup columns using site columns
Bad Practices
• Defining the same list structures over and over
Content Database
Indexing
Machines
ID(built in)
Model Manu Price Price Expire Date
Description
Index
Index
ID Index
Single Column Index
Index
Compound Column Index
Automatically generated and maintained
Data Types SupportedSingle line of textChoice field (but not multi-choice)NumberCurrencyDate/ TimeLookup (but not multi-value)Person or Group (but not multi-value)Title (but not in a document library)
Data Types Supported
Content TypeCurrencyLookupMetadataNumber Maximum of 20
indices per listUnique constraints are supported for columns in SharePoint 2010. A column with a unique constraint must be indexed.
Limits apply to all Operations
List Throttling
• Deleting a list with > 5000 items
• Delete a site with > 5000 items
• Creating an index on a list > 5000 items
Parts
ID(built in)
SKU Name Description
Code or a SharePoint Control
query
Content Database
5,000 rows touched on list query (SPQuery) (List)
20,000 rows touched (admin) 20,000 rows touched on
cross-list (SPSiteDataQuery)
Query Analyzed
SPQueryThrottledException (code)Query ResultsSubset of results with warning (UI)
How Does Indexing Impact Throttling?
ID(built in)
SKU Name Description
Code or a SharePoint Control
Where Part.SKU == SKU123
Content Database
SKU Index
Where Part.Name == 8mm Hex Nut
Query Analyzer
Use index
Scan table
SPQueryThrottledException (code)
Parts list,20000 items
No index
List Throttlingdemo
PracticesGood Practices
• Index columns used to filter
• Schedule off-hour maintenance window
• Use Content Iterator to process all list items
• Use Metadata Navigation to partition list access
• Use List Patterns to segment views and data
Bad Practices
• Indexing columns you don’t use to filter
• Globally disabling throttling
• Permanently disabling throttling on a list
• Using all of your index slots for a list
Runtime
Design Time
LINQ To SharePoint Process
SPMetal
Your Site DataContext source code
YourSourceYour
SourceYourSource
SolutionPackage
Deployed &
ActivatedSolution
LINQ to SharePointQuery Efficiency
LINQ Query
LINQ to SP Provider
var results = from projectItem in context.PriorityProjects where projectItem.ExecutiveSponsor == sponsor select projectItem;
<Where> <And> <BeginsWith> <FieldRef Name="ContentTypeId" /> <Value Type="ContentTypeId">0x0100</Value> </BeginsWith> <Eq> <FieldRef Name="Executive_x0020_Sponsor" /> <Value Type="Text">David Pelton</Value> </Eq> </And> </Where> </Query> <ViewFields> <FieldRef Name="Executive_x0020_Sponsor" /> <FieldRef Name="ProjectsLookup" LookupId="TRUE" /> <FieldRef Name="ID" /><FieldRef Name="Title" /> </ViewFields> <RowLimit Paged="TRUE">2147483647</RowLimit></View>
CAML generated at runtime by provider
Efficient CAML queries generated when possible
Blocks LINQ queries that translate to 2 or more CAML queries
LINQ to Objects does the rest.
View Projectionsusing (ManufacturingSiteDataContext context = new ManufacturingSiteDataContext(SPContext.Current.Web.Url)){ var results = from projectItem in context.PriorityProjects where projectItem.ExecutiveSponsor == sponsor select new { projectItem.Title, projectItem.ExecutiveSponsor, projectItem.Project.Leader }; …}
<View> <Query> <Where> …</Where> </Query> <ViewFields> <FieldRef Name="Title" /> <FieldRef Name="Executive_x0020_Sponsor" /> <FieldRef Name="ProjectLeader" /> </ViewFields> <ProjectedFields> <Field Name="ProjectLeader" Type="Lookup" List="Project" ShowField="Leader" /> </ProjectedFields> <Joins> <Join Type="LEFT" ListAlias="Project"> <!--List Name: Projects--> <Eq> <FieldRef Name="Project" RefType="ID" /> <FieldRef List="Project" Name="ID" /> </Eq> </Join> </Joins></View>
LINQ CAML
View projections combine entities Only way to return data from more than
one entity in one query Use anonymous or strongly typed
objects More efficient than lazy loading when
properties will be accessed Navigating through entity relationships
uses lazy loading Projections are not updateable
LINQ To SharePointdemo
Practices
Good Practices
• Inspect CAML output• Use View Projections• Apply efficient LINQ
syntax• Use SPSiteDataQuery
to aggregate items if no relationship exist
Bad Practices
• Ignoring CAML generated by queries
• Using LINQ to aggregate lists without relationships
Guidance Overview
SharePoint Development
Client
Execution
Data
Application Foundations
SharePoint Web ServicesREST InterfacesClient Object Model
Client Data Access Options
Client Side Object Model (CSOM)
WCF
SharePoint
CSOM Services
WCF Data Services Proxy
SharePoint Client Query Protocol
OData Protocol
WCF Data Services provider
ASMX Proxy
SOAP
ASMX Web Services
LINQ To SharePoint
Client Data AccessClient Side Object
Model (CSOM) REST interface Web services
List queries
List join queries Implicit only to satisfy where clause
External list queries
View projections
Request batching
Synchronous operations (except ECMA)
Asynchronous operations
SharePoint Foundation object model access
Access to SharePoint Server functionality (beyond SharePoint Foundation)
Support non-Windows clients (ECMA only)
Support strongly-typed LINQ queries (objects only, no list queries) (with proxy, lists only)
What is OData (www.odata.org)?
• REST based protocol • Two serialization formats– JSON– ATOM/ATOM PUB
• Supports advanced features– Batching– Concurrency Control– Partial Updates
Client
Service
URI addressable resourceshttp verbs
JSON or ATOM &
ATOM Pub
MIMEETAGsX-HTTP Merge
How Does Command Batching Work? (OData)
Custom Client-Side Code
WCF Data Services Proxy
Server Object Model
MIME Encoded Message
Add MachineUpdate PartDelete Bin
ResultsUser Results
Add MachineUpdate PartDelete Bin
Calls made on the client into the WCF Data services proxy1
BeginExecuteBatch called, causing the commands to be
sent to the server2
Commands are executed, and results gathered and returned. Each operation
has a result3The proxy calls the callback method
with an array of results4
Using WCF Data Servicesdemo
Practices
Good Practices
• Use command batching
• Minimize data returned to the client
• Use asynchronous processing
• Use View Projections
Bad Practices
• Override concurrency control without a good reason
Recommended Practice: Avoid using SharePoint Web Services to access lists for future compatibility.
How Does the Guidance Library Help?
Flexibility
Testability
Supportability
Manageability
Service Locator
SharePoint Logger
Application Settings Manager
Example – Service Locator Scenario: You are logging failures in your system to the event log
using the logger.
For compliance reasons you need to log this information using special logger that tracks additional information on the research site
The HiComplianceLogger is now used without changing the application code
cfg = SharePointServiceLocator.GetCurrent().GetInstance<IServiceLocatorConfig>();
cfg.Site = researchSite; cfg.RegisterTypeMapping<ILogger,HiComplianceLogger>();
var logger = SharePointServiceLocator.GetCurrent().GetInstance<ILogger>();logger.LogToOperations(error, 0, EventSeverity.Warning, LoggingAreas.ResearchPortal.DrugManagementCategory);
Example: Hierarchical Setting LookupSPFarm
SPWebApplication
SPSite SPSite
SPWeb
SPWebApplication
SPWeb
SPWeb
SPWeb
SPSite
ApplicationCode
var setting = hconfig.GetByKey<string>[“Foobar”]
Foobar in settings?
Not found, look for Foobar
Not Found, look for Foobar
Not found, look for Foobar
Foobar found, return setting value
Why use the Guidance?
Gain deeper insights into SharePoint architecture and internals
Better evaluate your decisions and tradeoffs
Develop applications more efficiently
Develop applications that are more flexible and manageable
http://www.microsoft.com/spgProduction Release
http://spg.codeplex.comDiscussions and support
It’s Easiest to Use Only What you Know
List Relationships: Database Foreign Key
OrderLinesOrders
ID(primary key)
OrderNo Amount Cost ID(primary key)
OrderID(foreign key)
SKU Quantity Price
Foreign Key Relationship
A Typical Database Foreign Key Relationship