Friday, December 23, 2011

Create BAT File in MOSS 2007 / SharePoint 2007


To ease the deployment process, create a batch file called InstallAll.bat in the folder that contains the FormDataWorkflow.sln Visual Studio solution file. Add the following code to the InstallAll.bat file.
iisreset /stop

"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -uf FormDataAspxPages
"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -if FormDataASPXPages\bin\Debug\FormDataAspxPages.dll

"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -uf FormDataWorkflow
"%programfiles%\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" -if FormDataWorkflow\bin\Debug\FormDataWorkflow.dll

iisreset /start

copy /Y "FormDataAspxPages\FormDataAssocForm.aspx" %SystemDrive%"\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS"
copy /Y "FormDataAspxPages\FormDataInitForm.aspx" %SystemDrive%"\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS"

mkdir  %SystemDrive%"\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES\FormDataWorkflow"

copy "FormDataWorkflow\Feature.xml" %SystemDrive%"\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES\FormDataWorkflow"
copy "FormDataWorkflow\workflow.xml" %SystemDrive%"\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES\FormDataWorkflow" 

pushd "%programfiles%\common files\microsoft shared\web server extensions\12\bin"

stsadm -o deactivatefeature -filename "FormDataWorkflow\feature.xml" -url http://localhost -force
stsadm -o uninstallfeature -filename "FormDataWorkflow\feature.xml" -force

stsadm -o installfeature -filename "FormDataWorkflow\feature.xml" -force
stsadm -o activatefeature -filename "FormDataWorkflow\feature.xml" -url http://localhost -force

popd

PAUSE

Friday, December 9, 2011

Debugging Feature Receivers


Feature receivers can be difficult because they are often executed within a separate process. To see an example of this problem put a breakpoint on the first line of our FeatureActivated method and try debugging using Visual Studio.  The code will be deployed and the feature will be activated, but execution will not stop at the breakpoint.  Visual Studio makes use of a separate process, VSSPHost.exe, to automate the deployment only, and therefore the breakpoint is never hit but the code still execures.
        We can work around this issue in one of two ways: we can either attach a debugger to the appropriate process, or we can ensure that our feature receiver runs in the W3SVC process. To ensure  that a debugger is attached to the correct process, we can take the following steps:
   
            1.   Add the following line of code to the method to be debugged:
    Debugger.Break();

   When error window open then select “Debug the Program”
 

Friday, September 9, 2011

Machine Caching in SharePoint 2010

Some caching techniques in SharePoint 2010:-

1. Object Caching (Configurable)
2. BLOB Cache (Configurable) :  Open web.config in SharePoint Root Hive:
<BlobCache location="D:\BLOB\" path="\.(gif|jpg|jpeg|jpe|jfif|bmp|dib|tif|tiff|ico|png|wdp|hdp|css|js|asf|avi|flv|m4v|mov|mp3|mp4|mpeg|mpg|rm|rmvb|wma|
wmv)$" maxSize="10" enabled="true" />

3. Caching in code (Programmable)

Important Links about Caching in SharePoint
http://msdn.microsoft.com/en-us/library/aa661294.aspx
http://msdn.microsoft.com/en-us/library/aa661294.aspx
http://msdn.microsoft.com/en-us/library/ms550239.aspx
http://msdn.microsoft.com/en-us/library/aa622758.aspx
http://technet.microsoft.com/en-us/library/cc770229.aspx
http://technet.microsoft.com/en-us/library/cc770229.aspx#BLOB
http://www.zimmergren.net/archive/2008/10/07/web-part-caching-%E2%80%93-a-simple-approach.aspx
http://msdn.microsoft.com/en-us/library/bb687949%28office.12%29.aspx#UsingSPData
http://technet.microsoft.com/en-us/library/ee424404.aspx#Section1c


Web Part Caching – A simple approach:-

Open Visual Studio2010 and select a WebPart form SharePoint 2010 Template:

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;

namespace VisualWebPartProject1.VisualWebPart1
{
    [ToolboxItemAttribute(false)]
    public class VisualWebPart1 : WebPart
    {       
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/VisualWebPartProject1/VisualWebPart1/VisualWebPart1UserControl.ascx";
       
        protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            Controls.Add(control);

            List<SPList> lists = new List<SPList>();
            string status = "";

            if (HttpRuntime.Cache["SimpleSampleCache"] == null)
            {
                status = "The following items are <strong>NOT</strong> fetched from the cache<br/><br/>";

                SPWeb web = SPContext.Current.Web;
                foreach (SPList list in web.Lists)
                    lists.Add(list);

                HttpRuntime.Cache.Add("SimpleSampleCache",
                lists,
                null,
                DateTime.MaxValue,
                TimeSpan.FromMinutes(10),
                System.Web.Caching.CacheItemPriority.Default, null);
            }
            else
            {
                status = "The following items <strong>ARE</strong> fetched from the cache!<br/><br/>";
                lists = (List<SPList>)HttpRuntime.Cache["SimpleSampleCache"];
            }
           
            Controls.Add(new LiteralControl(status));

            foreach (SPList l in lists)
                Controls.Add(new LiteralControl(l.Title + " - " + l.ItemCount + " items<br/>"));   
        }
    }
}

Press F5 and add WebPart to an WebPart Page and Show the Result as follows:-




Thank You.
 

Developer Dashboard

Activating the Developer Dashboard

