SlideShare a Scribd company logo
1 of 17
SPMetal
Pranav Sharma
http://pranavsharma.info

Senior SharePoint Consultant
Portal Solutions
http://www.portalsolutions.net

Twitter: @ePranav
What is SPMetal and LINQ?
“SPMetal is a command-line tool that generates entity classes, which provide an object-
oriented interface to the Microsoft SharePoint Foundation content databases. These
classes are primarily used in LINQ to SharePoint queries; but they are also used to add,
delete, and change list items with concurrency conflict resolution. Finally, they can be
used as an alternative to the regular SharePoint Foundation object model for
referencing content.

The tool is included with SharePoint Foundation and is located in
%ProgramFiles%Common FilesMicrosoft Sharedweb server extensions14BIN”
Language-Integrated Query (LINQ) is a set of features that extends powerful query
capabilities to the language syntax of C# and VB. LINQ introduces standard, easily-
learned patterns for querying and updating data, and the technology can be extended to
support potentially any kind of data store” (MSDN)
Let’s create a sample list
Setting up SPMetal
 Create PreBuild.bat and save with encoding: Unicode (UTF-8 without
  signature) – codepage 65001
 Include generated codefile in project
 Add project reference to Microsoft.SharePoint.Linq.dll
 Sign project using key file
Options (1 of 3)
Option     Value definition    Example                    Comments
web        The complete,       /web:http://ContosoServer/ Required. You can have port numbers in the server name; for
           absolute URL of     Marketing                  example, /web:http://ContosoServer:5555/Marketing.
           the Web site                                   Do not include the home page or any other page in the URL.
           whose data is
           modeled by the
           entity classes.
code       The relative or     /code:MarketingSite.cs      If this option is not used, the generated code is streamed to standard
           absolute path and                               output.
           file name of the                                If no file name extension is specified or the file name extension is not
           output file.                                    either "cs" or "vb", the language option must be used.
                                                           The file name (exclusive of the extension) is also used to form the
                                                           beginning of the name of a class that derives fromDataContext; in this
                                                           example the class is namedMarketingSiteDataContext. The derived
                                                           class represents the lists and data of the whole Web site, so choose a
                                                           file name that conveys that meaning. (You can override this naming
                                                           behavior with an SPMetal Parameters XML file.)
language   The programming /language:csharp                The only possible values are "csharp" and "vb".
           language of the                                 If the value of the code option has either "cs" or "vb" as a file name
           generated code.                                 extension, SPMetal can infer the language and thelanguage option is not
                                                           needed.
namespace The namespace        /namespace:Contoso.TeamA If this option is not used, the generated code specifies no namespace
          that contains the    ctivityReports           and the compiled assembly treats the default namespace specified in
          entity class                                  the properties of the Visual Studio project as the namespace of the
          declarations.                                 generated classes.
Options (2 of 3)
Option       Value definition                 Example                        Comments
useremoteapi No value.                        /useremoteapi                  This option signals that the value of the web parameter
                                                                             points to a server that is not the one on which SPMetal
                                                                             is running. One possible use for this parameter is to
                                                                             generate code against a Web site on an online
                                                                             deployment of SharePoint to which you intend to upload
                                                                             your solution as a sandboxed solution.
user            The user in whose context /user:Contosobob                  Use this option if you do not want SPMetal to run in
                SPMetal executes.                                            your own context. Specify the domain.
password        The password for the user /password:$5U+ryz                  Use in conjunction with the user option.
                specified in theuser option.
serialization   Specifies whether objects    /serialization:unidirectional The only possible values are "unidirectional" and
                that instantiate the                                       "none". Specify "unidirectional" if you want the objects
                generated classes are                                      to be serializable. SPMetal adds appropriate attributes
                serializable.                                              from theSystem.Runtime.Serialization namespace to the
                                                                           class and property declarations and adds handlers for
                                                                           the Deserializing event.
                                                                           If this option is not used, "none" is assumed.
parameters      Identifies the path and name /parameters:MarketingSite.xml You typically will not reuse exactly the same parameters
                of an XML file that contains                               XML file for different Web sites, so name the file the
                overrides of SPMetal default                               same as the Web site.
                settings.                                                  For more information about the parameters file,
                                                                           see Overriding SPMetal Defaults by Using a Parameters
                                                                           XML File.
