Thursday, April 21, 2011

The SPMetal Tool

SPMetal is a command line tool that generates code that is an alternative to the SharePoint object model. By default, the tool is located at
 C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN.
Simply point it at a SharePoint team site and the resulting code file will contain strongly typed entity classes for all of the site’s lists and libraries as they are configured at that moment in time. This code is often easier to use than the SharePoint object model equivalents. The best example of this is actually the main task our web part will perform—querying for data. Using the SharePoint object model, you could issue a query for specific items of a list using an XML-formatted CAML query. Notice that the query is just in the form of a string with no IntelliSense provided for structure, field names, or possible values.
SPList list = m_web.Lists["Issues"];
SPQuery query = New SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Category'/><Value
Type='CHOICE'>Hardware</Value></Eq></Where>";
SPListItemCollection items = list.GetItems(query);

Instead, the entity classes created by SPMetal support LINQ.
using (EntitiesDataContext dc = new EntitiesDataContext(webUrl))
{
var q = from issue in dc.Issues where issue.Category == Category.Hardware
select issue.Title;
A developer would typically use SPMetal during the coding phase, running the tool and adding the resulting file to his Visual Studio project. To run the tool, launch a command window and type a command similar to
SPMetal /web:http://edhild3/sites/dynppt /code:Entities.cs /language:csharp.
In this command we have specified three parameters. The first, web, specifies the site to use as the source. The generated code file will contain classes for working against a similarly structured site. In this case, we chose our team site where we created the Issues list. The second parameter, code, specifies the name for the file you want the generated code to be placed in. This file will be placed in the same directory as the SPMetal tool. Once you have it, copy and add it to your solution. The last parameter, language, specifies the .NET language you want the generated code to be in. There are many more parameters to this file and if you are going to be doing a lot of coding against SharePoint data sources.

Note It is important to realize that this code runs in the context of the developer running the command unless
another user is specified as a parameter. Since SharePoint security trims the data to which a user has access,
make sure the user running this tool actually has access to the data you are planning to code against

No comments:

Post a Comment