Friday, November 16, 2012

SharePoint 2010 14\TEMPLATE directory

TEMPLATE folder is one of the most important file folder of SharePoint where the templates, pages, masterpages will reside.
We will check the breakdown structure of directory and what each folder is meant for in SharePoint.Understanding this folder structure is important to get clear picture on, how and where SharePoint will house our deployed items.

TEMPLATE Directory

The installation path of the TEMPLATE directory will be

[root directory]:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE

Following is image of TEMPLATE directory breakdown structure in SharePoint 2010
TEMPLATE folder structure

1033

This sub-directory contains templates for various documents, XML files, and workflows.
This number corresponds to the language localization for English.
If SharePoint is installed with other languages being primary, the number will be different.

ADMIN

The ADMIN sub-directory contains ASP.NET server pages that correspond to administrative
tasks. Most of them will be accessed through the Central Administration site.

CONTROLTEMPLATES

This is one of the common sub-directory used by many. This contains ASP.NET user controls that are utilized by SharePoint.Also while SharePoint customization, folders will be deployed to house the project related files.
For example, if we create any visual web parts the user controls will be deployed as folders in this sub-directory.

DocumentTemplates

The only thing stored in this directory is the standard ASP.NET server page for wikis.

FEATURES

The FEATURES sub-directory contains 250+ folders, which represent the core features of SharePoint 2010.
Each of these folders contain a Feature.xml file, which identifies to SharePoint 2010 several characteristics such as the identity, scope, resources and manifest location of the feature. SharePoint customization deployed as features will be deployed to this sub-directory.

GLOBAL

This sub-directory houses the standard ASP.NET master pages that deploy with SharePoint
2010, such as the v4, default, and minimal master pages.
Also here are global templates for site definitions, views, and schema for list templates.

IDENTITYMODEL

This sub-directory contains default login pages for the different types of authentication
models, such as Forms, Windows, Trust, and Card.

IMAGES

This sub-directory houses all of the standard images for the SharePoint product.
If you have images deployed as part of customized solutions, by default they will
be deployed as sub-folders of this sub-directory.

LAYOUTS

The LAYOUTS folder is the folder that contains a large portion of the ASP.NET server
pages that are used in the SharePoint product.
You can reference this directory from within a SharePoint site by using a format similar to the following: http://mysite/_layouts/viewlsts.aspx

Pages

Only three ASP.NET server pages are stored in this folder, named form, viewpage,
and webfldr.

Scenarios

This sub-directory contains wizard-style pages, used in some of the different services
with greater complexity, such as BCS, ProfileServiceApplication, and joining the
farm with a particular web server.

Site Templates

This sub-directory contains the site templates for the different built-in SharePoint
2010 web templates.

SQL

This sub-directory contains SQL table creation scripts for tables associated with
various types of SharePoint 2010 databases. Many of the services database creation
scripts are here, such as the UsageDB, the Diagnostics DB, and Configuration DBs.
Also stored here are upgrade scripts to upgrade from a SharePoint 2007 solution
to a SharePoint 2010 solution.

THEMES

This sub-directory houses the 23 built-in themes or looks that are installed with
SharePoint 2010.

XML

The XML sub-directory contains XML schema and document files related to various
configurations in SharePoint.

Retrieving List Items with CAML Query - Examples

 

If you need to retrieve items from a list when developing web parts, application pages or custom field types you can best use the SPQueryobject from the SharePoint object model. This object is located in the Microsoft.SharePoint namespace of the Microsoft.SharePoint.dll located in the Global Assembly Cache.

Instantiate the object as follows:
SPQuery query = new SPQuery();
 
The most important property is the Query property, which needs to be set to your CAML query:

string camlquery = "<OrderBy><FieldRef Name='Country' /></OrderBy><Where>"
    + "<Eq><FieldRef Name='LastName' /><Value Type='Text'>Smith</Value></Eq>"
    + </Where>";
query.Query = camlquery;
 
At this point you can execute the query on your list:
SPListItemCollection listItemsCollection = list.GetItems(qry); 

Get data in datatable

A small remark with the GetItems method of the SPList instance: this method returns a collection of type SPListItemCollection. It is possible that it is easier working with a DataTable. In that case you can execute the query as follows:


DataTable listItemsTable = list.GetItems(qry).GetDataTable(); 

View fields property

The query will not only return all list items that have their last name set to Smith, but also all columns of each list item. In cases you work with large lists it can be important to retrieve a subset of list items containing only the columns you need. In that case you will have to set the ViewFields property of the SPQuery object. 

