SlideShare uma empresa Scribd logo
1 de 27
Baixar para ler offline
Techniques to Access
List Data




Rob Windsor
rwindsor@portalsolutions.net
@robwindsor
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
• Use QueryThrottleMode to enable/disable throttling
   Enabled by default
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);
SPQuery.ViewAttributes
• Scope
     Default = Show files and folders of specific folder
     FilesOnly = Show files of specific folder
     Recursive = Shows files in all folders
     RecursiveAll = Show files and folders in all folders
• Moderation
   HideUnapproved = Don’t show draft items
   Contributor = Show draft items for current user only
   Moderator = Show draft items
• Syntax
   Query.ViewAttributes = "Scope='Recursive'"
“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
Paging CAML Queries
• Seriously convoluted for all but the simplest cases
• Paging managed by SPListItemCollectionPosition
    Only supports Prev / Next paging
    Cannot jump to a specific page
• PagingInfo
    String representing the parameters used to get the next page of
     items
    Parts
        Paged=TRUE – the list is paged
        PagedPrev=TRUE – retrieve the previous page
        p_ID=n – list item id of the first or last value in the set last retrieved
        p_<Field Name>=v - value of first or last value of the order by field in the set
         last retrieved
        PageFirstRow – the position of the last item in the last set retrieved
CAML Queries
var list = SPContext.Current.Web.Lists["Announcements"];
var query = new SPQuery();
query.RowLimit = 10;
query.Query = "<OrderBy Override="TRUE">" +
    "<FieldRef Name="FileLeafRef" /></OrderBy>";

do
{
     var items = list.GetItems(query);

     // work with items

    query.ListItemCollectionPosition =
        items.ListItemCollectionPosition;
} while (query.ListItemCollectionPosition != null);
List Relationships
Joins in CAML Queries
• SPQuery supports joins
    SPSiteDataQuery does not
• Joins can only be done on lookup columns
• Key properties
    J oins: 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(
    "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

Mais conteúdo relacionado

Mais procurados

Dm adapter RubyConf.TW
Dm adapter RubyConf.TWDm adapter RubyConf.TW
Dm adapter RubyConf.TWcodingforrent
 
Using Apache Solr
Using Apache SolrUsing Apache Solr
Using Apache Solrpittaya
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridgeRomans Malinovskis
 
Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)Wongnai
 
Asp.net create delete directory folder in c# vb.net
Asp.net   create delete directory folder in c# vb.netAsp.net   create delete directory folder in c# vb.net
Asp.net create delete directory folder in c# vb.netrelekarsushant
 
Learn Ajax here
Learn Ajax hereLearn Ajax here
Learn Ajax herejarnail
 
Web осень 2012 лекция 6
Web осень 2012 лекция 6Web осень 2012 лекция 6
Web осень 2012 лекция 6Technopark
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETTomas Jansson
 
appengine java night #1
appengine java night #1appengine java night #1
appengine java night #1Shinichi Ogawa
 
Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6Technopark
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of SlickKnoldus Inc.
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Rebecca Grenier
 
The Ring programming language version 1.5.2 book - Part 44 of 181
The Ring programming language version 1.5.2 book - Part 44 of 181The Ring programming language version 1.5.2 book - Part 44 of 181
The Ring programming language version 1.5.2 book - Part 44 of 181Mahmoud Samir Fayed
 
Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to SolrJayesh Bhoyar
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateKiev ALT.NET
 

Mais procurados (19)

Dm adapter
Dm adapterDm adapter
Dm adapter
 
Dm adapter RubyConf.TW
Dm adapter RubyConf.TWDm adapter RubyConf.TW
Dm adapter RubyConf.TW
 
Using Apache Solr
Using Apache SolrUsing Apache Solr
Using Apache Solr
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridge
 
Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)Solr's Search Relevancy (Understand Solr's query debug)
Solr's Search Relevancy (Understand Solr's query debug)
 