•    PowerShell
•    STSADM.exe
•    SharePoint Object Model (API's)

Activate the Developer Dashboard using PowerShell:-
$devdash = [Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashboardSettings;
$devdash.DisplayLevel = 'OnDemand';
$devdash.TraceEnabled = $true;
$devdash.Update()

Activate the Developer Dashboard using STSADM.EXE:-
STSADM.EXE -o setproperty -pn developer-dashboard -pv ondemand

Activate the Developer Dashboard using the SharePoint Object Model:-
using Microsoft.SharePoint.Administration;
SPWebService svc = SPContext.Current.Site.WebApplication.WebService;
svc.DeveloperDashboardSettings.DisplayLevel =
    SPDeveloperDashboardLevel.Off;
svc.DeveloperDashboardSettings.Update();

•    Off (Disables the Developer Dashboard)
•    On (Enables the Developer Dashboard)
•    OnDemand (Enables the Developer Dashboard upon request by clicking the icon in the upper right corner)

SPMonitoredScope to track performance in your applications:-
 using (new SPMonitoredScope("Monitoring"))
{
    Controls.Add(new Literal { Text = "When the awesomeness is flying... " });
               
    using (new SPMonitoredScope("Sub-Monitoring"))
    {
        Controls.Add(new Literal { Text = "Hello this is --Sub-Monitoring! " });

        using (new SPMonitoredScope("Sub-Sub-Monitoring"))
        {
            Controls.Add(new Literal { Text = "<br/>Hello this is Sub-Sub-Monitoring!" });
        }

        using (new SPMonitoredScope("Sub-Sub-Monitoring_1"))
        {
            Controls.Add(new Literal { Text = "Hello this is Sub-Sub-Monitoring_1" });
        }
    }
}

Now go and test Doveloper Dashboard to find the Result with about scope names
0.Monitoring
1. Sub-Monitoring
2. Sub-Sub-Monitoring
3. Sub-Sub-Monitoring_1
  

Friday, September 2, 2011

SharePoint 2010 Backup and Recovery

Initial Backup Configuration
•    Farm, Service Applications, Content Databases: Local Administrator Group Member
•    Site collections, sites, lists, document libraries: Farm Administrator Group Member

Backing Up the Farm
following services must be running at the time you are issuing the backup command from CA:
•    Timer Service
•    SharePoint Foundation Administration Service

    In order to be able to back up the content databases, you must have the db_backupoperator role assigned to the user you are trying to perform the backup with.
Backing Up Content Databases
Backup-SPFarm -Directory "path" -BackupMethod "Full|Differential" -Item

•    Directory: Set the backup folder
•    BackupMethod: Specify whether to run a full or differential backup
•    Item: Specify the farm, web application or (shared) service application you want to backup

    At the end of the backup/restore operation you will find either spbackup.log or sprestore.log.
Backing Up Site Collection, Lists and Document Libraries
    The preferred file extension is .bak.
Backup-SPSite -Identity "Site Collection Name" -Path "path"  [-UseSqlSnapshot] [-NoSiteLock]

we can back up single sites, lists or document libraries:
Export-SPWeb -Identity "Site/List/Library name" -Path "path" [-IncludeUserSecurity] [-GradualDelete] [-IncludeVersions]

Backing Up Log Files
Merge-SPLogFile -Path"path" -Overwrite

Initial Restore Configuration
1.    Start the SharePoint Foundation Administration Service on all farm servers
2.    Do not restart services using the Product Configuration Wizard (which causes custom configuration of the service apps to be lost).

Restoring an Entire Farm
1.    Restore-SPFarm –Directory "path" –RestoreMethod Overwrite [-BackupId "guid"]
2.    Get-SPBackupHistory -Directory "path"

Start and Stop Service using Powershell
1.    Get-SPServiceInstance | Stop-SPServiceInstance
2.    Get-SPServiceInstance | Start-SPServiceInstance

Restore Using the SQL Server Tools
•    You cannot restore the SharePoint 2010 configuration data.
•    You cannot restore SharePoint 2010 search.

Backing Up and Restoring Configuration Settings on Another Farm
What you need to bear in mind for the mentioned scenario is that you must copy and restore the configuration settings for the following elements:
•    The farm
•    Web applications
•    Service applications
1.    Get-SPWebApplication | %{$_.Name;$_.Url;%{$_.ContentDatabases|%{$_.Name}; Write-Host “” }}
2.    Get-SPContentDatabase | Dismount-ContentDatabases3.   
4.    Backup-SPFarm –Directory "path" -BackupMethod "Full | Differential"
5.    Mount-SPContentDatabase –Name "WSS_Content" -WebApplication "URL"
6.    Restore-SPFarm –Directory "path" -RestoreMethod Overwrite -ConfigurationOnly
7.    Restore-SPFarm –Directory <backup folder> -RestoreMethod Overwrite –ConfigurationOnly –Item "web app | service app"
8.    Update-SPSecureStoreApplicationServerKey –Passphrase <passphrase>
9.    Mount-SPContentDatabase –Name <db name> -WebApplication <web app URL>

Restoring Site Collections
1.    Restore-SPSite –Identity <site_collection_url> -Path <network_shared_path>\newteamsite.bak -Force

Import list and libraries
1. Import-SPWeb –Identity <site_collection_url> -Path <network_shared_path>\listname.cmp

Create a network shared folder
1. Start, Command Prompt
2. cd /
3. mkdir SPBackupFolder
4. Cacls SPBackupFolder /G <DomainName>\Administrator:F
5. Net Share SPBackupFolder=C:\SPBackupFolder /GRANT:<DomainFolder>\Adminstrator,FULL
-----------------------------------------------------------------------
Get-Help Restore-SPSite -detailed
Get-Help Import-SPWeb -detailed
Get-Help Get-SPBackupHistory -detailed
Get-SPBackupHistory –Directory <network_shared_path>\SPBackup
Get-SPBackupHistory –Directory <network_shared_path>\SPBackup -ShowBackup
Get-SPBackupHistory –Directory <network_shared_path>\SPBackup -ShowRestore
-----------------------------------------------------------------------

Thursday, September 1, 2011

People Search in Silverlight WebPart



Step1: File->New Project->Silverlight->Silverlight Application->SP_SilverligetApplication1
(Name)->click OK

Pleas make sure check the box "Host the silverlight application in a new web site"->Click OK

Step2: Right clink on SP_SilverlightApplication1->Add service referece->Address as type "http://servername/_vti_bin/People.asmx"->click on "Go" and select an service "People" and give namespace as "PeopleWS"

Step3: Open SP_SilverlightApplication1->MainPage.xml and type following code.

<UserControl x:Class="SP_SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="240" d:DesignWidth="280">
    <Grid x:Name="LayoutRoot" Background="White">
        <Border BorderThickness="4" BorderBrush="Black">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="30" />
                    <RowDefinition Height="145" />
                    <RowDefinition Height="25" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="3" VerticalAlignment="Top">
                    <TextBlock HorizontalAlignment="Left" Name="textBlock1" Text="Search:" VerticalAlignment="Center" />
                    <TextBox x:Name="SearchTxt" Width="200" KeyUp="SearchTxt_KeyUp" />
                    <Button x:Name="SearchBtn" Click="SearchBtn_Click">
                        <Image Source="/SilverSite;component/Images/search32x32.png" Width="16" Height="16" />                    </Button>
                </StackPanel>
                <StackPanel Grid.Row="1" Orientation="Vertical" HorizontalAlignment="Left" Margin="3">
                    <ListBox x:Name="ResultsLst" Width="265" Height="135" />
                </StackPanel>
                <StackPanel Grid.Row="2" Orientation="Horizontal" Margin="3">
                    <Button x:Name="AddNameBtn" Content="Add ->" Click="AddNameBtn_Click" />
                    <TextBlock x:Name="UserNameTxt" Width="143" Padding="5" VerticalAlignment="Center" />
                </StackPanel>
                <StackPanel Grid.Row="3" Orientation="Horizontal" Margin="3" HorizontalAlignment="Right">
                    <Button x:Name="OKBtn" Content="OK" Width="75" Click="OKBtn_Click" Height="20" Padding="3" />
                    <Button x:Name="CancelBtn" Content="Cancel" Width="75" Height="20" Padding="3" Click="CancelBtn_Click" />
                </StackPanel>
            </Grid>
        </Border>
    </Grid>
</UserControl>

Step4: open SP_SilverlightApplication1->MainPage.xaml.cs and type the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using System.Diagnostics;


namespace SP_SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        public string HostName { get; set; }
        public string SelectedAccountName { get; set; }
        public MainPage HostControl { get; set; }
        public enum AddressType
        {
            Primary,
            Secondary
        }
        public AddressType PickerAddressType { get; set; }
        private class PickerEntry
        {
            public string DisplayName { get; set; }
            public string AccountName { get; set; }
            public PickerEntry() { }
            public PickerEntry(string displayName, string accountName)
            {
                this.DisplayName = displayName;
                this.AccountName = accountName;
            }
            public override string ToString()
            {
                return this.DisplayName;
            }
        }
        public MainPage()
        {
            InitializeComponent();
            UserNameTxt.TextDecorations = TextDecorations.Underline;
        }       
        private void OKBtn_Click(object sender, RoutedEventArgs e)
        {
            //make sure a value was selected
            if (string.IsNullOrEmpty(UserNameTxt.Text))
            {
                MessageBox.Show("You must select a user before clicking OK; if you wish to " +
                    "cancel this operation then click the Cancel button.", "Select User",
                    MessageBoxButton.OK);
                CancelBtn.Focus();
                return;
            }
            //plug in the values
            if (PickerAddressType == AddressType.Primary)
            {
                HostControl.PrimaryAdmin = SelectedAccountName;
                HostControl.PrimaryDisplayName = UserNameTxt.Text;
            }
            else
            {
                HostControl.SecondaryAdmin = SelectedAccountName;
                HostControl.SecondaryDisplayName = UserNameTxt.Text;
            }

            CloseDialog();
        }
        private void CloseDialog()
        {
            //clear out selections for next time
            SearchTxt.Text = string.Empty;
            UserNameTxt.Text = string.Empty;
            ResultsLst.Items.Clear();

            //cast the parent to popup and close; don't set visibility or it
            //causes more code the next time you want to open it up
            Popup p = (Popup)this.Parent;
            p.IsOpen = false;          
        }
        private void SearchBtn_Click(object sender, RoutedEventArgs e)
        {
            //make sure a search value was entered
            if (string.IsNullOrEmpty(SearchTxt.Text))
            {
                MessageBox.Show("You must enter a search term.", "Missing Search Term",
                    MessageBoxButton.OK);
                SearchTxt.Focus();
                return;
            }
            try
            {
                //change the cursor to hourglass
                this.Cursor = Cursors.Wait;
               
                //the main control has code like this to get the HostName
                //get info on the current host
                //string curUrl = HtmlPage.Document.DocumentUri.AbsoluteUri.ToString();

                //get the host name; note that this assumes the user has rights to the root site
                //site collection; that may not be true in your scenario
                //Uri curUri = new Uri(curUrl);
                //HostName = curUri.Scheme + "://" + curUri.Host + ":" + curUri.Port.ToString();
                //set the search request
                PeopleWS.PeopleSoapClient ps = new PeopleWS.PeopleSoapClient();
                //use the host name property to configure the request against the site in
                //which the control is hosted
                ps.Endpoint.Address =
                    new System.ServiceModel.EndpointAddress(HostName + "/_vti_bin/People.asmx");

                //create the handler for when the call completes
                ps.SearchPrincipalsCompleted +=
                    new EventHandler<PeopleWS.SearchPrincipalsCompletedEventArgs>(ps_SearchPrincipalsCompleted);               
                //execute the search
                ps.SearchPrincipalsAsync(SearchTxt.Text, 50, PeopleWS.SPPrincipalType.User);
            }
            catch (Exception ex)
            {
                //ERROR LOGGING HERE
                Debug.WriteLine(ex.Message);

                MessageBox.Show("There was a problem executing the search; please try again " +
                    "later or contact your Help Desk if the problem continues.", "Search Error",
                    MessageBoxButton.OK);
                //reset cursor
                this.Cursor = Cursors.Arrow;
            }
        }
        void ps_SearchPrincipalsCompleted(object sender, PeopleWS.SearchPrincipalsCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                    MessageBox.Show("An error was returned: " + e.Error.Message, "Search Error",
                        MessageBoxButton.OK);
                else
                {
                    System.Collections.ObjectModel.ObservableCollection<PeopleWS.PrincipalInfo>
                        results = e.Result;
                    //clear the search results listbox
                    ResultsLst.Items.Clear();
                    foreach (PeopleWS.PrincipalInfo pi in results)
                    {
                        ResultsLst.Items.Add(new PickerEntry(pi.DisplayName, pi.AccountName));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error processing the search results: " + ex.Message,
                    "Search Error", MessageBoxButton.OK);
            }
            finally
            {
                //reset cursor
                this.Cursor = Cursors.Arrow;
            }
        }
        private void AddNameBtn_Click(object sender, RoutedEventArgs e)
        {
            //see if an item is selected
            if ((ResultsLst.Items.Count == 0) || (ResultsLst.SelectedItem == null))
            {
                MessageBox.Show("You must run a search and select a name first.",
                    "Add User Error", MessageBoxButton.OK);
                return;
            }

            AddPickerEntry();
        }
        private void AddPickerEntry()
        {
            //cast the selected name as a PickerEntry
            PickerEntry pe = (PickerEntry)ResultsLst.SelectedItem;
            UserNameTxt.Text = pe.DisplayName;
            SelectedAccountName = pe.AccountName;
        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            CloseDialog();
        }
        private void SearchTxt_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                SearchBtn_Click(sender, new RoutedEventArgs());
        }

        public string PrimaryAdmin { get; set; }
        public string PrimaryDisplayName { get; set; }
        public string SecondaryAdmin { get; set; }
        public string SecondaryDisplayName { get; set; }
    }
}