You can do this by specifying all columns you want to see returned:


qry.ViewFields = "<FieldRef Name='FirstName' /><FieldRef Name='LastName' />";
query.ViewFieldsOnly = true;
 
This will return the first name and the last name of the retrieved employees, but also the system fields like the ID and the Created date.

The major disadvantage of the SPQuery object is that you can query only one list. If you want to query more than one list you will have to use the SPSiteDataQuery. More on this object in a later article because it earns special attention.
It is common knowledge by now but let me remind you that it’s always a good idea to use SPQuery to retrieve a subset of list items. You can loop through the list item collection to find the list items that match your needs but this will have a serious negative impact on the performance of your work.

IncludeMandatoryColumns

When this Boolean property is set to True, the result set will not only return the columns as defined in the ViewFields property, but also the columns that you defined in the list as required.
When working with the SPQuery object:
qry.IncludeMandatoryColumns = true;
When working with the GetListItems method of the Lists.asmx web service:

XmlNode queryOptionsNode = camlDocument.CreateElement("QueryOptions");
queryOptionsNode.InnerXml =
    "<IncludeMandatoryColumns>True</IncludeMandatoryColumns>";

RowLimit

Setting this property limits the number of rows returned in the result set.
When working with the SPQuery object:
qry.RowLimit = 10;
 

Example: 



 using (SPSite site = new SPSite("http://localhost"))
         {
            using (SPWeb web = site.OpenWeb())
            {
SPList List = oWebsiteRoot.Lists["Tasks"];
               // Build a query. 
 SPQuery query = new SPQuery();
 
Query.Query = "<Where><Eq><FieldRef Name='Status'/>" +
    "<Value Type='Text'>Completed</Value></Eq></Where>";

 query.ViewFields = string.Concat(
                                   "<FieldRef Name='AssignedTo' />",
                                   "<FieldRef Name='LinkTitle' />",
                                   "<FieldRef Name='DueDate' />",
                                   "<FieldRef Name='Priority' />"); 
 
query.ViewFieldsOnly = true;
query.RowLimit = 10; 
 
SPListItemCollection collListItems = List.GetItems(query);
DataTable listItemsTable = List.GetItems(query).GetDataTable(); 
}
} 

Another Example - Using Sharepoint Client Object Model: 

Four properties of ListItem are not available by default when you return list items: 
DisplayName, EffectiveBasePermissions, HasUniqueRoleAssignments, and RoleAssignments
Use Include method to get them. 
Only the specified properties are available after query execution.
Therefore, you receive a PropertyOrFieldNotInitializedException
if you attempt to access other properties beyond those that have been specified. 
In addition, you receive this error if you attempt to use properties such as 
ContentType or ParentList to access the properties of containing objects.

using System;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveListItems
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");

            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" +
                "<Value Type='Number'>10</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>";
            ListItemCollection collListItem = oList.GetItems(camlQuery);

clientContext.Load(collListItem);
OR
clientContext.Load(collListItem,
                 items => items.Include(
                    item => item.Id,
                    item => item.DisplayName,
                    item => item.HasUniqueRoleAssignments));
 
 
 clientContext.ExecuteQuery();

            foreach (ListItem oListItem in collListItem)
            {
                Console.WriteLine("ID: {0} \nTitle: {1} \nBody: {2}", oListItem.Id, oListItem["Title"], oListItem["Body"]);
            }
        }
    }
}
 

Retrieving specific fields from a specified number of items

 

The following example shows how to retrieve specific fields from only the first five items in a list. Because only the Title and Body columns are specified, these are the only properties that are available.


using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveSpecificItemsFields
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");

            CamlQuery camlQuery = new CamlQuery();
            ListItemCollection collListItem = oList.GetItems(camlQuery);

            clientContext.Load(
                collListItem,
                items => items.Take(5).Include(
                item => item["Title"],
                item => item["Body"]));

            clientContext.ExecuteQuery();

            foreach (ListItem oListItem in collListItem)
            {
                Console.WriteLine("Title: {0} \nBody: {1}\n", oListItem["Title"], oListItem["Body"]);
            }
        }
    }
}

Retrieving items from all the lists in a Web site 

 