Asp.net create delete directory folder in c# vb.net
Asp.net   create delete directory folder in c# vb.netAsp.net   create delete directory folder in c# vb.net
Asp.net create delete directory folder in c# vb.net
 
Learn Ajax here
Learn Ajax hereLearn Ajax here
Learn Ajax here
 
Web осень 2012 лекция 6
Web осень 2012 лекция 6Web осень 2012 лекция 6
Web осень 2012 лекция 6
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
 
appengine java night #1
appengine java night #1appengine java night #1
appengine java night #1
 
Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
CAVE Overview
CAVE OverviewCAVE Overview
CAVE Overview
 
Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access Slick: Bringing Scala’s Powerful Features to Your Database Access
Slick: Bringing Scala’s Powerful Features to Your Database Access
 
The Ring programming language version 1.5.2 book - Part 44 of 181
The Ring programming language version 1.5.2 book - Part 44 of 181The Ring programming language version 1.5.2 book - Part 44 of 181
The Ring programming language version 1.5.2 book - Part 44 of 181
 
Recursive Query Throwdown
Recursive Query ThrowdownRecursive Query Throwdown
Recursive Query Throwdown
 
Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to Solr
 
How to Use JSON in MySQL Wrong
How to Use JSON in MySQL WrongHow to Use JSON in MySQL Wrong
How to Use JSON in MySQL Wrong
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 

Destaque

Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...SPTechCon
 
JavaScript and jQuery for SharePoint Developers
JavaScript and jQuery for SharePoint DevelopersJavaScript and jQuery for SharePoint Developers
JavaScript and jQuery for SharePoint DevelopersRob Windsor
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIRob Windsor
 
Tutorial, Part 1: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 1: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 1: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 1: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...SPTechCon
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Rob Windsor
 
SharePoint 2010 Application Development Overview
SharePoint 2010 Application Development OverviewSharePoint 2010 Application Development Overview
SharePoint 2010 Application Development OverviewRob Windsor
 
Integrating SharePoint 2010 and Visual Studio Lightswitch
Integrating SharePoint 2010 and Visual Studio LightswitchIntegrating SharePoint 2010 and Visual Studio Lightswitch
Integrating SharePoint 2010 and Visual Studio LightswitchRob Windsor
 

Destaque (7)

Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
 
JavaScript and jQuery for SharePoint Developers
JavaScript and jQuery for SharePoint DevelopersJavaScript and jQuery for SharePoint Developers
JavaScript and jQuery for SharePoint Developers
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST API
 
Tutorial, Part 1: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 1: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 1: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 1: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010
 
SharePoint 2010 Application Development Overview
SharePoint 2010 Application Development OverviewSharePoint 2010 Application Development Overview
SharePoint 2010 Application Development Overview
 
Integrating SharePoint 2010 and Visual Studio Lightswitch
Integrating SharePoint 2010 and Visual Studio LightswitchIntegrating SharePoint 2010 and Visual Studio Lightswitch
Integrating SharePoint 2010 and Visual Studio Lightswitch
 

Semelhante a Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor - SPTec…

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 Scalarostislav
 
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자Donghyeok Kang
 
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-spsbe12BIWUG
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
Api design and usability
Api design and usabilityApi design and usability
Api design and usabilitysumitamar
 
SharePoint TechCon 2009 - 907
SharePoint TechCon 2009 - 907SharePoint TechCon 2009 - 907
SharePoint TechCon 2009 - 907Andreas Grabner
 
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
 
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
 
Appengine Java Night #2a
Appengine Java Night #2aAppengine Java Night #2a
Appengine Java Night #2aShinichi Ogawa
 
Advance java session 3
Advance java session 3Advance java session 3
Advance java session 3Smita B Kumar
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An AnalysisJustin Finkelstein
 
