SlideShare a Scribd company logo
CAML, REST and LINQ -
Data Access Options in
SharePoint 2010




Rob Windsor
rwindsor@allin.com
@robwindsor       #spsvb
Sponsors
About Me
•   Senior SharePoint Architect with Allin Consulting
•   Technical Contributor to the Pluralsight On-Demand Library
•   Microsoft MVP, MCPD, MCT
•   Founder and Past-President of the North Toronto .NET UG
•   Co-author of Prof. Visual Basic 2010 and .NET 4 (Wrox)
Lists
• The data storage mechanism in SharePoint
    Virtually all content stored in lists
• Provisioning engine handles list creation and schema management
• SharePoint provides interface to add, edit, delete and view items
• Lists support:
      Multiple views (for sorting, filtering, grouping)
      Simple validation
      Content approval
      Item versioning
• Data stored in rows and columns
    More like Excel worksheets than database tables
Accessing and Updating List Items
• Field values accessed via SPListItem indexer
• Generally accessed by internal name
• Weakly typed
var web = SPContext.Current.Web;               var web = SPContext.Current.Web;

var list = web.Lists.TryGetList("Products");   var list = web.Lists.TryGetList("Products");
if (list == null) return;                      if (list == null) return;

foreach (SPListItem item in list.Items)        foreach (SPListItem item in list.Items)
{                                              {
    Console.WriteLine("{0} ({1})",                 var price = Convert.ToDouble(
        item["Title"],                                 item["UnitPrice"]);
        item["UnitPrice"]);                        price *= 1.1;
}                                                  item["UnitPrice"] = price;
                                                   item.Update();
                                               }
Field Names
• Fields have three names
   Display name
      The name displayed to the end user
      Can be changed
   Internal name
        Set when field is created
        Does not change
        Non-alphanumeric chars escaped (e.g. Unit_x0020_Price)
        Find using Server Explorer
   Static name
      Used by custom field types
CAML Queries
• Query list items using XML syntax
• SPQuery
   Query single list
   Returns SPLitsItemCollection
• SPSiteDataQuery
   Query multiple lists across site collection
   Returns DataSet
CAML Queries
var query = new SPQuery();
query.ViewFields =
    "<FieldRef Name='Title' />" +
    "<FieldRef Name='UnitPrice' />";
query.Query =
    "<OrderBy>" +
    " <FieldRef Name='Title' />" +
    "</OrderBy>" +
    "<Where>" +
    " <And>" +
    "    <Gt>" +
    "      <FieldRef Name='UnitsInStock' />" +
    "      <Value Type='Integer'>0</Value>" +
    "    </Gt>" +
    "    <Eq>" +
    "      <FieldRef Name='Category' LookupId='True' />" +
    "      <Value Type='Lookup'>1</Value>" +
    "    </Eq>" +
    " </And>" +
    "</Where>";

var items = list.GetItems(query);
“All we can do is decide what to do with
   the time tools that is are given us”




  Image from The Lord of the Rings: The Fellowship of the Ring by New
  Line Cinema
Large List Throttling

• Lists can store millions of items
• Retrieval of items is throttled
    Max 5,000 items
    Max 20,000 for Owners
    No max for local admin
• Can override limits in code
    QueryThrottleMode
• Can configure time window
  where limits are ignored
    For reporting, list aggregation, etc
    Done during off-peak hours
List Relationships
Joins in CAML Queries
• SPQuery supports joins
    SPSiteDataQuery does not
• Joins can only be done on lookup columns
• Key properties
    Joins: Define joins to other lists
    ProjectedFields: Fields being projected from the foreign list
• Only inner and left outer joins are supported
SPQuery with Join Example
var query = new SPQuery { RowLimit = 5 };
query.ProjectedFields =
    "<Field Name='CategoryTitle' Type='Lookup' List='productCategory' ShowField='Title' />";
query.ViewFields =
    "<FieldRef Name='Title' />" +
    "<FieldRef Name='UnitPrice' />" +
    "<FieldRef Name='UnitsInStock' />" +
    "<FieldRef Name='CategoryTitle' />";