using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveFirstTenItemsAllLists
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            ListCollection collList = clientContext.Web.Lists;

            clientContext.Load(
                collList,
                lists => lists.Where(
                    list => list.Hidden == false).Include(
                    list => list.Title,
                    list => list.Items.Take(10)));

            clientContext.ExecuteQuery();

            foreach (SP.List oList in clientContext.Web.Lists)
            {
                string listTitle = oList.Title;
                int itemCount = oList.Items.Count;

                Console.WriteLine("List {0} returned with {1} items", listTitle, itemCount);
            }
        }
    }
}

CAML Query tutorial for SharePoint 

  •    CAML - Collaborative Application Markup Language
  •   XML- Extensible Markup Language based query language
       CAML:   Used to perform a query operation against SharePoint Lists

How SharePoint List Items are retrieved?

SharePoint List data can be retrieved in any one of the following ways:
1. Using the SharePoint object model – used when code runs on the server         (Example: Developing a web part or an application page)
2. Using the SharePoint Lists web service – used when your code doesn’t run on the server where the SharePoint is installed (Example: Developing a windows application)
3. Using Power shell –used mostly by the ADMIN of the SharePoint when they quickly want to retrieve some information from the SharePoint site

How does CAML query looks like?

As I already mentioned, it is XML based query language and it contains tags in it. The root element of the CAML query root element is Query. But it is not necessary to use Query element in the query you form.
Within the Query element you have two elements possible:
1. Where   – to filter the data
2. OrderBy – to categorize the data
A simple structure of the CAML query is as follows:
<Query>
          <Where>
                   <Eq>
                             <FieldRef Name=”FieldName” />
                             <Value Type=”DataType”>Value</Value>
                   </Eq>
          </Where>
          <OrderBy>
                             <FieldRef Name=”FieldName” />
                             <FieldRef Name=”FieldName” />
          </OrderBy>
</Query>

Refer: Query Schema Elements

 

Operators in CAML Query

From the above structure, we came to know that it uses Where and OrderBy elements to retrieve the data from the list.
Let us know about the operators present in the CAML query and its usage:

Inside the Where element

1. Logical Operators - AND, OR
2. Comparison Operators - Listed Below in the table
AND – Which takes two conditions are satisfied
OR – Which takes when either of the conditions is satisfied

Comparison Operators
Inside the OrderBy/GroupBy element

OrderBy – Which orders or sort the data depends upon the field (FieldRef element) given.
GroupBy – Which groups the data depends upon the group by field (FieldRef element) given.

Examples
Logical & Comparison Operators

Use of AND, Gt, Leq
<Query>
<Where>
<And>
<Gt>
<FieldRef Name="Quantity" />
<Value Type="Number">0</Value>
</Gt>
<Leq>
<FieldRef Name="Price" />
<Value Type="Number">2000</Value>
</Leq>
</And>
</Where>
</Query>
Use of OR, Gt, Leq
<Query>
<Where>
<Or>
    <Gt>
<FieldRef Name="Quantity" />
<Value Type="Number">0</Value>
    </Gt>
                     <Leq>
  <FieldRef Name="Price" />
<Value Type="Number">2000</Value>
    </Leq>
               </Or>
       </Where>
</Query>
Use of BeginsWith, Leq
<Query>
<Where>
<And>
     <BeginsWith>
 <FieldRef Name="Title" />
 <Value Type="Text">M</Value>
     </BeginsWith>
     <Leq>
    <FieldRef Name="Quantity" />
<Value Type="Number">1000</Value>
     </Leq>
</And>
</Where>
<OrderBy>
<FieldRef Name="Price" Ascending="False" />
</OrderBy>
</Query>

OrderBy Operator
 
<Query>
<Where>
<Or>
   <Gt>
<FieldRef Name="Quantity" />
<Value Type="Number">0</Value>
  </Gt>
    <Leq>
<FieldRef Name="Price" />
<Value Type="Number">2000</Value>
  </Leq>
</Or>
</Where>
<OrderBy>
<FieldRef Name="Price" Ascending="True" />
</OrderBy>
</Query>

 

CAML Query

 

  • A caml query is build in two parts.
    • 1) Sort
    • 2) Filter
  • Sort part is the sorting based on some columns
  • Filter part is the where clause of the CAML query
  • In order to build up the XML for the CAML we create the where clause as follows:
    • Write the where clause just as you write in sql
    • Find out the operators such as =, <=, <,> etc.
    • Find out the keywords for these operators in CAML language. For example = is eq, < is lt and so on.
    • Break the sql string such that the operator comes first and then comes the operands. Continue this till the whole string is completed in this fashion.
    • Replace the operators with the keywords in CAML language.
    • Example: where column1=”a” and column2=”b” and column3 like ‘%c%’
    • => where (column1=”a” and column2=”b”) and column3 like ‘%c%’
    • => where and (column1=”a” and column2=”b”) (column3 like ‘%c%’)
    • => where and (and (column1=”a” column2=”b”) column3 like ‘%c%’)
    • => where and and (= column1 a column2 b) contains column3 c
    • => where and and eq column1 a eq column2 b contains column3 c
    • => <where>