Step5: Right Click SP_SilverlightApplication->Properties->Build->Output->Output path->"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin\silverlight\"

save all and build the solution

Step6: go to sharepoint application and edit any page and add a silverlight webpart from Categories->Media and Content->Silverlight web part->Add->Url->"_LAYOUTS/ClientBin/silverlight/SP_SilverlightApplication1.xap"->click OK.

Setp7: Test the Application






Wednesday, August 31, 2011

Feature to Install a Custom Master Page while Site Provisioning




step1: File->New Project-> WSPBuilder->WSPBuilder Project->WSPBuilderProject1
step2: Right click on 12 folder and create folder heirarcy as follows

12
    1033
    LAYOUTS
    SiteTemplates

step3: go to "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\SiteTemplates\sts" and copy sts folder and paste in visual studio "SiteTemplates" and rename as "DemoCompanySiteDef"

step4: go to "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\GLOBAL\default.master" and copy default.master and paste into the visual studio under the "MasterPages" folder adn rename as "DemoCompany.master"

step5: add new folder under 12->1033->"XML" foler and add one xml file and rename it as "WebTempDemoCompany.xml" [ file name MUST start with WebTemp-----.xml]

step6: Build and Deploy WSPPackage and for testing go to central admin and create a sitecollection for this
go to application management->sharepoint site management-> create site collection ->select "Web Demo" tab from select a template and select "Demo Company Site"
---------------------------------------------------------------------------------------------------------
//DemoCompanySiteDef->default.aspx