Elasticsearch and Symfony Integration - Debarko De
Elasticsearch and Symfony Integration - Debarko DeElasticsearch and Symfony Integration - Debarko De
Elasticsearch and Symfony Integration - Debarko DeDebarko De
 

Semelhante a Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor - SPTec… (20)

ERRest in Depth
ERRest in DepthERRest in Depth
ERRest in Depth
 
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
 
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
[제1회 루씬 한글분석기 기술세미나] solr로 나만의 검색엔진을 만들어보자
 
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
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
AJAX.ppt
AJAX.pptAJAX.ppt
AJAX.ppt
 
Api design and usability
Api design and usabilityApi design and usability
Api design and usability
 
SharePoint TechCon 2009 - 907
SharePoint TechCon 2009 - 907SharePoint TechCon 2009 - 907
SharePoint TechCon 2009 - 907
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
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 ...
 
Requery overview
Requery overviewRequery overview
Requery overview
 
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
 
ERRest and Dojo
ERRest and DojoERRest and Dojo
ERRest and Dojo
 
Appengine Java Night #2a
Appengine Java Night #2aAppengine Java Night #2a
Appengine Java Night #2a
 
Advance java session 3
Advance java session 3Advance java session 3
Advance java session 3
 
Drupal7 dbtng
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
 
Jersey
JerseyJersey
Jersey
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An Analysis
 
Elasticsearch and Symfony Integration - Debarko De
Elasticsearch and Symfony Integration - Debarko DeElasticsearch and Symfony Integration - Debarko De
Elasticsearch and Symfony Integration - Debarko De
 

Mais de SPTechCon

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 - SPTechConSPTechCon
 
NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...
NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...
NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...SPTechCon
 
“Managing Up” in Difficult Situations by Bill English - SPTechCon
“Managing Up” in Difficult Situations by Bill English - SPTechCon“Managing Up” in Difficult Situations by Bill English - SPTechCon
“Managing Up” in Difficult Situations by Bill English - SPTechConSPTechCon
 
Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...
Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...
Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...SPTechCon
 
Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...
Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...
Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...SPTechCon
 
Microsoft Keynote by Richard Riley - SPTechCon
Microsoft Keynote by Richard Riley - SPTechConMicrosoft Keynote by Richard Riley - SPTechCon
Microsoft Keynote by Richard Riley - SPTechConSPTechCon
 
Ten Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechCon
Ten Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechConTen Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechCon
Ten Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechConSPTechCon
 
Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...
Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...
Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...SPTechCon
 
Law & Order: Content Governance Strategies by Chrisitan Buckley - SPTechCon
Law & Order: Content Governance Strategies by Chrisitan Buckley - SPTechConLaw & Order: Content Governance Strategies by Chrisitan Buckley - SPTechCon
Law & Order: Content Governance Strategies by Chrisitan Buckley - SPTechConSPTechCon
 
What IS SharePoint Development? by Mark Rackley - SPTechCon
 What IS SharePoint Development? by Mark Rackley - SPTechCon What IS SharePoint Development? by Mark Rackley - SPTechCon
What IS SharePoint Development? by Mark Rackley - SPTechConSPTechCon
 
The SharePoint and jQuery Guide by Mark Rackley - SPTechCon
The SharePoint and jQuery Guide by Mark Rackley - SPTechConThe SharePoint and jQuery Guide by Mark Rackley - SPTechCon
The SharePoint and jQuery Guide by Mark Rackley - SPTechConSPTechCon
 
Understanding and Implementing Governance for SharePoint 2010 by Bill English...
Understanding and Implementing Governance for SharePoint 2010 by Bill English...Understanding and Implementing Governance for SharePoint 2010 by Bill English...
Understanding and Implementing Governance for SharePoint 2010 by Bill English...SPTechCon
 
Integrate External Data with the Business Connectivity Services by Tom Resing...
Integrate External Data with the Business Connectivity Services by Tom Resing...Integrate External Data with the Business Connectivity Services by Tom Resing...
Integrate External Data with the Business Connectivity Services by Tom Resing...SPTechCon
 
Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...
Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...
Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...SPTechCon
 