<and>
          <and>
                   <eq>
                             <FieldRef name=”Column1” />
                             <Value Type=string>a</Value>
                   </eq>
                   <eq>
                             <FieldRef name=”Column2” />
                             <Value Type=string>b</Value>                                 
 </eq>
          </and>
          <contains>
                   <FieldRef name=”Column3” />
                   <Value Type=string>c</Value>
          </contains>
</and>
                           </where>

Download CAML Query Builder here

Refer: Sharepoint-works

Thursday, November 15, 2012

How to Create a Custom Site Definition with Additional Content in SharePoint 2010 Using Visual Studio 2010

Site Definitions give you lots of flexibility in choosing custom layouts, features, elements, modules, etc., that are included when a new site is created in SharePoint. Furthermore, Site Definitions make it easier to maintain and upgrade your SharePoint solutions.

Challenge

How do I create a custom Site Definition, as well as content related to a Site Definition in SharePoint 2010, using the Visual Studio 2010 project template?

Solution:
Creating a custom site definition using the Visual Studio project template

To create a site template, follow these steps:
  • Open Visual Studio 2010, click New on the File menu, and then click Project.
  • In the Templates pane, select the Site Definition project template under SharePoint 2010 templates folder.
  • In the Name box, provide a name for your solution.
  • In the Name box, input DemoSiteDefs and then click OK (See Figure 1).
Figure 1

At this point, the SharePoint Customization Wizard will appear (See Figure 2).