<%@ Page language="C#" MasterPageFile="~masterurl/custom.master"    Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage,Microsoft.SharePoint,Version=12.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
    <SharePoint:EncodedLiteral runat="server" text="<%$Resources:wss,multipages_homelink_text%>" EncodeMethod="HtmlEncode"/> - <SharePoint:ProjectProperty Property="Title" runat="server"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderPageImage" runat="server"><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderPageTitleInTitleArea" runat="server">
         <label class="ms-hidden"><SharePoint:ProjectProperty Property="Title" runat="server"/></label>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderTitleBreadcrumb" runat="server"/>
<asp:Content ContentPlaceHolderId="PlaceHolderTitleAreaClass" runat="server">
<style type="text/css">
TD.ms-titleareaframe, .ms-pagetitleareaframe {
    height: 10px;
}
Div.ms-titleareaframe {
    height: 100%;
}
.ms-pagetitleareaframe table {
    background: none;
    height: 10px;
}
</style>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
    <META Name="CollaborationServer" Content="SharePoint Team Web Site">
    <script type="text/javascript">
    var navBarHelpOverrideKey = "wssmain";
    </script>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderSearchArea" runat="server">
    <SharePoint:DelegateControl runat="server"
        ControlId="SmallSearchInputBox" />
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderLeftActions" runat="server">
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderPageDescription" runat="server"/>
<asp:Content ContentPlaceHolderId="PlaceHolderBodyAreaClass" runat="server">
<style type="text/css">
.ms-bodyareaframe {
    padding: 0px;
}
</style>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
    <table cellspacing="0" border="0" width="100%">
      <tr>
       <td class="ms-pagebreadcrumb">
        <asp:SiteMapPath SiteMapProvider="SPContentMapProvider" id="ContentMap" SkipLinkText="" NodeStyle-CssClass="ms-sitemapdirectional" runat="server"/>
       </td>
      </tr>
      <tr>
       <td class="ms-webpartpagedescription"><SharePoint:ProjectProperty Property="Description" runat="server"/></td>
      </tr>
      <tr>
        <td>
         <table width="100%" cellpadding=0 cellspacing=0 style="padding: 5px 10px 10px 10px;">
          <tr>
           <td valign="top" width="70%">
               <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="Left" Title="loc:Left" />
               &nbsp;
           </td>
           <td>&nbsp;</td>
           <td valign="top" width="30%">
               <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="Right" Title="loc:Right" />
               &nbsp;
           </td>
           <td>&nbsp;</td>
          </tr>
         </table>
        </td>
      </tr>
    </table>
</asp:Content>
--------------------------------------------------------------------------------------------------
DemoCompanySiteDef->xml->ONET.xml