query.Query =
    "<Where>" +
    " <And>" +
    "    <Gt>" +
    "      <FieldRef Name='UnitsInStock' />" +
    "      <Value Type='Integer'>0</Value>" +
    "    </Gt>" +
    "    <Eq>" +
    "      <FieldRef Name='CategoryTitle' />" +
    "      <Value Type='Text'>Condiments</Value>" +
    "    </Eq>" +
    " </And>" +
    "</Where>";
query.Joins =
    "<Join Type='INNER' ListAlias='productCategory'>" +
    " <Eq>" +
    "    <FieldRef Name='Category' RefType='ID' />" +
    "    <FieldRef List='productCategory' Name='ID' />" +
    " </Eq>" +
    "</Join>";

return list.GetItems(query);
Querying Multiple Lists with SPSiteDataQuery

• Core properties the same as SPQuery
• Cannot query lists outside site collection
• Key additional properties
    Lists
       Defines which lists will be included in query
       Use ServerTemplate for OOB content types
       Use BaseType plus filter for ID in where clause for custom content
        types
    Webs
       Defines the scope of the query
       SiteCollection
          – Query all matching lists in site collection
       Recursive:
          – Query all matching lists in current Web and it’s children
SPSiteDataQuery Example
var query = new SPSiteDataQuery { RowLimit = 50 };
query.ViewFields =
    "<FieldRef Name='Title' />" +
    "<FieldRef Name='DueDate' />" +
    "<FieldRef Name='AssignedTo' />";
query.Query =
    "<Where>" +
    " <And>" +
    "    <Geq>" +
    "      <FieldRef Name='DueDate' />" +
    "      <Value Type='DateTime'><Today /></Value>" +
    "    </Geq>" +
    "    <Leq>" +
    "      <FieldRef Name='DueDate' />" +
    "      <Value Type='DateTime'><Today OffsetDays='5' /></Value>" +
    "    </Leq>" +
    " </And>" +
    "</Where>";
query.Lists =
    "<Lists ServerTemplate='107' />"; <!– Task Lists -->
query.Webs =
    "<Webs Scope='SiteCollection' />";

return web.GetSiteData(query);
DEMO
List access using Server
Object Model
REST APIs
• Generally used by remote applications
• Uses Open Data (oData) Protocol
    Also known as: Astoria, ADO.NET Data Services, WCF Data Services
    Data centric (REST) Web service
    Data returned in AtomPub or JSON format
    Metadata is available
       Allows creation of service proxy
       Strongly-typed access to data
    Requests for collections may not return all items
       Max 1,000 items returned per request
       Need to check for continuation
REST APIs
• Urls map to SharePoint resources
    Example: ListData.svc/Products(2)/Category maps to the category
     for the product with id == 2
• Protocol commands
      $filter={simple predicate}
      $expand={Entity}
      $orderby={property}
      $skip=n
      $top=n
      $metadata
REST APIs (oData)
Consuming Data via REST APIs
Consuming Data via REST APIs
var context = new DemoDataContext(new Uri(
    SiteUrl + @"_vti_bin/ListData.svc"));
context.Credentials = CredentialCache.DefaultCredentials;

var query = from detail in context.OrderDetails
            where detail.UnitPrice < 100
            select detail;
Consuming Data via REST APIs
var context = new DemoDataContext(new Uri(
    "http://localhost/sites/demo/_vti_bin/ListData.svc"));
context.Credentials = CredentialCache.DefaultCredentials;

var query = from detail in context.OrderDetails
            where detail.UnitPrice < 100
            select detail;
var queryCount = query.Count();

var details = new List<OrderDetailsItem>();

var dsquery = query as DataServiceQuery<OrderDetailsItem>;
var response = dsquery.Execute() as QueryOperationResponse<OrderDetailsItem>;

details.AddRange(response);
var token = response.GetContinuation();
while (token != null)
{
    response = context.Execute(token);
    details.AddRange(response);
    token = response.GetContinuation();
}
Consuming Data via REST APIs
var url = "http://localhost/sites/demo/_vti_bin/ListData.svc";
var context = new DemoProxy.DemoDataContext(new Uri(url));
context.Credentials = System.Net.CredentialCache.DefaultCredentials;

var products = from product in context.Products
               where product.Category.Title == "Condiments" &&
                   product.UnitsInStock > 0
               select product;

foreach (var product in products)
{
    product.UnitsInStock += 1;
    context.UpdateObject(product);   // don’t forget this
}
context.SaveChanges();
DEMO
Using the REST APIs
LINQ to SharePoint
• LINQ provider generates CAML for query
    Requires reference to Microsoft.SharePoint.Linq.dll