Options (3 of 3)
<?xml version="1.0" encoding="utf-8"?>
<Web AccessModifier="Internal"
xmlns="http://schemas.microsoft.com/SharePoint/2009/spmetal">
          <ContentType Name="Contact" Class="Contact">
                    <Column Name="ContId" Member="ContactId" />
                    <Column Name="ContactName" Member="ContactName1" />
                    <Column Name="Category" Member="Cat" Type="String"/>
                    <ExcludeColumn Name="HomeTelephone" />
          </ContentType>
          <ExcludeContentType Name="Order"/>
          <List Name="Team Members" Type="TeamMember">
                    <ContentType Name="Item" Class="TeamMember" />
          </List>
</Web>
Logging
Use the DataContext’s Log property to inspect underlying SPQueries


using (var context = new Sp2010DataContext("http://sp2010"))
{
   var contextLog = new StringBuilder();
   context.Log = new StringWriter(contextLog);
   Console.WriteLine(contextLog);
}
Iterating
foreach (var myItem in context.MyList)
{
        Console.WriteLine(myItem.Title);
        Console.WriteLine("   ->" + myItem.MyColumnChoice);
        //Console.WriteLine("   ->" + myItem.MyColumnManagedMetadata);
}




Querying
Console.WriteLine((from myItem in context.MyList
                   where myItem.MyColumnChoice.Equals(MyColumnChoice.BarackObama)
                   select myItem.Title).
                   FirstOrDefault());