<?xml version="1.0" encoding="utf-8"?>
<Project Title="$Resources:onet_TeamWebSite;" Revision="2" ListDir="$Resources:core,lists_Folder;" xmlns:ows="Microsoft SharePoint"><!-- _locID@Title="camlidonet1" _locComment="{StringCategory=HTX}" -->
  <NavBars>
    <NavBar Name="$Resources:core,category_Top;" Separator="&amp;nbsp;&amp;nbsp;&amp;nbsp;" Body="&lt;a ID='onettopnavbar#LABEL_ID#' href='#URL#' accesskey='J'&gt;#LABEL#&lt;/a&gt;" ID="1002" />
    <NavBar Name="$Resources:core,category_Documents;" Prefix="&lt;table border=0 cellpadding=4 cellspacing=0&gt;" Body="&lt;tr&gt;&lt;td&gt;&lt;table border=0 cellpadding=0 cellspacing=0&gt;&lt;tr&gt;&lt;td&gt;&lt;img src='/_layouts/images/blank.gif' ID='100' alt='' border=0&gt;&amp;nbsp;&lt;/td&gt;&lt;td valign=top&gt;&lt;a ID=onetleftnavbar#LABEL_ID# href='#URL#'&gt;#LABEL#&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/td&gt;&lt;/tr&gt;" Suffix="&lt;/table&gt;" ID="1004" />
    <NavBar Name="$Resources:core,category_Lists;" Prefix="&lt;table border=0 cellpadding=4 cellspacing=0&gt;" Body="&lt;tr&gt;&lt;td&gt;&lt;table border=0 cellpadding=0 cellspacing=0&gt;&lt;tr&gt;&lt;td&gt;&lt;img src='/_layouts/images/blank.gif' ID='100' alt='' border=0&gt;&amp;nbsp;&lt;/td&gt;&lt;td valign=top&gt;&lt;a ID=onetleftnavbar#LABEL_ID# href='#URL#'&gt;#LABEL#&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/td&gt;&lt;/tr&gt;" Suffix="&lt;/table&gt;" ID="1003" />
    <NavBar Name="$Resources:core,category_Discussions;" Prefix="&lt;table border=0 cellpadding=4 cellspacing=0&gt;" Body="&lt;tr&gt;&lt;td&gt;&lt;table border=0 cellpadding=0 cellspacing=0&gt;&lt;tr&gt;&lt;td&gt;&lt;img src='/_layouts/images/blank.gif' ID='100' alt='' border=0&gt;&amp;nbsp;&lt;/td&gt;&lt;td valign=top&gt;&lt;a ID=onetleftnavbar#LABEL_ID# href='#URL#'&gt;#LABEL#&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/td&gt;&lt;/tr&gt;" Suffix="&lt;/table&gt;" ID="1006" />
    <NavBar Name="$Resources:core,category_Sites;" Prefix="&lt;table border=0 cellpadding=4 cellspacing=0&gt;" Body="&lt;tr&gt;&lt;td&gt;&lt;table border=0 cellpadding=0 cellspacing=0&gt;&lt;tr&gt;&lt;td&gt;&lt;img src='/_layouts/images/blank.gif' ID='100' alt='' border=0&gt;&amp;nbsp;&lt;/td&gt;&lt;td valign=top&gt;&lt;a ID=onetleftnavbar#LABEL_ID# href='#URL#'&gt;#LABEL#&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/td&gt;&lt;/tr&gt;" Suffix="&lt;/table&gt;" ID="1026" />
    <NavBar Name="$Resources:core,category_People;" Prefix="&lt;table border=0 cellpadding=4 cellspacing=0&gt;" Body="&lt;tr&gt;&lt;td&gt;&lt;table border=0 cellpadding=0 cellspacing=0&gt;&lt;tr&gt;&lt;td&gt;&lt;img src='/_layouts/images/blank.gif' ID='100' alt='' border=0&gt;&amp;nbsp;&lt;/td&gt;&lt;td valign=top&gt;&lt;a ID=onetleftnavbar#LABEL_ID# href='#URL#'&gt;#LABEL#&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/td&gt;&lt;/tr&gt;" Suffix="&lt;/table&gt;" ID="1027" />
  </NavBars>
  <ListTemplates>
  </ListTemplates>
  <DocumentTemplates>
    <DocumentTemplate Path="STS" Name="" DisplayName="$Resources:core,doctemp_None;" Type="100" Default="FALSE" Description="$Resources:core,doctemp_None_Desc;" />
    <DocumentTemplate Path="STS" DisplayName="$Resources:core,doctemp_Word97;" Type="101" Default="TRUE" Description="$Resources:core,doctemp_Word97_Desc;">
      <DocumentTemplateFiles>
        <DocumentTemplateFile Name="doctemp\word\wdtmpl.doc" TargetName="Forms/template.doc" Default="TRUE" />
      </DocumentTemplateFiles>
    </DocumentTemplate>
    <DocumentTemplate Path="STS" DisplayName="$Resources:core,doctemp_Excel97;" Type="103" Description="$Resources:core,doctemp_Excel97_Desc;">
      <DocumentTemplateFiles>
        <DocumentTemplateFile Name="doctemp\xl\xltmpl.xls" TargetName="Forms/template.xls" Default="TRUE" />
      </DocumentTemplateFiles>
    </DocumentTemplate>
    <DocumentTemplate Path="STS" DisplayName="$Resources:core,doctemp_Powerpoint97;" Type="104" Description="$Resources:core,doctemp_Powerpoint97_Desc;">
      <DocumentTemplateFiles>
        <DocumentTemplateFile Name="doctemp\ppt\pptmpl.pot" TargetName="Forms/template.pot" Default="TRUE" />
      </DocumentTemplateFiles>
    </DocumentTemplate>
    <DocumentTemplate Path="STS" DisplayName="$Resources:core,doctemp_Word;" Type="121" Default="TRUE" Description="$Resources:core,doctemp_Word_Desc;">
      <DocumentTemplateFiles>
        <DocumentTemplateFile Name="doctemp\word\wdtmpl.dotx" TargetName="Forms/template.dotx" Default="TRUE" />
      </DocumentTemplateFiles>
    </DocumentTemplate>
    <DocumentTemplate Path="STS" DisplayName="$Resources:core,doctemp_Excel;" Type="122" Description="$Resources:core,doctemp_Excel_Desc;">
      <DocumentTemplateFiles>
        <DocumentTemplateFile Name="doctemp\xl\xltmpl.xlsx" TargetName="Forms/template.xlsx" Default="TRUE" />
      </DocumentTemplateFiles>
    </DocumentTemplate>
    <DocumentTemplate Path="STS" DisplayName="$Resources:core,doctemp_Powerpoint;" Type="123" Description="$Resources:core,doctemp_Powerpoint_Desc;">
      <DocumentTemplateFiles>
        <DocumentTemplateFile Name="doctemp\ppt\pptmpl.pptx" TargetName="Forms/template.pptx" Default="TRUE" />
      </DocumentTemplateFiles>
    </DocumentTemplate>
    <DocumentTemplate Path="STS" DisplayName="$Resources:core,doctemp_OneNote;" Type="111" Description="$Resources:core,doctemp_OneNote_Desc;">
      <DocumentTemplateFiles>
        <DocumentTemplateFile Name="doctemp\onenote\template.one" TargetName="Forms/template.one" Default="TRUE" />
      </DocumentTemplateFiles>
    </DocumentTemplate>
    <DocumentTemplate Path="STS" DisplayName="$Resources:core,doctemp_FP;" Type="102" Description="$Resources:core,doctemp_FP_Desc;">
      <DocumentTemplateFiles>
        <DocumentTemplateFile Name="doctemp\fp\fptmpl.htm" TargetName="Forms/template.htm" Default="TRUE" />
      </DocumentTemplateFiles>
    </DocumentTemplate>
    <DocumentTemplate Path="STS" DisplayName="$Resources:core,doctemp_BasicPage;" Type="105" Description="$Resources:core,doctemp_BasicPage_Desc;">
      <DocumentTemplateFiles>
        <DocumentTemplateFile Name="doctemp\blankpgs\_basicpage.htm" TargetName="Forms/_basicpage.htm" Default="TRUE" />
      </DocumentTemplateFiles>
    </DocumentTemplate>
    <DocumentTemplate Path="STS" DisplayName="$Resources:core,doctemp_WebPartPage;" Type="106" Description="$Resources:core,doctemp_WebPartPage_Desc;">
      <DocumentTemplateFiles>
        <DocumentTemplateFile Name="doctemp\smartpgs\_webpartpage.htm" TargetName="Forms/_webpartpage.htm" Default="TRUE" />
      </DocumentTemplateFiles>
    </DocumentTemplate>
    <DocumentTemplate XMLForm="TRUE" Path="STS" DisplayName="$Resources:core,doctemp_BlankForm;" Type="1000" Default="TRUE" Description="$Resources:core,doctemp_BlankForm_Desc;">
      <DocumentTemplateFiles>
        <DocumentTemplateFile Name="doctemp\xmlforms\blank\template.xml" TargetName="Forms/template.xml" Default="TRUE" />
      </DocumentTemplateFiles>
    </DocumentTemplate>
  </DocumentTemplates>
  <Configurations>
    <Configuration ID="-1" Name="NewWeb" />     
    <Configuration ID="0" Name="Default"
                   CustomMasterUrl="~SiteCollection/_catalogs/masterpage/DemoCompany.master"
                   MasterUrl="~SiteCollection/_catalogs/masterpage/DemoCompany.master">
      <Lists>
        <List FeatureId="00BFEA71-E717-4E80-AA17-D0C71B360101" Type="101" Title="$Resources:core,shareddocuments_Title;" Url="$Resources:core,shareddocuments_Folder;" QuickLaunchUrl="$Resources:core,shareddocuments_Folder;/Forms/AllItems.aspx" />
        <List FeatureId="00BFEA71-6A49-43FA-B535-D15C05500108" Type="108" Title="$Resources:core,discussions_Title;" Url="$Resources:core,lists_Folder;/$Resources:core,discussions_Folder;" QuickLaunchUrl="$Resources:core,lists_Folder;/$Resources:core,discussions_Folder;/AllItems.aspx" EmailAlias="$Resources:core,discussions_EmailAlias;" />
        <List FeatureId="00BFEA71-D1CE-42de-9C63-A44004CE0104" Type="104" Title="$Resources:core,announceList;" Url="$Resources:core,lists_Folder;/$Resources:core,announce_Folder;">
          <Data>
            <Rows>
              <Row>
                <Field Name="Title">$Resources:onetid11;</Field>
                <Field Name="Body">$Resources:onetid12;</Field>
                <Field Name="Expires">&lt;ows:TodayISO/&gt;</Field>
              </Row>
            </Rows>
          </Data>
        </List>
        <List FeatureId="00BFEA71-2062-426C-90BF-714C59600103" Type="103" Title="$Resources:core,linksList;" Url="$Resources:core,lists_Folder;/$Resources:core,links_Folder;" />
        <List FeatureId="00BFEA71-EC85-4903-972D-EBE475780106" Type="106" Title="$Resources:core,calendarList;" Url="$Resources:core,lists_Folder;/$Resources:core,calendar_Folder;" QuickLaunchUrl="$Resources:core,lists_Folder;/$Resources:core,calendar_Folder;/Calendar.aspx" EmailAlias="$Resources:core,calendar_EmailAlias;" />
        <List FeatureId="00BFEA71-A83E-497E-9BA0-7A5C597D0107" Type="107" Title="$Resources:core,taskList;" Url="$Resources:core,lists_Folder;/$Resources:core,tasks_Folder;" QuickLaunchUrl="$Resources:core,lists_Folder;/$Resources:core,tasks_Folder;/AllItems.aspx" />
      </Lists>
      <Modules>
        <Module Name="Default" />       
      </Modules>
      <SiteFeatures>
        <!-- BasicWebParts Feature -->
        <Feature ID="00BFEA71-1C5E-4A24-B310-BA51C3EB7A57" />
        <!-- Three-state Workflow Feature -->
        <Feature ID="FDE5D850-671E-4143-950A-87B473922DC7" />
        <Feature ID="95F25D4A-D256-4158-96FE-010F599149CC" />
      </SiteFeatures>
      <WebFeatures>
        <Feature ID="00BFEA71-4EA5-48D4-A4AD-7EA5C011ABE5" />
        <!-- TeamCollab Feature -->
        <Feature ID="F41CC668-37E5-4743-B4A8-74D1DB3FD8A4" />
        <!-- MobilityRedirect -->       
      </WebFeatures>
    </Configuration>

  </Configurations>
  <Modules>
    <Module Name="Default" Url="" Path="">
      <File Url="default.aspx" NavBarHome="True">
        <View List="$Resources:core,lists_Folder;/$Resources:core,announce_Folder;" BaseViewID="0" WebPartZoneID="Left" />
        <View List="$Resources:core,lists_Folder;/$Resources:core,calendar_Folder;" BaseViewID="0" RecurrenceRowset="TRUE" WebPartZoneID="Left" WebPartOrder="2" />
        <AllUsersWebPart WebPartZoneID="Right" WebPartOrder="1"><![CDATA[
                   <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2" xmlns:iwp="http://schemas.microsoft.com/WebPart/v2/Image">
                        <Assembly>Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
                        <TypeName>Microsoft.SharePoint.WebPartPages.ImageWebPart</TypeName>
                        <FrameType>None</FrameType>
                        <Title>$Resources:wp_SiteImage;</Title>
                        <iwp:ImageLink>/_layouts/images/homepage.gif</iwp:ImageLink>
                        <iwp:AlternativeText>$Resources:core,sitelogo_wss;</iwp:AlternativeText>
                   </WebPart>
                   ]]></AllUsersWebPart>
        <View List="$Resources:core,lists_Folder;/$Resources:core,links_Folder;" BaseViewID="0" WebPartZoneID="Right" WebPartOrder="2" />
        <NavBarPage Name="$Resources:core,nav_Home;" ID="1002" Position="Start" />
        <NavBarPage Name="$Resources:core,nav_Home;" ID="0" Position="Start" />
      </File>
    </Module>
  
  </Modules>
  <ServerEmailFooter>$Resources:ServerEmailFooter;</ServerEmailFooter>