• Only available to server object model
• Queries are strongly-typed
• Entities created using SPMetal command-line utility
    Similar to SqlMetal in LINQ to SQL
    Located in <System root>bin
    Basic usage
       spmetal /web:<site url> /code:<file name>
    Code generation can be customized via parameters XML file
       http://msdn.microsoft.com/en-us/library/ee535056.aspx
Consuming Data with LINQ to SharePoint

var url = "http://localhost/sites/demo";
var context = new SPNorthwind.SPNorthwindDataContext(url);

// context.Log = Console.Out;

var products = from product in context.Products
                where product.Category.Title == "Condiments" &&
                    product.UnitsInStock > 0
                select product;

foreach (var product in products)
{
    product.UnitsInStock += 1;
}
context.SubmitChanges();
DEMO
LINQ to SharePoint
Thank You
• Big thanks to the organizers, sponsors and you for making
  this event possible
• Please fill out your evaluation
• Please keep in touch


    rwindsor@allin.com
    @robwindsor
    msmvps.com/blogs/windsor

More Related Content

What's hot

SharePoint 2010 Client Object Model
SharePoint 2010 Client Object ModelSharePoint 2010 Client Object Model
SharePoint 2010 Client Object Model
G. Scott Singleton
 
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
SPTechCon
 
SharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote AuthenticationSharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote AuthenticationAdil Ansari
 
Understanding and programming the SharePoint REST API
Understanding and programming the SharePoint REST APIUnderstanding and programming the SharePoint REST API
Understanding and programming the SharePoint REST API
Chris Beckett
 
Are you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint AppsAre you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint AppsLiam Cleary [MVP]
 
SharePoint Client Object Model (CSOM)
SharePoint Client Object Model (CSOM)SharePoint Client Object Model (CSOM)
SharePoint Client Object Model (CSOM)
Kashif Imran
 
Working With Sharepoint 2013 Apps Development
Working With Sharepoint 2013 Apps DevelopmentWorking With Sharepoint 2013 Apps Development
Working With Sharepoint 2013 Apps Development
Pankaj Srivastava
 
Develop iOS and Android apps with SharePoint/Office 365
Develop iOS and Android apps with SharePoint/Office 365Develop iOS and Android apps with SharePoint/Office 365
Develop iOS and Android apps with SharePoint/Office 365
Kashif Imran
 
SharePoint 2013 REST APIs
SharePoint 2013 REST APIsSharePoint 2013 REST APIs
SharePoint 2013 REST APIs
Giuseppe Marchi
 
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Eric Shupps
 
Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010
Ben Robb
 
SharePoint 2013 APIs
SharePoint 2013 APIsSharePoint 2013 APIs
SharePoint 2013 APIs
John Calvert
 
Introduction to SharePoint 2013 REST API
Introduction to SharePoint 2013 REST APIIntroduction to SharePoint 2013 REST API
Introduction to SharePoint 2013 REST API
QUONTRASOLUTIONS
 
SharePoint 2007 Presentation
SharePoint 2007 PresentationSharePoint 2007 Presentation
SharePoint 2007 PresentationAjay Jain
 
CSOM (Client Side Object Model). Explained @ SharePoint Saturday Houston
CSOM (Client Side Object Model). Explained @ SharePoint Saturday HoustonCSOM (Client Side Object Model). Explained @ SharePoint Saturday Houston
CSOM (Client Side Object Model). Explained @ SharePoint Saturday Houston
Kunaal Kapoor
 
Introduction to using jQuery with SharePoint
Introduction to using jQuery with SharePointIntroduction to using jQuery with SharePoint
Introduction to using jQuery with SharePoint
Rene Modery
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvcGuo Albert
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.Net
Hitesh Santani
 

What's hot (20)

SharePoint 2010 Client Object Model
SharePoint 2010 Client Object ModelSharePoint 2010 Client Object Model
SharePoint 2010 Client Object Model
 
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
 
SharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote AuthenticationSharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote Authentication
 
Understanding and programming the SharePoint REST API
Understanding and programming the SharePoint REST APIUnderstanding and programming the SharePoint REST API
Understanding and programming the SharePoint REST API
 
