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();
            }
        }
    }
}

Create a SharePoint Lists in Object Model


 using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;

namespace LINQLists.Features.Feature1
{
    [Guid("1d80182d-25a1-4809-8104-bd915d224c76")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        private void FixupField(SPList splist, string fieldInternalName)
        {
            FixupField(splist.Fields.GetFieldByInternalName(fieldInternalName));
        }

        private void FixupField(SPField spfield)
        {
            spfield.ShowInDisplayForm = true;
            spfield.ShowInEditForm = true;
            spfield.ShowInEditForm = true;
            spfield.ShowInNewForm = true;
            spfield.ShowInVersionHistory = true;
            spfield.ShowInViewForms = true;

            SPView defaultView = spfield.ParentList.DefaultView;
            defaultView.ViewFields.Add(spfield);
            defaultView.Update();
            spfield.Update();
        }      

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using (SPWeb spWeb = (SPWeb)properties.Feature.Parent)
            {
                Guid pListGuid = spWeb.Lists.Add("Projects", "Company Projects",

SPListTemplateType.GenericList);
                spWeb.Update();               
      
                SPList pList = spWeb.Lists[pListGuid];       
                pList.OnQuickLaunch = true;
                SPField pTitleIDField = pList.Fields["Title"];
                FixupField(pList, pList.Fields.Add("Description", SPFieldType.Text, false));
                FixupField(pList, pList.Fields.Add("Due Date", SPFieldType.DateTime, false));
                SPFieldDateTime dueDateField = (SPFieldDateTime)pList.Fields["Due Date"];
                dueDateField.DisplayFormat = SPDateTimeFieldFormatType.DateOnly;
      
                dueDateField.Update();
                pList.Update();       
      
                Guid eListGuid = spWeb.Lists.Add("Employees", "Employees",

SPListTemplateType.GenericList);               
                spWeb.Update();

                SPList eList = spWeb.Lists[eListGuid];
                eList.OnQuickLaunch = true;
                SPField titleIDField = eList.Fields["Title"];
                titleIDField.Title = "Fullname";
                titleIDField.Update();
      
                FixupField(eList, eList.Fields.Add("JobTitle", SPFieldType.Text, false));
                FixupField(eList, eList.Fields.Add("Team", SPFieldType.Text, false));
                FixupField(eList, eList.Fields.Add("Contribution (in Milestones)",

SPFieldType.Number, false));
                string projectFieldInternalName = eList.Fields.AddLookup("Project", pListGuid,

false);
                SPFieldLookup projectField =

(SPFieldLookup)eList.Fields.GetFieldByInternalName(projectFieldInternalName);
                projectField.LookupField = pTitleIDField.InternalName;

                FixupField(projectField);
                eList.Update();       
      
                string employeeFieldInternalName = pList.Fields.AddLookup("Primary Contact",

eListGuid, false);
                SPFieldLookup managerField =

(SPFieldLookup)pList.Fields.GetFieldByInternalName(employeeFieldInternalName);
                managerField.LookupField = titleIDField.InternalName;
                FixupField(managerField);
                pList.Update();
            }
        }
        
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            using (SPWeb spWeb = (SPWeb)properties.Feature.Parent)
            {
                SPList empList = spWeb.Lists["Employees"];
                empList.Delete();
                spWeb.Update();
                SPList proLists = spWeb.Lists["Projects"];
                proLists.Delete();
                spWeb.Update();
            }
        }
        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}
        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //} 
        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string
upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}

Sandbox WebPart

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;

namespace SandboxedWebPart.WebPart1
{
    [ToolboxItemAttribute(false)]
    public class WebPart1 : WebPart
    {
        protected override void CreateChildControls()
        {
            Label message1 = new Label();
            Controls.Add(message1);

            Controls.Add(new WebControl(HtmlTextWriterTag.Br));
            Controls.Add(new WebControl(HtmlTextWriterTag.Br));
            Button testButton1 = new Button();
            testButton1.Text = "Test 1";
            testButton1.Click += delegate
            {
                message1.Text = string.Format("Site having {0} Lists", SPContext.Current.Web.Lists.Count);
            };
            Controls.Add(testButton1);

            Button testButton2 = new Button();
            testButton2.Text = "Test 2";
            testButton2.Click+=delegate
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(
                        delegate
                        {
                            using (SPSite siteCollection = new SPSite(SPContext.Current.Site.ID))
                            {
                                SPWeb web = siteCollection.OpenWeb();
                                message1.Text = string.Format("Site having {0} Lists", web.Lists.Count);
                            }
                        });
                }
                catch (Exception e)
                {
                    message1.Text = e.Message;
                }
            };
            Controls.Add(testButton2);