</Project>
-------------------------------------------------------------------------------------------------
DemoCompanyMasterPage->feature.xml

<?xml version="1.0" encoding="utf-8" ?>
<Feature Id="95F25D4A-D256-4158-96FE-010F599149CC"
         Title="Demo Master Page"
         Scope="Site"
         Version="1.0.0.0"
         Hidden="FALSE"
         DefaultResourceFile="core"           
         xmlns="http://schemas.microsoft.com/sharepoint/"
         Description="This Feature contains the demo master page">
  <ElementManifests>
    <ElementManifest Location="elements.xml" />
    <ElementFile Location="MasterPages\DemoCompany.master" />
  </ElementManifests>
</Feature>
-----------------------------------------------------------------------------------------
DemoCompanyMasterPage->elements.xml

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="DemoCompanyMasterPage"
          Url="_catalogs/masterpage"
          Path="MasterPages"
          RootWebOnly="FALSE">
    <File Url="DemoCompany.master"
          Type="GhostableInLibrary" />
  </Module>
</Elements>
---------------------------------------------------------------------------------------------
Template->1033->XML->WebTempDemoCompany.xml

<?xml version="1.0" encoding="utf-8" ?>
<Templates xmlns:ows="Microsoft SharePoint">
  <Template Name="DemoCompanySiteDef"
            ID="10051">
    <Configuration ID="0"
                   Title="Demo Company Site"
                   Hidden="FALSE"
                   ImageUrl="/_layouts/images/stsprev.png"
                   Description="A site for the Demo Company"
                   DisplayCategory="Demo Company" >
    </Configuration>
  </Template>