Are you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint AppsAre you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint Apps
 
SharePoint Client Object Model (CSOM)
SharePoint Client Object Model (CSOM)SharePoint Client Object Model (CSOM)
SharePoint Client Object Model (CSOM)
 
Working With Sharepoint 2013 Apps Development
Working With Sharepoint 2013 Apps DevelopmentWorking With Sharepoint 2013 Apps Development
Working With Sharepoint 2013 Apps Development
 
Develop iOS and Android apps with SharePoint/Office 365
Develop iOS and Android apps with SharePoint/Office 365Develop iOS and Android apps with SharePoint/Office 365
Develop iOS and Android apps with SharePoint/Office 365
 
SharePoint 2013 REST APIs
SharePoint 2013 REST APIsSharePoint 2013 REST APIs
SharePoint 2013 REST APIs
 
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
 
Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010Introduction to the Client OM in SharePoint 2010
Introduction to the Client OM in SharePoint 2010
 
SharePoint 2013 APIs
SharePoint 2013 APIsSharePoint 2013 APIs
SharePoint 2013 APIs
 
Introduction to SharePoint 2013 REST API
Introduction to SharePoint 2013 REST APIIntroduction to SharePoint 2013 REST API
Introduction to SharePoint 2013 REST API
 
SharePoint 2007 Presentation
SharePoint 2007 PresentationSharePoint 2007 Presentation
SharePoint 2007 Presentation
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Sharepoint Online
Sharepoint OnlineSharepoint Online
Sharepoint Online
 
CSOM (Client Side Object Model). Explained @ SharePoint Saturday Houston
CSOM (Client Side Object Model). Explained @ SharePoint Saturday HoustonCSOM (Client Side Object Model). Explained @ SharePoint Saturday Houston
CSOM (Client Side Object Model). Explained @ SharePoint Saturday Houston
 
Introduction to using jQuery with SharePoint
Introduction to using jQuery with SharePointIntroduction to using jQuery with SharePoint
Introduction to using jQuery with SharePoint
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.Net
 

Viewers also liked

Karine bosch andy-van_steenbergen-caml-spsbe12
Karine bosch andy-van_steenbergen-caml-spsbe12Karine bosch andy-van_steenbergen-caml-spsbe12
Karine bosch andy-van_steenbergen-caml-spsbe12
BIWUG
 
The SharePoint & jQuery Guide
The SharePoint & jQuery GuideThe SharePoint & jQuery Guide
The SharePoint & jQuery Guide
Mark Rackley
 
Social features in SharePoint 2013
Social features in SharePoint 2013Social features in SharePoint 2013
Social features in SharePoint 2013
Michael Doyle
 
Biwug 25092012 sp2013_itpro_hans_jaspers
Biwug 25092012 sp2013_itpro_hans_jaspersBiwug 25092012 sp2013_itpro_hans_jaspers
Biwug 25092012 sp2013_itpro_hans_jaspersBIWUG
 
LINQ to SharePoint
LINQ to SharePointLINQ to SharePoint
LINQ to SharePoint
André Vala
 
Deep Dive into the Content Query Web Part by Christina Wheeler - SPTechCon
Deep Dive into the Content Query Web Part by Christina Wheeler - SPTechConDeep Dive into the Content Query Web Part by Christina Wheeler - SPTechCon
Deep Dive into the Content Query Web Part by Christina Wheeler - SPTechCon
SPTechCon
 

Viewers also liked (6)

Karine bosch andy-van_steenbergen-caml-spsbe12
Karine bosch andy-van_steenbergen-caml-spsbe12Karine bosch andy-van_steenbergen-caml-spsbe12
Karine bosch andy-van_steenbergen-caml-spsbe12
 
The SharePoint & jQuery Guide
The SharePoint & jQuery GuideThe SharePoint & jQuery Guide
The SharePoint & jQuery Guide
 
Social features in SharePoint 2013
Social features in SharePoint 2013Social features in SharePoint 2013
Social features in SharePoint 2013
 
Biwug 25092012 sp2013_itpro_hans_jaspers
Biwug 25092012 sp2013_itpro_hans_jaspersBiwug 25092012 sp2013_itpro_hans_jaspers
Biwug 25092012 sp2013_itpro_hans_jaspers
 