Figure 2
  • You will see a SharePoint Customization Wizard asking for a local site for debugging and deployment. Enter the URL for the SharePoint server site where you want to debug the site definition, or use the default location (http://system name/).
  • Select Deploy as a farm solution for "What is the trust level for this SharePoint solution?"
  • Click Finish. The project appears in Solution Explorer.
  • A new solution will be created as shown in the image below. Note that two .xml files are created (WebTemp_DemoSiteDefs.xml, ONet.xml). As well, Features and Package folders are created. (See Figure 3)
Figure 3
WebTemp_DemoSiteDefs.xml

In WebTemp_DemoSiteDefs.xml, add our custom site definition into the catalog of site definitions so that we can pick the site definition to provision from the Create Site and Workspace application pages.  It is important that the Template Name exactly matches our site definition name. This file name begins with the "webtemp" prefix as required by SharePoint. The general format of WebTemp_DemoSiteDefs.xml is as shown in the following figure.
Figure 4
When this Site Definition is installed, a global WebTemp_DemoSiteDefs.xml is installed in %Program Files%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LCID\XML, where LCID is the numeric ID of language/culture. Ex: 1033 for English.

Onet.xml

Onet.xml is all about Navigation areas, List Definitions, Modules, List Templates, Configurations, BaseTypes, Components, etc. (See Figure 5).
Figure 5
When this Site Definition is installed, a global Onet.xml is installed in %Program Files%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\GLOBAL\XML.
For each Site Definition, there is a corresponding Onet.xml installed in a sub-directory (template name) at  %Program Files%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\SiteTemplates.
You can see more details about the format of Onet.xml file here: http://msdn.microsoft.com/en-us/library/ms474369.aspx.
Note: Once deployed, a Site definition cannot be modified. You should create a new kind of site. This can be done by creating a new WebTemp*.xml and Onet.xml.
  • Press F5 to run and deploy the project.
  • The solution will be deployed on SharePoint. You'll see a custom site Web page derived from your site definition (See Figure 6).
Figure 6

Open the newly created site, and you'll see a custom site Web page derived from your site definition.


Figure 7

Incorporating a custom master page into the Site Definition



  • Create a master page. For more information, see ASP.NET Master Pages.
  • Export and then import the custom master page into Visual Studio, as outlined in Walkthrough: Import a Custom Master Page and Content Page with an Image.
  • For this demo, I'm using the master page in http://startermasterpages.codeplex.com/.
  • Add the master page to a module. To do this, right-click the project node in Solution Explorer, point to Add, and then click New Item.
  • Within the Add New Item dialog box, in the list of SharePoint templates, select Module. Give the module a name, input MasterPageModule.
  • In the module, delete the default Sample.txt file.
  • Add a folder to the module named _catalogs, and then another one under it called masterpage.
This matches the file location of other master pages in SharePoint.
  • Add the master page under the masterpage folder. To do this, select the module node and then, on the Project menu, click Add Existing Item. Locate the master page and select it. Master page files have a .master file name extension. I added meetingworkspace.master file. See the following figure:
Figure 8
  • Double-click Elements.xml in the module to open it in the XML Designer.
  • You must update the Elements.xml file to reference the master page.
  • Replace the existing module markup as shown in the following figure.
Figure 9
  • Update the master page reference in default.aspx file
We are going to use our own master page in our Site Definition, therefore we need to change default.master -> custom.master in our default.aspx page. SharePoint will replace the custom.master reference with our master page during runtime page rendering based on the site definition schema (onet.xml).
Figure: 10
When we create a master page module, Visual Studio 2010 generates a new feature called Feature1.feature. We need to change properties and apply the master page feature to our Site Definition. Visual Studio 2010 creates a separate feature for master page instead of depending on the Site Definition so that it can be operated independent of our Site Definition.
Click to Feature1.feature. In the Feature Design mode we can edit title, description, and scope of feature.
Figure: 11
In the Manifest mode, you also see title, ID, scope, and element files of this feature (See Figure 12).
Figure: 12
Next, we need to add this custom master page to the Site Definition.
Update onet.xml file:
Add our  master pages feature (which ID="23d9ad40-56e7-4473-af17-c8c7fbc39b99") under WebFeatures. If our master page feature had been a "Site" scoped feature we would specify it under the SiteFeatures section (See Figure 13).
Update the default configuration and specify that our configuration should use our custom master page by setting the CustomMasterUrl and MasterUrl points to our custom master page (living in the master page gallery). By setting these values, we are effectively telling SharePoint that whenever .aspx refers to custom.master page, replace that with meetingworkspace.master page which is our custom master page (See Figure 13).


Figure: 13
  • Press F5 to run and deploy the project.
  • Create a Site. In the new Site, you can see the custom master page as shown in the following figure.
Figure: 14

Creating custom fields and adding them to the site definition

Define custom fields that will be used to create a custom list later. These fields provide additional data required by the code in the Site Definition.
To define custom fields:
  • Right-click the Site Definition node in Solution Explorer, point to Add, and then click on New Item.
  • Select Empty Element in the list of templates, and name the element SiteColumns.
  • In the Elements.xml file, I added two custom fields: Region, StandardRate. These fields are used to identify employees' region and their standard rate. You can add more fields if you want. Use the Create GUID tool on the Tools menu to generate a unique GUID for each additional field (See Figure 15).
Figure 15

Important

When adding a custom field, you must specify the ID, Type, Name, DisplayName, and Group attributes for the field in order for it to appear correctly in SharePoint. The statement completion erroneously indicates that you need only the first three of these attributes when, in fact, all five are required.
When we add an Empty Element, Visual Studio auto-generates Feature2 for this instance of Elements, so we need to change the default properties of Feature2. I changed title to Custom Contact Field Feature (scope is Site).
Next step, update onet.xml file:
Add the Custom Contact Field feature under SiteFeatures in onet.xml file (See Figure 16).
Figure 16
Press F5 to run and deploy the project.
At the top of the SharePoint Web page, click the Site Actions button and then click Site Settings. Under the Galleries section of the Site Settings page, click the Site columns link.
In the Site Column Gallery page, scroll the page down to the Custom Contact heading and note the new field item has been added, Region and Standard Rate (See Figure 17).
Figure 17


Creating a content type that includes the custom fields

To add a content type
  • Right-click the site definition node in Solution Explorer, point to Add, and then click on New Item.
  • Select Content Type in the list of templates and name the new content type, input ContactContentType name.
  • On the Choose Content Type Settings page, select Contact in the list for the base contact type.
  • Click Finish. You should see the content type appear in Solution Explorer
  • In the Elements.xml file for the content type, add the two custom columns that were created above (See Figure 18)
Figure 18
Note: When I added the Contact content type, by default, Visual Studio added it to the Custom Contact Field feature (it will be deployed to Site scope). You can create a new feature for this content type if you wish.
Press F5 to run and deploy the project.
  • At the top of the SharePoint Web page, click the Site Actions button and then click Site Settings.
  • Under the Galleries section of the Site Settings page, click the Site Content Types link.
  • In the Site Content Types Gallery page, note the new content type we just created, DemoSiteDefs - ContactContentType. Click it to view its fields. In the list of fields for DemoSiteDefs - ContactContentType, note the field Region and Standard Rate has been added (See Figure 19).
Figure 19


Creating a list definition based on the content type and adding it to the site definition

Creating a list definition and list instance that will use the new content type and field.

To create a list definition and list instance
  • Right-click the Site Definition node in Solution Explorer, point to Add, and then click on New Item.
  • Select List Definition in the list of templates and name the new list definition. I entered ContactListDefinition.
  • On the Choose List Definition Settings page, leave the default value, DemoSiteDefs - ContactListDefinition.
  • For What is the type of list definition? list, use Contact list.
  • Select the Add a list instance for this list definition box to add a list instance project item to the project. The list instance will be an instance of the new list definition.
  • Click Finish. You should see the list definition with list instance appear in Solution Explorer (See Figure 20).
Figure 20
To add a field to the list definition
  • Double-click Schema.xml under ContactListDefinition to view it.
  • Under the <ContentTypes> element, reference the ContactContentType that was created above (See Figure 21).
Figure 21
  • Under the <Fields> element, custom fields were added by the content type.
Figure 22
  • Add custom fields to view (See Figure 23).
Figure 23
  • Now, I want to deploy this list definition to scope Web, so I must create a feature for it.
  • To create a feature, right-click the Feature folder, click to Add Feature and then for the name of the feature, input ContactListDefinitionFeature.(See Figure 24)
  • In the Feture Design mode, I selected two items in the Items in the Solution box for this feature, ListInstance1 and ContactListDefinition (See Figure 24).
  • Change title of feature to Contact List Definition Feature (See Figure 24).
  • Change scope of feature to Web (See Figure 24).
Figure 24
  • Next step, update onet.xml file.  Add the Contact List Definition feature under WebFeatures in the onet.xml file (See Figure 25).
Figure 25
  • Press F5 to run and deploy the project.
  • Under the Lists section in the SharePoint QuickLaunch bar, click the DemoSiteDefs - ContactListDefinition link.
  • This is the list instance for the new list definition. Note that the new field Region and StandardRate must appear as a column in the list instance.
Figure 26

Adding default list data to a list instance

To provide an instance of the new list definition and some default employee information to the DemoSiteDefs - ContactListDefinition list after the site definition is deployed.
  • Double-click the Elements.xml file of ListInstance1 to open it.
  • I added two custom rows of data as shown in the following figure.
Figure 27
  • Press F5 to run and deploy the project.
  • Click on the DemoSiteDefs - ContactListDefinition link. You can see that the data has been added to the list instance as shown in the following figure.
Figure 28

Creating a visual Web Part and adding to the Site Definition

We will create a visual Web Part to display on the Site Definition's main page.
To create a visual Web Part
  • Right-click the site definition node in Solution Explorer, point to Add, and then click on New Item.
  • Select Visual Web Part in the list of templates and provide a name. I entered the name as DemoVisualWebPart.
  • This opens the file DemoVisualWebPartUserControl.ascx. At the bottom of DemoVisualWebPartUserControl.ascx, add the following controls to the form: a label and a calendar (See Figure 29).
Figure 29
  • You can write the code behind this under file DemoVisualWebPartUserControl.ascx.cs.
Next step, add the visual Web Part to the Site Definition's default ASPX page.
  • Open the default.aspx page and add the following under the WebPartPages tag:
Figure 30
This line associates the name DemoVisualWebPart with the Web Part and its code. The Namespace parameter is the same as the namespace used in the DemoVisualWebPartUsercontrol.ascx code file.
  • We need to create a WebPartZone and add WebPart to WebPartZone.
Figure 31
  • Press F5 to run and deploy the project.
  • Create a Site. In the new Site, you can see the DemoVisualWebPart appear in the Site as shown in the following figure.
Figure 32

Our final solution structure should now look like the following figure.


Figure 33
All done! Our solution is now ready for packaging into a .wsp solution file and deployment into the SharePoint farm.
You can download a demo project here.
I hope that you found it helpful to learn how to create a more full-featured Site Definition, incorporating several features and elements that you might wish to add to the Site Definition. 


Notes
  • Once deployed, a Site definition cannot be modified. You should create a new kind of site. This can be done by creating a new WebTemp*.xml and Onet.xml.

See Also