</Templates>


Tuesday, August 30, 2011

Create URL Redirection upon Event Errors


File->New->Project->SharePoint 2010->Empty Project->CustomErrorPage
CustomErrorPage->Add->New Item->SharePoint 2010->Event Receiver->MaxSubSitesReceiver
EventReceiverType->Web Events
Handle Events When->site is being provisioned
//MaxSubSitesReceiver->MaxSubSitesReceiver.cs
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace CustomErrorPage.MaxSubSitesReceiver
{  
    public class MaxSubSitesReceiver : SPWebEventReceiver
    {
       public override void WebAdding(SPWebEventProperties properties)
       {
           if (properties.Web.Webs.Count >= 2)
           {
               properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
               properties.Cancel = true;
               properties.RedirectUrl = "/_layouts/CustomErrorPage/SiteCreationError.aspx";
           }
       }
    }
}
----------------------------------------------------------------------------------------
CustomErrorPage->Add->SharePoint "Layouts" Mapped Folder
Layouts->CustomErroPage->Add Item->New Item->SharePoint 2010->Application Page->SiteCreationError.aspx

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SiteCreationError.aspx.cs" Inherits="CustomErrorPage.Layouts.CustomErrorPage.SiteCreationError" DynamicMasterPageFile="~masterurl/default.master" %>
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<p>
  ERROR: You can only have a maximum of two (2) subsites in the current site.
</p>
</asp:Content>
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
  ERROR: Maximum Subsites in Current Site Exceeded
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
ERROR: Maximum Subsites in Current Site Exceeded
</asp:Content>
 

Creating List & Contenty Type with Visual Studio


//Product->Elements.xml
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <!-- Parent ContentType: Item (0x01) -->

  <Field SourceID="http://schemas.microsoft.com/sharepoint/v3"
        ID="{36819A9B-E748-47D5-9949-A65DD195BF80}"
        Name="ProductDescription"
        DisplayName="Product Description"
        Group="My Custom Columns"
        Type="Text"
        DisplaceOnUpgrade="TRUE" />

  <Field SourceID="http://schemas.microsoft.com/sharepoint/v3"
         ID="{5CD2C0C1-67AC-4F9E-BF21-463CFEE9B382}"
         Name="ProductID"
         DisplayName="Product ID"
         Group="My Custom Columns"
         Type="Number"
         DisplaceOnUpgrade="TRUE" />

  <ContentType ID="0x0100fb1ad12faa9b4834ad4d590f0f030151"
              Name="Product"
              Group="My Custom Content Types"
              Version="0">
    <FieldRefs>
      <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}"
                Name="Title"
                DisplayName="Product Name" />
      <FieldRef ID="{36819A9B-E748-47D5-9949-A65DD195BF80}"
                Name="ProductDescription" />
      <FieldRef ID="{5CD2C0C1-67AC-4F9E-BF21-463CFEE9B382}"
                Name="ProductID" />
    </FieldRefs>
  </ContentType> 
 
  <ContentType ID="0x0100e4b24eca7bb9486b8a40e6143a7d884e"
               Name="ListsAndSchemas - Product"
               Group="Custom Content Types"
               Description="My Content Type"
               Inherits="TRUE"
               Version="0">
    <FieldRefs>
    </FieldRefs>
  </ContentType>