            Button testButton3 = new Button();
            testButton3.Text = "Test 3";
            testButton3.Click += delegate
            {
                try
                {
                    System.Net.HttpWebRequest.Create("http://crm-server:30312");
                }
                catch (Exception e)
                {
                    message1.Text = e.Message;
                }
            };
            Controls.Add(testButton3);

            Button testButton4 = new Button();
            testButton4.Text = "Test 4";
            testButton4.Click += delegate
            {
                try {
                    SPWeb site = SPContext.Current.Web;
                    SPSiteDataQuery query = new SPSiteDataQuery();
                    query.Lists = @"<Lists ServerTemplate=""104""/>";
                    query.Webs = @"<Webs Scope=""Recursive""/>";
                    message1.Text="No.Of Site Records "+site.GetSiteData(query).Rows.Count;
                }
                catch(Exception e)
                {
                    message1.Text = e.Message;
                }
            };
            Controls.Add(testButton4);
        }
    }
}

Monday, August 29, 2011

InfoPath Interview Questions

Q. How do I retrieve the value of an InfoPath field through code?
Ans.
XPathNavigator nav = MainDataSource.CreateNavigator();
string fieldValue = nav.SelectSingleNode("//my:field1", NamespaceManager).Value;

Q. How do I set the value of an InfoPath field through code?
Ans.
XPathNavigator nav = MainDataSource.CreateNavigator();
nav.SelectSingleNode("//my:field1", NamespaceManager).SetValue("myValue");

Q. How do I call a web service through code?
Ans.
// Create an XPathNavigator object to navigate the data source of the web service
XPathNavigator nav = DataSources["HelloWorld"].CreateNavigator();

// Set the value of the parameter to pass to the web service
nav.SelectSingleNode("//dfs:queryFields/tns:HelloWorld/tns:name", NamespaceManager).SetValue("myValue");

// Call the web service
DataSources["HelloWorld"].QueryConnection.Execute();
// Retrieve the results returned by the web service
string results = nav.SelectSingleNode("//dfs:dataFields/tns:HelloWorldResponse/tns:HelloWorldResult", //NamespaceManager).Value;
//where HelloWorld is the name of a data connection to a web service.


Simple Captcha Example

<html>
<head>
<title>Captcha</title>   
    <script type="text/javascript">
   //Created / Generates the captcha function   
    function DrawCaptcha()
    {
        var a = Math.ceil(Math.random() * 10)+ '';
        var b = Math.ceil(Math.random() * 10)+ '';      
        var c = Math.ceil(Math.random() * 10)+ ''; 
        var d = Math.ceil(Math.random() * 10)+ ''; 
        var e = Math.ceil(Math.random() * 10)+ ''; 
        var f = Math.ceil(Math.random() * 10)+ ''; 
        var g = Math.ceil(Math.random() * 10)+ ''; 
        var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
        document.getElementById("txtCaptcha").value = code
    }
    // Validate the Entered input aganist the generated security code function  
    function ValidCaptcha(){
        var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
        var str2 = removeSpaces(document.getElementById('txtInput').value);
        if (str1 == str2) return true;       
        return false;       
    }
    // Remove the spaces from the entered and generated code
    function removeSpaces(string)
    {
        return string.split(' ').join('');
    } 
    </script> 
</head>
<body onload="DrawCaptcha();">
<table>
<tr>
    <td>
        Welcome To Captcha<br />
    </td>
</tr>
<tr>
    <td>
        <input type="text" id="txtCaptcha"
            style="background-image:url(1.jpg); text-align:center; border:none;
            font-weight:bold; font-family:Modern" />
        <input type="button" id="btnrefresh" value="Refresh" onclick="DrawCaptcha();" />
    </td>
</tr>
<tr>
    <td>
        <input type="text" id="txtInput"/>   
    </td>
</tr>
<tr>
    <td>
        <input id="Button1" type="button" value="Check" onclick="alert(ValidCaptcha());"/>
    </td>
</tr>
</table>
</body>
</html>



Thursday, August 25, 2011

Using ADO.NET Data Services











using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Linq;
using System.Net;

namespace ProjectManagers
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        MyDataService.MeetingMangementDataContext ctx = new MyDataService.MeetingMangementDataContext(new Uri("http://crm-server:6861/_vti_bin/ListData.svc"));

        private void Form1_Load(object sender, EventArgs e)
        {
            ctx.Credentials = CredentialCache.DefaultCredentials;
            var q = from a in ctx.Announcements select a;
            this.announcementsItemBindingSource.DataSource = q;
        }

        private void announcementsItemBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            ctx.SaveChanges();
        }

        private void announcementsItemBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            ctx.UpdateObject(this.announcementsItemBindingSource.Current);
        }

    }
}