LINQ to SharePoint
LINQ to SharePointLINQ to SharePoint
LINQ to SharePoint
 
Deep Dive into the Content Query Web Part by Christina Wheeler - SPTechCon
Deep Dive into the Content Query Web Part by Christina Wheeler - SPTechConDeep Dive into the Content Query Web Part by Christina Wheeler - SPTechCon
Deep Dive into the Content Query Web Part by Christina Wheeler - SPTechCon
 

Similar to Data Access Options in SharePoint 2010

Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
SPTechCon
 
ERRest - Designing a good REST service
ERRest - Designing a good REST serviceERRest - Designing a good REST service
ERRest - Designing a good REST service
WO Community
 
SharePoint TechCon 2009 - 907
SharePoint TechCon 2009 - 907SharePoint TechCon 2009 - 907
SharePoint TechCon 2009 - 907Andreas Grabner
 
Requery overview
Requery overviewRequery overview
Requery overview
Sunghyouk Bae
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
Mark Rackley
 
ERRest in Depth
ERRest in DepthERRest in Depth
ERRest in Depth
WO Community
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
Christian Melchior
 
Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to Solr
Jayesh Bhoyar
 
Summer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and ScalaSummer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and Scala
rostislav
 
Api design and usability
Api design and usabilityApi design and usability
Api design and usability
sumitamar
 
apidays LIVE LONDON - Data Retrieval via APIs - Showdown of GraphQL vs ODATA ...
apidays LIVE LONDON - Data Retrieval via APIs - Showdown of GraphQL vs ODATA ...apidays LIVE LONDON - Data Retrieval via APIs - Showdown of GraphQL vs ODATA ...
apidays LIVE LONDON - Data Retrieval via APIs - Showdown of GraphQL vs ODATA ...
apidays
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
Ismail Mayat
 
L12: REST Service
L12: REST ServiceL12: REST Service
L12: REST Service
medialeg gmbh
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
Nick Lee
 
YQL & Yahoo! Apis
YQL & Yahoo! ApisYQL & Yahoo! Apis
YQL & Yahoo! Apis
Jai Santhosh
 
State of search | drupalcamp ghent
State of search | drupalcamp ghentState of search | drupalcamp ghent
State of search | drupalcamp ghent
Joris Vercammen
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
.NET Conf UY
 

Similar to Data Access Options in SharePoint 2010 (20)

Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
 
ERRest - Designing a good REST service
ERRest - Designing a good REST serviceERRest - Designing a good REST service
ERRest - Designing a good REST service
 
ERRest and Dojo
ERRest and DojoERRest and Dojo
ERRest and Dojo
 
SharePoint TechCon 2009 - 907
SharePoint TechCon 2009 - 907SharePoint TechCon 2009 - 907
SharePoint TechCon 2009 - 907
 
Requery overview
Requery overviewRequery overview
Requery overview
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
ERRest in Depth
ERRest in DepthERRest in Depth
ERRest in Depth
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Rest
RestRest
Rest
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to Solr
 
Summer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and ScalaSummer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and Scala
 
Api design and usability
Api design and usabilityApi design and usability
Api design and usability
 
apidays LIVE LONDON - Data Retrieval via APIs - Showdown of GraphQL vs ODATA ...
apidays LIVE LONDON - Data Retrieval via APIs - Showdown of GraphQL vs ODATA ...apidays LIVE LONDON - Data Retrieval via APIs - Showdown of GraphQL vs ODATA ...
apidays LIVE LONDON - Data Retrieval via APIs - Showdown of GraphQL vs ODATA ...
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
 
L12: REST Service
L12: REST ServiceL12: REST Service
L12: REST Service
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
YQL & Yahoo! Apis
YQL & Yahoo! ApisYQL & Yahoo! Apis
YQL & Yahoo! Apis
 
State of search | drupalcamp ghent
State of search | drupalcamp ghentState of search | drupalcamp ghent
State of search | drupalcamp ghent
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 

Recently uploaded

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