</Elements>
----------------------------------------------------------------------------------------
//ProductList->Elements.xml
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <!-- Do not change the value of the Name attribute below. If it does not match the folder name of the List Definition project item, an error will occur when the project is run. -->
    <ListTemplate
        Name="ProductList"
        Type="100001"
        BaseType="0"
        OnQuickLaunch="TRUE"
        SecurityBits="11"
        Sequence="410"
        DisplayName="ListsAndSchemas - ProductList"
        Description="My List Definition"
        Image="/_layouts/images/itgen.png"/>
</Elements>
-----------------------------------------------------------------------------------------------

//ProductList->Schema.xml
<?xml version="1.0" encoding="utf-8"?>
<List xmlns:ows="Microsoft SharePoint" Title="ListsAndSchemas - ProductList" EnableContentTypes="TRUE" FolderCreation="FALSE" Direction="$Resources:Direction;" Url="Lists/ListsAndSchemas-ProductList" BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/">
  <MetaData>
    <ContentTypes>
      <ContentTypeRef ID="0x01">
        <Folder TargetName="Item" />
      </ContentTypeRef>
      <ContentTypeRef ID="0x0120" />
      <ContentTypeRef ID="0x0100fb1ad12faa9b4834ad4d590f0f030151" />
    </ContentTypes>
    <Fields>
      <Field ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}"
            Name="Title"
            DisplayName="Product Name"
            Type="Text" />
      <Field ID="{36819A9B-E748-47D5-9949-A65DD195BF80}"
             Name="ProductDescription"
             DisplayName="Product Description"
             Type="Text" />
      <Field ID="{5CD2C0C1-67AC-4F9E-BF21-463CFEE9B382}"
             Name="ProductID"
             DisplayName="ProductID"
             Type="Number" />
    </Fields>
    <Views>
      <View BaseViewID="0" Type="HTML" MobileView="TRUE" TabularView="FALSE">
        <Toolbar Type="Standard" />
        <XslLink Default="TRUE">main.xsl</XslLink>
        <RowLimit Paged="TRUE">30</RowLimit>
        <ViewFields>
          <FieldRef Name="LinkTitleNoMenu"></FieldRef>
          <FieldRef ID="{36819A9B-E748-47D5-9949-A65DD195BF80}"
         Name="ProductDescription"
         DisplayName="Product Description" />
          <FieldRef ID="{5CD2C0C1-67AC-4F9E-BF21-463CFEE9B382}"
                 Name="ProductID"
                 DisplayName="ProductID" />
        </ViewFields>
        <Query>
          <OrderBy>
            <FieldRef Name="Modified" Ascending="FALSE"></FieldRef>
          </OrderBy>
        </Query>
        <ParameterBindings>
          <ParameterBinding Name="AddNewAnnouncement" Location="Resource(wss,addnewitem)" />
          <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
          <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_ONET_HOME)" />
        </ParameterBindings>
      </View>
      <View BaseViewID="1" Type="HTML" WebPartZoneID="Main" DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
        <Toolbar Type="Standard" />
        <XslLink Default="TRUE">main.xsl</XslLink>
        <RowLimit Paged="TRUE">30</RowLimit>
        <ViewFields>
          <FieldRef Name="Attachments"></FieldRef>
          <FieldRef Name="LinkTitle"></FieldRef>
          <FieldRef ID="{36819A9B-E748-47D5-9949-A65DD195BF80}"
          Name="ProductDescription"
          DisplayName="Product Description" />
          <FieldRef ID="{5CD2C0C1-67AC-4F9E-BF21-463CFEE9B382}"
                 Name="ProductID"
                 DisplayName="ProductID" />
        </ViewFields>
        <Query>
          <OrderBy>
            <FieldRef Name="ID"></FieldRef>
          </OrderBy>
        </Query>
        <ParameterBindings>
          <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
          <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_DEFAULT)" />
        </ParameterBindings>
      </View>
    </Views>
    <Forms>
      <Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
      <Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
      <Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
    </Forms>
  </MetaData>
</List>
------------------------------------------------------------------------------------------------

//ProductList->Products->Elements.xml
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ListInstance Title="Products"
               OnQuickLaunch="TRUE"
               TemplateType="10001"
               Url="Lists/Products"
               Description="">
  </ListInstance>
</Elements>
---------------------------------------------------------------------------------------------

Creating Entities Using the SPMetal Utility & Creating a Visual Web Part that uses LINQ





Open Visual Studio->SharePoint 2010->Visual WebPart->LINQListsPart (as WebPart Name)
-------------------------------------------------------------------------------------------------------
//File Name is "VisualWebPart1UserControl.ascx" -> Open this file & add following code
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1UserControl.ascx.cs" Inherits="LINQListsPart.VisualWebPart1.VisualWebPart1UserControl" %>

<asp:Literal ID="Display" runat="server" Text="Dispaly"></asp:Literal>

-----------------------------------------------------------------------------------------------
// File name is: "VisualWebPart1UserControl.ascx.cs" -> Open This file & add following code
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Linq;
using Microsoft.SharePoint.Library;
using System.Text;

namespace LINQListsPart.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder writer = new StringBuilder();

            try
            {
                using (EntitiesDataContext dc = new EntitiesDataContext("http://crm-server:30312/"))
                {                   
                    var q = from emp in dc.Employees
                            where emp.Project.DueDate < DateTime.Now.AddYears(5)
                            orderby emp.Project.DueDate
                            select new { emp.Title, Contact = emp.Project.PrimaryContact.Title };


                    writer.Append("<table border=\"1\" cellpadding=\"3\" cellspacing=\"3\">");

                    foreach (var employee in q)
                    {
                        writer.Append("<tr><td>");
                        writer.Append(employee.Title);
                        writer.Append("</td><td>");
                        writer.Append(employee.Contact);
                        writer.Append("</td></tr>");
                    }
                }
            }
            catch (Exception e1)
            {
                writer.Append("<tr><td>");
                writer.Append(e1.Message);
                writer.Append("</tr></td>");
            }
            finally
            {
                writer.Append("</table>");
                Display.Text = writer.ToString();
            }
        }
    }
}