Client Object Model




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ClientOM = Microsoft.SharePoint.Client;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Packaging;

namespace ListPrinter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void ShowButton_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            ListsListBox.Items.Clear();
            using(ClientOM.ClientContext ctx=new ClientOM.ClientContext(UrlTextBox.Text))
            {
                ClientOM.Web site=ctx.Web;
                ctx.Load(site);
                ctx.Load(site.Lists);
                ctx.ExecuteQuery();
                foreach (ClientOM.List list in site.Lists)
                {
                    ListsListBox.Items.Add(list.Title);
                    this.Cursor = Cursors.Default;
                }
            }
        }

        private void PrintButton_Click(object sender, EventArgs e)
        {
            if (ListsListBox.SelectedIndex > -1)
            {
                using (ClientOM.ClientContext ctx = new ClientOM.ClientContext(UrlTextBox.Text))
                {
                    string listTitle = ListsListBox.SelectedItem.ToString();
                    ClientOM.Web site = ctx.Web;
                    ctx.Load(site, s => s.Lists.Where(t => t.Title == listTitle));
                    ctx.ExecuteQuery();

                    ClientOM.List list = site.Lists[0];
                    ctx.Load(list, l => l.Fields.Where(f => f.Hidden == false && (f.CanBeDeleted || f.InternalName == "Title")));
                    ctx.ExecuteQuery();

                    ClientOM.ListItemCollection listItems = list.GetItems(ClientOM.CamlQuery.CreateAllFoldersQuery());
                    ctx.Load(listItems);
                    ctx.ExecuteQuery();

                    using (WordprocessingDocument package =
                WordprocessingDocument.Create("c:\\test1\\" + ListsListBox.SelectedItem.ToString() + ".docx",  WordprocessingDocumentType.Document))
                    {
                        Body body = new Body();
                        Table table = new Table();

                        //Columns
                        TableRow colRow = new TableRow();
                        foreach (ClientOM.Field field in list.Fields)
                        {
                            TableCell colCell = new TableCell();
                            colCell.Append(new Paragraph(new Run(new Text(field.Title))));
                            colRow.Append(colCell);
                        }
                        table.Append(colRow);

                        //Rows
                        foreach (ClientOM.ListItem item in listItems)
                        {
                            TableRow dataRow = new TableRow();

                            foreach (ClientOM.Field field in list.Fields)
                            {
                                TableCell dataCell = new TableCell();
                                string dataVal = string.Empty;
                                try
                                {
                                    dataVal = item[field.InternalName].ToString();
                                }
                                catch { dataVal = "-"; }
                                dataCell.Append(new Paragraph(new Run(new Text(dataVal))));
                                dataRow.Append(dataCell);
                            }

                            table.Append(dataRow);
                        }

                        body.Append(table);                       
                        package.AddMainDocumentPart();
                        package.MainDocumentPart.Document = new Document(body);
                        package.MainDocumentPart.Document.Save();
                        package.Close();
                    }
                }
                MessageBox.Show(" Document Created! ");
            }
        }
    }
}