Complex field types (1 of 3)
private TaxonomyFieldValue _myColumnManagedMetadata;


 [ColumnAttribute(Name = "MyColumnManagedMetadata", Storage =
"_myColumnManagedMetadata", FieldType = “Taxonomy")]
public TaxonomyFieldValue MyColumnManagedMetadata
{
   get { return _myColumnManagedMetadata; }
   set
   {
       if ((value != _myColumnManagedMetadata))
       {
          this.OnPropertyChanging("MyColumnManagedMetadata", _myColumnManagedMetadata);
          _myColumnManagedMetadata = value;
          this.OnPropertyChanged("MyColumnManagedMetadata");
       }
   }
}
Complex field types (2 of 3)
[CustomMapping(Columns = new String[] {"MyColumnManagedMetadata"})]
public void MapFrom(object listItem)
{
   var item = (SPListItem) listItem;
   this.MyColumnManagedMetadata = item["MyColumnManagedMetadata"] as TaxonomyFieldValue;
}




         public void MapTo(object listItem)
         {
            var item = (SPListItem)listItem;
            item["MyColumnManagedMetadata"] = this.MyColumnManagedMetadata;
         }
Complex field types (3 of 3)
public void Resolve(RefreshMode mode, object originalListItem, object databaseListItem)
{
   var origItem = (SPListItem) originalListItem;
   var dbItem = (SPListItem) databaseListItem;

    var origValue = (TaxonomyFieldValue) origItem["MyColumnManagedMetadata"];
    var dbValue = (TaxonomyFieldValue) dbItem["MyColumnManagedMetadata"];

    if (mode == RefreshMode.KeepCurrentValues ||
       (mode == RefreshMode.KeepChanges &&
        MyColumnManagedMetadata != origValue))
    {
        dbItem["MyColumnManagedMetadata"] = MyColumnManagedMetadata;
    } else if (mode == RefreshMode.OverwriteCurrentValues ||
              (mode == RefreshMode.KeepChanges &&
               MyColumnManagedMetadata == origValue &&
               MyColumnManagedMetadata != dbValue))
           {
               MyColumnManagedMetadata = dbValue;
           }
}
Updating
foreach (var myItem in context.MyList)
{
   switch (myItem.Title)
   {
      case “Choice 1":
         myItem.MyColumnChoice = MyColumnChoice.BarackObama;
         break;
      case “Choice 2":
         myItem.MyColumnChoice = MyColumnChoice.MittRomney;
         break;
      default:
         myItem.MyColumnChoice = MyColumnChoice.None;
         break;
   }
}
context.SubmitChanges();
Inserting
var newItem = new MyListItem
                   {
                         Title = "Choice 3",
                         MyColumnChoice = "Donald Trump"
                   };
context.MyList.InsertOnSubmit(newItem);
context.SubmitChanges();
When to use SPMetal?
 “While testing with a list of 45K items, SPQuery performed at 0.06s
  compared to SPMetal’s performance at 9.98s” – Pranav Sharma (See
  Resources for full article)
 When to use SPMetal?
     For quick wins when low on time
     For low usage applications where list size doesn’t cause performance concerns
     For easily binding SharePoint queries to data grids and repeaters
     For complex query writing (Ex: Multi-list Lookups)
     For new SP developers to avoid run-time errors by catching them at compile-time
Resources
 SPMetal (MSDN) http://bit.ly/icXOmf
 How to: Use SPMetal (MSDN) http://bit.ly/hLPbjo
 Overriding SPMetal Defaults by Using a Parameters XML File (MSDN)
  http://bit.ly/M3zSyH
 SPMetal and the Managed Metadata Column http://bit.ly/HteBbp
 Large list performance: SPMetal vs. SPQuery http://bit.ly/sYvAEL
Questions?
 Don’t forget to fill out evaluations online
 Show the sponsors some love


Pranav Sharma
http://pranavsharma.info

Senior SharePoint Consultant
Portal Solutions
http://www.portalsolutions.net

Twitter: @ePranav

More Related Content

What's hot

What's hot (17)

Data weave documentation
Data weave documentationData weave documentation
Data weave documentation
 
Java Annotation
Java AnnotationJava Annotation
Java Annotation
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Java 8-revealed
Java 8-revealedJava 8-revealed
Java 8-revealed
 
Data weave component
Data weave componentData weave component
Data weave component
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
Dost.jar and fo.jar
Dost.jar and fo.jarDost.jar and fo.jar
Dost.jar and fo.jar
 
iOS Application Development
iOS Application DevelopmentiOS Application Development
iOS Application Development
 
Instant DBMS Homework Help
Instant DBMS Homework HelpInstant DBMS Homework Help
Instant DBMS Homework Help
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
 
Annotations
AnnotationsAnnotations
Annotations
 
Pdf open parameters
Pdf open parametersPdf open parameters
Pdf open parameters
 
XMPPart5
XMPPart5XMPPart5
XMPPart5
 
4. plsql
4. plsql4. plsql
4. plsql
 
Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6Object Oriented Programming with Laravel - Session 6
Object Oriented Programming with Laravel - Session 6
 
10g plsql slide
10g plsql slide10g plsql slide
10g plsql slide
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
 

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-spsbe12BIWUG
 
Biwug 25092012 sp2013_itpro_hans_jaspers
Biwug 25092012 sp2013_itpro_hans_jaspersBiwug 25092012 sp2013_itpro_hans_jaspers
Biwug 25092012 sp2013_itpro_hans_jaspersBIWUG
 
How To Successfully Deliver Your SharePoint Project In Ten Easy Steps - Symon...
How To Successfully Deliver Your SharePoint Project In Ten Easy Steps - Symon...How To Successfully Deliver Your SharePoint Project In Ten Easy Steps - Symon...
How To Successfully Deliver Your SharePoint Project In Ten Easy Steps - Symon...SPC Adriatics
 
Best practices with development of enterprise-scale SharePoint solutions - Pa...
Best practices with development of enterprise-scale SharePoint solutions - Pa...Best practices with development of enterprise-scale SharePoint solutions - Pa...
Best practices with development of enterprise-scale SharePoint solutions - Pa...SPC Adriatics
 
Best Practices for SharePoint Development Customization
Best Practices for SharePoint Development CustomizationBest Practices for SharePoint Development Customization
Best Practices for SharePoint Development CustomizationRicardo Wilkins
 
Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0LiquidHub
 
Best Practices to SharePoint Physical and Information Architecture
Best Practices to SharePoint Physical and Information ArchitectureBest Practices to SharePoint Physical and Information Architecture
Best Practices to SharePoint Physical and Information ArchitectureJoel Oleson
 
Best Practice SharePoint Architecture
Best Practice SharePoint ArchitectureBest Practice SharePoint Architecture
Best Practice SharePoint ArchitectureMichael Noel
 

Viewers also liked (9)

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 25092012 sp2013_itpro_hans_jaspers
Biwug 25092012 sp2013_itpro_hans_jaspersBiwug 25092012 sp2013_itpro_hans_jaspers
Biwug 25092012 sp2013_itpro_hans_jaspers
 
How To Successfully Deliver Your SharePoint Project In Ten Easy Steps - Symon...
How To Successfully Deliver Your SharePoint Project In Ten Easy Steps - Symon...How To Successfully Deliver Your SharePoint Project In Ten Easy Steps - Symon...
How To Successfully Deliver Your SharePoint Project In Ten Easy Steps - Symon...
 
Best practices with development of enterprise-scale SharePoint solutions - Pa...
Best practices with development of enterprise-scale SharePoint solutions - Pa...Best practices with development of enterprise-scale SharePoint solutions - Pa...
Best practices with development of enterprise-scale SharePoint solutions - Pa...
 
Best Practices for SharePoint Development Customization
Best Practices for SharePoint Development CustomizationBest Practices for SharePoint Development Customization
Best Practices for SharePoint Development Customization
 
Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0
 
Best Practices to SharePoint Physical and Information Architecture
Best Practices to SharePoint Physical and Information ArchitectureBest Practices to SharePoint Physical and Information Architecture
Best Practices to SharePoint Physical and Information Architecture
 
Best Practice SharePoint Architecture
Best Practice SharePoint ArchitectureBest Practice SharePoint Architecture
Best Practice SharePoint Architecture
 
SharePoint Programming Basic
SharePoint Programming BasicSharePoint Programming Basic
SharePoint Programming Basic
 

Similar to Using SPMetal for faster SharePoint development

Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernatepatinijava
 
Developing web apps using Erlang-Web
Developing web apps using Erlang-WebDeveloping web apps using Erlang-Web
Developing web apps using Erlang-Webfanqstefan
 
User and group security migration
User and group security migrationUser and group security migration
User and group security migrationAmit Sharma
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utilityAmit Sharma
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utilityAmit Sharma
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5Mahmoud Ouf
 
User and group security migration
User and group security migrationUser and group security migration
User and group security migrationAmit Sharma
 
WML Script by Shanti katta
WML Script by Shanti kattaWML Script by Shanti katta
WML Script by Shanti kattaSenthil Kanth
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2Neeraj Mathur
 
DOSUG XML Beans overview by Om Sivanesian
DOSUG XML Beans overview by Om SivanesianDOSUG XML Beans overview by Om Sivanesian
DOSUG XML Beans overview by Om SivanesianMatthew McCullough
 
Python (Jinja2) Templates for Network Automation
Python (Jinja2) Templates for Network AutomationPython (Jinja2) Templates for Network Automation
Python (Jinja2) Templates for Network AutomationRick Sherman
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldDavid McCarter
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldDavid McCarter
 

Similar to Using SPMetal for faster SharePoint development (20)

Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernate
 
Struts 2
Struts 2Struts 2
Struts 2
 
Developing web apps using Erlang-Web
Developing web apps using Erlang-WebDeveloping web apps using Erlang-Web
Developing web apps using Erlang-Web
 
User and group security migration
User and group security migrationUser and group security migration
User and group security migration
 
ORM JPA
ORM JPAORM JPA
ORM JPA
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utility
 
Force.com migration utility
Force.com migration utilityForce.com migration utility
Force.com migration utility
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
User and group security migration
User and group security migrationUser and group security migration
User and group security migration
 
WML Script by Shanti katta
WML Script by Shanti kattaWML Script by Shanti katta
WML Script by Shanti katta
 
Java XML Parsing
Java XML ParsingJava XML Parsing
Java XML Parsing
 
XML
XMLXML
XML
 
ASP.Net Presentation Part2
ASP.Net Presentation Part2ASP.Net Presentation Part2
ASP.Net Presentation Part2
 
DOSUG XML Beans overview by Om Sivanesian
DOSUG XML Beans overview by Om SivanesianDOSUG XML Beans overview by Om Sivanesian
DOSUG XML Beans overview by Om Sivanesian
 
Python (Jinja2) Templates for Network Automation
Python (Jinja2) Templates for Network AutomationPython (Jinja2) Templates for Network Automation
Python (Jinja2) Templates for Network Automation
 
MyBatis
MyBatisMyBatis
MyBatis
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real World
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real World
 
Bb Tequila Coding Style (Draft)
Bb Tequila Coding Style (Draft)Bb Tequila Coding Style (Draft)
Bb Tequila Coding Style (Draft)
 

Recently uploaded

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 

Recently uploaded (20)

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 

Using SPMetal for faster SharePoint development

  • 1. SPMetal Pranav Sharma http://pranavsharma.info Senior SharePoint Consultant Portal Solutions http://www.portalsolutions.net Twitter: @ePranav
  • 2. What is SPMetal and LINQ? “SPMetal is a command-line tool that generates entity classes, which provide an object- oriented interface to the Microsoft SharePoint Foundation content databases. These classes are primarily used in LINQ to SharePoint queries; but they are also used to add, delete, and change list items with concurrency conflict resolution. Finally, they can be used as an alternative to the regular SharePoint Foundation object model for referencing content. The tool is included with SharePoint Foundation and is located in %ProgramFiles%Common FilesMicrosoft Sharedweb server extensions14BIN” Language-Integrated Query (LINQ) is a set of features that extends powerful query capabilities to the language syntax of C# and VB. LINQ introduces standard, easily- learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store” (MSDN)
  • 3. Let’s create a sample list
  • 4. Setting up SPMetal  Create PreBuild.bat and save with encoding: Unicode (UTF-8 without signature) – codepage 65001  Include generated codefile in project  Add project reference to Microsoft.SharePoint.Linq.dll  Sign project using key file
  • 5. Options (1 of 3) Option Value definition Example Comments web The complete, /web:http://ContosoServer/ Required. You can have port numbers in the server name; for absolute URL of Marketing example, /web:http://ContosoServer:5555/Marketing. the Web site Do not include the home page or any other page in the URL. whose data is modeled by the entity classes. code The relative or /code:MarketingSite.cs If this option is not used, the generated code is streamed to standard absolute path and output. file name of the If no file name extension is specified or the file name extension is not output file. either "cs" or "vb", the language option must be used. The file name (exclusive of the extension) is also used to form the beginning of the name of a class that derives fromDataContext; in this example the class is namedMarketingSiteDataContext. The derived class represents the lists and data of the whole Web site, so choose a file name that conveys that meaning. (You can override this naming behavior with an SPMetal Parameters XML file.) language The programming /language:csharp The only possible values are "csharp" and "vb". language of the If the value of the code option has either "cs" or "vb" as a file name generated code. extension, SPMetal can infer the language and thelanguage option is not needed. namespace The namespace /namespace:Contoso.TeamA If this option is not used, the generated code specifies no namespace that contains the ctivityReports and the compiled assembly treats the default namespace specified in entity class the properties of the Visual Studio project as the namespace of the declarations. generated classes.
  • 6. Options (2 of 3) Option Value definition Example Comments useremoteapi No value. /useremoteapi This option signals that the value of the web parameter points to a server that is not the one on which SPMetal is running. One possible use for this parameter is to generate code against a Web site on an online deployment of SharePoint to which you intend to upload your solution as a sandboxed solution. user The user in whose context /user:Contosobob Use this option if you do not want SPMetal to run in SPMetal executes. your own context. Specify the domain. password The password for the user /password:$5U+ryz Use in conjunction with the user option. specified in theuser option. serialization Specifies whether objects /serialization:unidirectional The only possible values are "unidirectional" and that instantiate the "none". Specify "unidirectional" if you want the objects generated classes are to be serializable. SPMetal adds appropriate attributes serializable. from theSystem.Runtime.Serialization namespace to the class and property declarations and adds handlers for the Deserializing event. If this option is not used, "none" is assumed. parameters Identifies the path and name /parameters:MarketingSite.xml You typically will not reuse exactly the same parameters of an XML file that contains XML file for different Web sites, so name the file the overrides of SPMetal default same as the Web site. settings. For more information about the parameters file, see Overriding SPMetal Defaults by Using a Parameters XML File.
  • 7. Options (3 of 3) <?xml version="1.0" encoding="utf-8"?> <Web AccessModifier="Internal" xmlns="http://schemas.microsoft.com/SharePoint/2009/spmetal"> <ContentType Name="Contact" Class="Contact"> <Column Name="ContId" Member="ContactId" /> <Column Name="ContactName" Member="ContactName1" /> <Column Name="Category" Member="Cat" Type="String"/> <ExcludeColumn Name="HomeTelephone" /> </ContentType> <ExcludeContentType Name="Order"/> <List Name="Team Members" Type="TeamMember"> <ContentType Name="Item" Class="TeamMember" /> </List> </Web>
  • 8. Logging Use the DataContext’s Log property to inspect underlying SPQueries using (var context = new Sp2010DataContext("http://sp2010")) { var contextLog = new StringBuilder(); context.Log = new StringWriter(contextLog); Console.WriteLine(contextLog); }
  • 9. Iterating foreach (var myItem in context.MyList) { Console.WriteLine(myItem.Title); Console.WriteLine(" ->" + myItem.MyColumnChoice); //Console.WriteLine(" ->" + myItem.MyColumnManagedMetadata); } Querying Console.WriteLine((from myItem in context.MyList where myItem.MyColumnChoice.Equals(MyColumnChoice.BarackObama) select myItem.Title). FirstOrDefault());
  • 10. Complex field types (1 of 3) private TaxonomyFieldValue _myColumnManagedMetadata; [ColumnAttribute(Name = "MyColumnManagedMetadata", Storage = "_myColumnManagedMetadata", FieldType = “Taxonomy")] public TaxonomyFieldValue MyColumnManagedMetadata { get { return _myColumnManagedMetadata; } set { if ((value != _myColumnManagedMetadata)) { this.OnPropertyChanging("MyColumnManagedMetadata", _myColumnManagedMetadata); _myColumnManagedMetadata = value; this.OnPropertyChanged("MyColumnManagedMetadata"); } } }
  • 11. Complex field types (2 of 3) [CustomMapping(Columns = new String[] {"MyColumnManagedMetadata"})] public void MapFrom(object listItem) { var item = (SPListItem) listItem; this.MyColumnManagedMetadata = item["MyColumnManagedMetadata"] as TaxonomyFieldValue; } public void MapTo(object listItem) { var item = (SPListItem)listItem; item["MyColumnManagedMetadata"] = this.MyColumnManagedMetadata; }
  • 12. Complex field types (3 of 3) public void Resolve(RefreshMode mode, object originalListItem, object databaseListItem) { var origItem = (SPListItem) originalListItem; var dbItem = (SPListItem) databaseListItem; var origValue = (TaxonomyFieldValue) origItem["MyColumnManagedMetadata"]; var dbValue = (TaxonomyFieldValue) dbItem["MyColumnManagedMetadata"]; if (mode == RefreshMode.KeepCurrentValues || (mode == RefreshMode.KeepChanges && MyColumnManagedMetadata != origValue)) { dbItem["MyColumnManagedMetadata"] = MyColumnManagedMetadata; } else if (mode == RefreshMode.OverwriteCurrentValues || (mode == RefreshMode.KeepChanges && MyColumnManagedMetadata == origValue && MyColumnManagedMetadata != dbValue)) { MyColumnManagedMetadata = dbValue; } }
  • 13. Updating foreach (var myItem in context.MyList) { switch (myItem.Title) { case “Choice 1": myItem.MyColumnChoice = MyColumnChoice.BarackObama; break; case “Choice 2": myItem.MyColumnChoice = MyColumnChoice.MittRomney; break; default: myItem.MyColumnChoice = MyColumnChoice.None; break; } } context.SubmitChanges();
  • 14. Inserting var newItem = new MyListItem { Title = "Choice 3", MyColumnChoice = "Donald Trump" }; context.MyList.InsertOnSubmit(newItem); context.SubmitChanges();
  • 15. When to use SPMetal?  “While testing with a list of 45K items, SPQuery performed at 0.06s compared to SPMetal’s performance at 9.98s” – Pranav Sharma (See Resources for full article)  When to use SPMetal?  For quick wins when low on time  For low usage applications where list size doesn’t cause performance concerns  For easily binding SharePoint queries to data grids and repeaters  For complex query writing (Ex: Multi-list Lookups)  For new SP developers to avoid run-time errors by catching them at compile-time
  • 16. Resources  SPMetal (MSDN) http://bit.ly/icXOmf  How to: Use SPMetal (MSDN) http://bit.ly/hLPbjo  Overriding SPMetal Defaults by Using a Parameters XML File (MSDN) http://bit.ly/M3zSyH  SPMetal and the Managed Metadata Column http://bit.ly/HteBbp  Large list performance: SPMetal vs. SPQuery http://bit.ly/sYvAEL
  • 17. Questions?  Don’t forget to fill out evaluations online  Show the sponsors some love Pranav Sharma http://pranavsharma.info Senior SharePoint Consultant Portal Solutions http://www.portalsolutions.net Twitter: @ePranav