Data Access Options in SharePoint 2010

  • 1. CAML, REST and LINQ - Data Access Options in SharePoint 2010 Rob Windsor rwindsor@allin.com @robwindsor #spsvb
  • 3. About Me • Senior SharePoint Architect with Allin Consulting • Technical Contributor to the Pluralsight On-Demand Library • Microsoft MVP, MCPD, MCT • Founder and Past-President of the North Toronto .NET UG • Co-author of Prof. Visual Basic 2010 and .NET 4 (Wrox)
  • 4. Lists • The data storage mechanism in SharePoint  Virtually all content stored in lists • Provisioning engine handles list creation and schema management • SharePoint provides interface to add, edit, delete and view items • Lists support:  Multiple views (for sorting, filtering, grouping)  Simple validation  Content approval  Item versioning • Data stored in rows and columns  More like Excel worksheets than database tables
  • 5. Accessing and Updating List Items • Field values accessed via SPListItem indexer • Generally accessed by internal name • Weakly typed var web = SPContext.Current.Web; var web = SPContext.Current.Web; var list = web.Lists.TryGetList("Products"); var list = web.Lists.TryGetList("Products"); if (list == null) return; if (list == null) return; foreach (SPListItem item in list.Items) foreach (SPListItem item in list.Items) { { Console.WriteLine("{0} ({1})", var price = Convert.ToDouble( item["Title"], item["UnitPrice"]); item["UnitPrice"]); price *= 1.1; } item["UnitPrice"] = price; item.Update(); }
  • 6. Field Names • Fields have three names  Display name  The name displayed to the end user  Can be changed  Internal name  Set when field is created  Does not change  Non-alphanumeric chars escaped (e.g. Unit_x0020_Price)  Find using Server Explorer  Static name  Used by custom field types
  • 7. CAML Queries • Query list items using XML syntax • SPQuery  Query single list  Returns SPLitsItemCollection • SPSiteDataQuery  Query multiple lists across site collection  Returns DataSet
  • 8. CAML Queries var query = new SPQuery(); query.ViewFields = "<FieldRef Name='Title' />" + "<FieldRef Name='UnitPrice' />"; query.Query = "<OrderBy>" + " <FieldRef Name='Title' />" + "</OrderBy>" + "<Where>" + " <And>" + " <Gt>" + " <FieldRef Name='UnitsInStock' />" + " <Value Type='Integer'>0</Value>" + " </Gt>" + " <Eq>" + " <FieldRef Name='Category' LookupId='True' />" + " <Value Type='Lookup'>1</Value>" + " </Eq>" + " </And>" + "</Where>"; var items = list.GetItems(query);
  • 9. “All we can do is decide what to do with the time tools that is are given us” Image from The Lord of the Rings: The Fellowship of the Ring by New Line Cinema
  • 10. Large List Throttling • Lists can store millions of items • Retrieval of items is throttled  Max 5,000 items  Max 20,000 for Owners  No max for local admin • Can override limits in code  QueryThrottleMode • Can configure time window where limits are ignored  For reporting, list aggregation, etc  Done during off-peak hours
  • 12. Joins in CAML Queries • SPQuery supports joins  SPSiteDataQuery does not • Joins can only be done on lookup columns • Key properties  Joins: Define joins to other lists  ProjectedFields: Fields being projected from the foreign list • Only inner and left outer joins are supported
  • 13. SPQuery with Join Example var query = new SPQuery { RowLimit = 5 }; query.ProjectedFields = "<Field Name='CategoryTitle' Type='Lookup' List='productCategory' ShowField='Title' />"; query.ViewFields = "<FieldRef Name='Title' />" + "<FieldRef Name='UnitPrice' />" + "<FieldRef Name='UnitsInStock' />" + "<FieldRef Name='CategoryTitle' />"; query.Query = "<Where>" + " <And>" + " <Gt>" + " <FieldRef Name='UnitsInStock' />" + " <Value Type='Integer'>0</Value>" + " </Gt>" + " <Eq>" + " <FieldRef Name='CategoryTitle' />" + " <Value Type='Text'>Condiments</Value>" + " </Eq>" + " </And>" + "</Where>"; query.Joins = "<Join Type='INNER' ListAlias='productCategory'>" + " <Eq>" + " <FieldRef Name='Category' RefType='ID' />" + " <FieldRef List='productCategory' Name='ID' />" + " </Eq>" + "</Join>"; return list.GetItems(query);
  • 14. Querying Multiple Lists with SPSiteDataQuery • Core properties the same as SPQuery • Cannot query lists outside site collection • Key additional properties  Lists  Defines which lists will be included in query  Use ServerTemplate for OOB content types  Use BaseType plus filter for ID in where clause for custom content types  Webs  Defines the scope of the query  SiteCollection – Query all matching lists in site collection  Recursive: – Query all matching lists in current Web and it’s children
  • 15. SPSiteDataQuery Example var query = new SPSiteDataQuery { RowLimit = 50 }; query.ViewFields = "<FieldRef Name='Title' />" + "<FieldRef Name='DueDate' />" + "<FieldRef Name='AssignedTo' />"; query.Query = "<Where>" + " <And>" + " <Geq>" + " <FieldRef Name='DueDate' />" + " <Value Type='DateTime'><Today /></Value>" + " </Geq>" + " <Leq>" + " <FieldRef Name='DueDate' />" + " <Value Type='DateTime'><Today OffsetDays='5' /></Value>" + " </Leq>" + " </And>" + "</Where>"; query.Lists = "<Lists ServerTemplate='107' />"; <!– Task Lists --> query.Webs = "<Webs Scope='SiteCollection' />"; return web.GetSiteData(query);
  • 16. DEMO List access using Server Object Model
  • 17. REST APIs • Generally used by remote applications • Uses Open Data (oData) Protocol  Also known as: Astoria, ADO.NET Data Services, WCF Data Services  Data centric (REST) Web service  Data returned in AtomPub or JSON format  Metadata is available  Allows creation of service proxy  Strongly-typed access to data  Requests for collections may not return all items  Max 1,000 items returned per request  Need to check for continuation
  • 18. REST APIs • Urls map to SharePoint resources  Example: ListData.svc/Products(2)/Category maps to the category for the product with id == 2 • Protocol commands  $filter={simple predicate}  $expand={Entity}  $orderby={property}  $skip=n  $top=n  $metadata
  • 20. Consuming Data via REST APIs
  • 21. Consuming Data via REST APIs var context = new DemoDataContext(new Uri( SiteUrl + @"_vti_bin/ListData.svc")); context.Credentials = CredentialCache.DefaultCredentials; var query = from detail in context.OrderDetails where detail.UnitPrice < 100 select detail;
  • 22. Consuming Data via REST APIs var context = new DemoDataContext(new Uri( "http://localhost/sites/demo/_vti_bin/ListData.svc")); context.Credentials = CredentialCache.DefaultCredentials; var query = from detail in context.OrderDetails where detail.UnitPrice < 100 select detail; var queryCount = query.Count(); var details = new List<OrderDetailsItem>(); var dsquery = query as DataServiceQuery<OrderDetailsItem>; var response = dsquery.Execute() as QueryOperationResponse<OrderDetailsItem>; details.AddRange(response); var token = response.GetContinuation(); while (token != null) { response = context.Execute(token); details.AddRange(response); token = response.GetContinuation(); }
  • 23. Consuming Data via REST APIs var url = "http://localhost/sites/demo/_vti_bin/ListData.svc"; var context = new DemoProxy.DemoDataContext(new Uri(url)); context.Credentials = System.Net.CredentialCache.DefaultCredentials; var products = from product in context.Products where product.Category.Title == "Condiments" && product.UnitsInStock > 0 select product; foreach (var product in products) { product.UnitsInStock += 1; context.UpdateObject(product); // don’t forget this } context.SaveChanges();
  • 25. LINQ to SharePoint • LINQ provider generates CAML for query  Requires reference to Microsoft.SharePoint.Linq.dll • Only available to server object model • Queries are strongly-typed • Entities created using SPMetal command-line utility  Similar to SqlMetal in LINQ to SQL  Located in <System root>bin  Basic usage  spmetal /web:<site url> /code:<file name>  Code generation can be customized via parameters XML file  http://msdn.microsoft.com/en-us/library/ee535056.aspx
  • 26. Consuming Data with LINQ to SharePoint var url = "http://localhost/sites/demo"; var context = new SPNorthwind.SPNorthwindDataContext(url); // context.Log = Console.Out; var products = from product in context.Products where product.Category.Title == "Condiments" && product.UnitsInStock > 0 select product; foreach (var product in products) { product.UnitsInStock += 1; } context.SubmitChanges();
  • 28. Thank You • Big thanks to the organizers, sponsors and you for making this event possible • Please fill out your evaluation • Please keep in touch rwindsor@allin.com @robwindsor msmvps.com/blogs/windsor