Tutorial: Best Practices for Building a Records-Management Deployment in Shar...
Tutorial: Best Practices for Building a Records-Management Deployment in Shar...Tutorial: Best Practices for Building a Records-Management Deployment in Shar...
Tutorial: Best Practices for Building a Records-Management Deployment in Shar...SPTechCon
 
Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...
Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...
Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...SPTechCon
 
Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...
Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...
Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...SPTechCon
 
Sponsored Session: Better Document Management Using SharePoint by Roland Simo...
Sponsored Session: Better Document Management Using SharePoint by Roland Simo...Sponsored Session: Better Document Management Using SharePoint by Roland Simo...
Sponsored Session: Better Document Management Using SharePoint by Roland Simo...SPTechCon
 
Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...
Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...
Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...SPTechCon
 
Creating a Great User Experience in SharePoint by Marc Anderson - SPTechCon
Creating a Great User Experience in SharePoint by Marc Anderson - SPTechConCreating a Great User Experience in SharePoint by Marc Anderson - SPTechCon
Creating a Great User Experience in SharePoint by Marc Anderson - SPTechConSPTechCon
 

Mais de SPTechCon (20)

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
 
NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...
NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...
NOW I Get It... What SharePoint Is, and Why My Business Needs It by Mark Rack...
 
“Managing Up” in Difficult Situations by Bill English - SPTechCon
“Managing Up” in Difficult Situations by Bill English - SPTechCon“Managing Up” in Difficult Situations by Bill English - SPTechCon
“Managing Up” in Difficult Situations by Bill English - SPTechCon
 
Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...
Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...
Part I: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTec...
 
Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...
Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...
Part II: SharePoint 2013 Administration by Todd Klindt and Shane Young - SPTe...
 
Microsoft Keynote by Richard Riley - SPTechCon
Microsoft Keynote by Richard Riley - SPTechConMicrosoft Keynote by Richard Riley - SPTechCon
Microsoft Keynote by Richard Riley - SPTechCon
 
Ten Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechCon
Ten Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechConTen Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechCon
Ten Best SharePoint Features You’ve Never Used by Christian Buckley - SPTechCon
 
Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...
Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...
Looking Under the Hood: How Your Metadata Strategy Impacts Everything You Do ...
 
Law & Order: Content Governance Strategies by Chrisitan Buckley - SPTechCon
Law & Order: Content Governance Strategies by Chrisitan Buckley - SPTechConLaw & Order: Content Governance Strategies by Chrisitan Buckley - SPTechCon
Law & Order: Content Governance Strategies by Chrisitan Buckley - SPTechCon
 
What IS SharePoint Development? by Mark Rackley - SPTechCon
 What IS SharePoint Development? by Mark Rackley - SPTechCon What IS SharePoint Development? by Mark Rackley - SPTechCon
What IS SharePoint Development? by Mark Rackley - SPTechCon
 
The SharePoint and jQuery Guide by Mark Rackley - SPTechCon
The SharePoint and jQuery Guide by Mark Rackley - SPTechConThe SharePoint and jQuery Guide by Mark Rackley - SPTechCon
The SharePoint and jQuery Guide by Mark Rackley - SPTechCon
 
Understanding and Implementing Governance for SharePoint 2010 by Bill English...
Understanding and Implementing Governance for SharePoint 2010 by Bill English...Understanding and Implementing Governance for SharePoint 2010 by Bill English...
Understanding and Implementing Governance for SharePoint 2010 by Bill English...
 
Integrate External Data with the Business Connectivity Services by Tom Resing...
Integrate External Data with the Business Connectivity Services by Tom Resing...Integrate External Data with the Business Connectivity Services by Tom Resing...
Integrate External Data with the Business Connectivity Services by Tom Resing...
 
Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...
Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...
Converting an E-mail Culture into a SharePoint Culture by Robert Bogue - SPTe...
 
Tutorial: Best Practices for Building a Records-Management Deployment in Shar...
Tutorial: Best Practices for Building a Records-Management Deployment in Shar...Tutorial: Best Practices for Building a Records-Management Deployment in Shar...
Tutorial: Best Practices for Building a Records-Management Deployment in Shar...
 
Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...
Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...
Tutorial: Building Business Solutions: InfoPath & Workflows by Jennifer Mason...
 
Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...
Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...
Creating Simple Dashboards Using Out-of-the-Box Web Parts by Jennifer Mason- ...
 
Sponsored Session: Better Document Management Using SharePoint by Roland Simo...
Sponsored Session: Better Document Management Using SharePoint by Roland Simo...Sponsored Session: Better Document Management Using SharePoint by Roland Simo...
Sponsored Session: Better Document Management Using SharePoint by Roland Simo...
 
Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...
Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...
Sponsored Session: The Missing Link: Content-Aware Integration to SharePoint ...
 
Creating a Great User Experience in SharePoint by Marc Anderson - SPTechCon
Creating a Great User Experience in SharePoint by Marc Anderson - SPTechConCreating a Great User Experience in SharePoint by Marc Anderson - SPTechCon
Creating a Great User Experience in SharePoint by Marc Anderson - SPTechCon
 

Tutorial, Part 3: SharePoint 101: Jump-Starting the Developer by Rob Windsor - SPTec…

  • 1. Techniques to Access List Data Rob Windsor rwindsor@portalsolutions.net @robwindsor
  • 2. 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
  • 3. 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(); }
  • 4. 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
  • 5. CAML Queries • Query list items using XML syntax • SPQuery  Query single list  Returns SPLitsItemCollection • SPSiteDataQuery  Query multiple lists across site collection  Returns DataSet • Use QueryThrottleMode to enable/disable throttling  Enabled by default
  • 6. 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);
  • 7. SPQuery.ViewAttributes • Scope  Default = Show files and folders of specific folder  FilesOnly = Show files of specific folder  Recursive = Shows files in all folders  RecursiveAll = Show files and folders in all folders • Moderation  HideUnapproved = Don’t show draft items  Contributor = Show draft items for current user only  Moderator = Show draft items • Syntax  Query.ViewAttributes = "Scope='Recursive'"
  • 8. “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
  • 9. 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
  • 10. Paging CAML Queries • Seriously convoluted for all but the simplest cases • Paging managed by SPListItemCollectionPosition  Only supports Prev / Next paging  Cannot jump to a specific page • PagingInfo  String representing the parameters used to get the next page of items  Parts  Paged=TRUE – the list is paged  PagedPrev=TRUE – retrieve the previous page  p_ID=n – list item id of the first or last value in the set last retrieved  p_<Field Name>=v - value of first or last value of the order by field in the set last retrieved  PageFirstRow – the position of the last item in the last set retrieved
  • 11. CAML Queries var list = SPContext.Current.Web.Lists["Announcements"]; var query = new SPQuery(); query.RowLimit = 10; query.Query = "<OrderBy Override="TRUE">" + "<FieldRef Name="FileLeafRef" /></OrderBy>"; do { var items = list.GetItems(query); // work with items query.ListItemCollectionPosition = items.ListItemCollectionPosition; } while (query.ListItemCollectionPosition != null);
  • 13. Joins in CAML Queries • SPQuery supports joins  SPSiteDataQuery does not • Joins can only be done on lookup columns • Key properties  J oins: Define joins to other lists  ProjectedFields: Fields being projected from the foreign list • Only inner and left outer joins are supported
  • 14. 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);
  • 15. 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
  • 16. 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);
  • 17. DEMO List access using Server Object Model
  • 18. 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
  • 19. 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
  • 21. Consuming Data via REST APIs
  • 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();