Pages

Search This Blog

Wednesday, December 14, 2011

Create Custom content type with Custom fields supporting creation of multiple types of documents (.doc, .xls, .ppt) in MOSS

At times, we may have a requirement where in we need to create different type of documents (Word - .doc/.docx , Excel - .xls/.xlsx, Powerpoint - .ppt/.pptx) in a single document library.

So we need to follow the below mentioned steps:

1. Create the required custom fields.

<Field ID="{2B333B0C-05E6-4576-A49E-8713CD6F3FA6}" Name="Field1"      DisplayName="Field1" Type="User" Required="FALSE" Indexed="TRUE"  ShowInNewForm="TRUE" ShowInEditForm="TRUE" ShowInDisplayForm="TRUE"
Group="Other Columns" >
    <Formula>=Author</Formula>
    <FieldRefs>
      <FieldRef Name="Author"/>
    </FieldRefs>
</Field>

<Field ID="{B8DEEF8E-54AA-4ad9-9AC7-115AC936228E}" Name="Field2"
 DisplayName="Field2" Type="Choice" Required="FALSE" Indexed="TRUE"   ShowInNewForm="TRUE"  ShowInEditForm="TRUE" ShowInDisplayForm="TRUE"
Group="Other Columns" >
    <CHOICES>
      <CHOICE>void</CHOICE>
    </CHOICES>
</Field>
and so on......

2. Create custom content types with the required custom fields.

<!--Generic content type inherited from document content type containing all the fields-->
<ContentType  ID="0x01010D" Name="CustomDocLibWrkspcCT" Group="Document Content Types" Description="Create a document for the document library" Version="0">
  <FieldRefs>
    <FieldRef ID="{2B333B0C-05E6-4576-A49E-8713CD6F3FA6}"  Name="Owner" Required="FALSE" ShowInNewForm="TRUE" ShowInEditForm="TRUE" ShowInDisplayForm="TRUE"/>
    <FieldRef ID="{B8DEEF8E-54AA-4ad9-9AC7-115AC936228E}" Name="Entity" Required="FALSE"   ShowInNewForm="TRUE" ShowInEditForm="TRUE" ShowInDisplayForm="TRUE"/>
  </FieldRefs>

  <XmlDocuments>
     <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
        <FormTemplates xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
          <Display>DocumentLibraryForm</Display>
          <Edit>DocumentLibraryForm</Edit>
          <New>DocumentLibraryForm</New>
        </FormTemplates>
      </XmlDocument>
    </XmlDocuments>

</ContentType>

<!--Content types inherited from above created document content type-->
<ContentType  ID="0x01010D0089A4ED8153C04980A6CC1DB53EFA85A9"
       Name="Word Document" Group="Document Content Types"
       Description="Create a word document for the document library"
       Version="0">
    <FieldRefs></FieldRefs>
  </ContentType>

<!--Content type for Excel document-->
<ContentType DocumentTemplate="122"  ID="0x01010D00A09D2732961C4ffe822B33F30117D24F" Name="Excel Document" Group="Document Content Types" Description="Create an excel document for the document library" Version="0">
    <DocumentTemplate TargetName="/_cts/Excel Document/MyTemplate.XLSX" />
    <FieldRefs></FieldRefs>   
</ContentType>

<!--Provision the document template in system content types virtual folder-->
<Module Name="XLSTemplates" Url="_cts/Excel Document" RootWebOnly="TRUE" Path="XLSTemplates" >
    <File Url="MyTemplate.XLSX" Type="Ghostable" />
</Module>

<!--Content type for PowerPoint document-->
<ContentType DocumentTemplate="123" ID="0x01010D0036A1687A93B8415fAE51C38676BACD9F" Name="PowerPoint Document" Group="Document Content Types" Description="Create a powerpoint document for the document library" Version="0" >
<DocumentTemplate TargetName="/_cts/PowerPoint Document/MyPptTemplate.PPTX" />
    <FieldRefs></FieldRefs>  
</ContentType>

<!--Provision the document template in system content types virtual folder-->
<Module Name="PPTTemplates" Url="_cts/PowerPoint Document" RootWebOnly="TRUE" Path="PPTTemplates" >
    <File Url="MyPptTemplate.PPTX" Type="Ghostable" />
</Module>

Note: The templates for these files are uploaded at the location http://minus.com/mtomNJw23

3. Attach these content types to the document library.
In the schema.xml file of the custom document library, within the <ContentTypes> tag, attach the content types created above

<ContentTypes>                 
      <ContentTypeRef ID="0x01010D0089A4ED8153C04980A6CC1DB53EFA85A9">
        <Folder TargetName="Forms/Document"/>
      </ContentTypeRef>
      <ContentTypeRef  ID="0x01010D00A09D2732961C4ffe822B33F30117D24F">
        <Folder TargetName="_cts/Excel Document"/>
      </ContentTypeRef>
      <ContentTypeRef ID="0x01010D0036A1687A93B8415fAE51C38676BACD9F">
        <Folder TargetName="_cts/PowerPoint Document"/>
      </ContentTypeRef>
      <ContentTypeRef ID="0x0120" />
</ContentTypes>

Monday, December 12, 2011

Display data by joining 2 lists using CAML : SharePoint 2010

One of the cool new features in SharePoint 2010 is to be able to perform joins using CAML query between 2 or more lists.
This example demonstrates how we can perform join between 2 lists on the basis of lookup field.

In this example, we have 2 lists named 'Courses' and 'Faculty'.

The 'Courses' list contains all courses being taught to students along with the 'Lecturer' taking the courses.The 'Lecturer' field is a lookup to the 'Title' field in 'Faculty' list which contains the name of the lecturer.This is the field on which the join will be performed.

It also contains a 'TargetGroup' field specifying which audience this post is targetted to like developer, administrator,designer etc. as shown below:




The 'Faculty' list is the master list containing all the details of the lecturers like their names and email addresses.



Now, we want to get the course title,course lecturer, lecturer's email and course's target group from the 'Courses' list where the 'TargetGroup' is 'developer'.

This can be done by creating an application page having a gridview which will display the results of the query.
The method 'GetJoinedQueryResults()' gets the records by joining 2 lists 'Courses' and 'Faculty' using the 'Lecturer' lookup field.

The query.Query contains the where clause for the query,
The query.Joins field specifies the join statement on the 'Lecturer' field using list alias 'courseLecturers' for the list
'Faculty'.
The query.ProjectedFields specifies the fields to get from the list being joined ; like 'Email' from the list 'Faculty'.
The query.ViewFields gets the fields to be displayed in the result.

The complete code for the application page along with the codebehind is given below:

<%@ 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="DisplayItemsFromJoinedCAMLQuery.aspx.cs" Inherits="Blog_Test_Project.Layouts.Blog_Test_Project.DisplayItemsFromJoinedCAMLQuery" DynamicMasterPageFile="~masterurl/default.master" %>

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">

</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">

<asp:Label ID="lblError" runat="server" Visible="false"></asp:Label>

<asp:GridView ID="gvJoinedQueryResults" runat="server" AutoGenerateColumns="false" Width="100%">
                           <EmptyDataRowStyle />
                            <EmptyDataTemplate>
                                No records found.
                            </EmptyDataTemplate>
                           <Columns>
                                <asp:BoundField DataField="Title" HeaderText="Course Title" />
                                <asp:BoundField DataField="Lecturer" HeaderText="Lecturer" />
                                <asp:BoundField DataField="Email" HeaderText="Lecturer Email" /> 
                                <asp:BoundField DataField="TargetGroup" HeaderText="Target Group" />                                                                                           
                            </Columns>
                         
                        </asp:GridView>
</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
View Results of a joined query
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
View Results of a joined query
</asp:Content>

namespace Blog_Test_Project.Layouts.Blog_Test_Project
{

public partial class DisplayItemsFromJoinedCAMLQuery : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {

           
                BindData();
           

        }


        public void BindData()
        {
            try
            {
                DataTable joinedQueryResults = GetJoinedQueryResults();
                if (joinedQueryResults != null)
                {
                    gvJoinedQueryResults.DataSource = joinedQueryResults;
                    gvJoinedQueryResults.DataBind();
                }
                else
                {
                    lblError.Text = "No records found.";
                    lblError.Visible = true;
                 
                }
               
            }
            catch (Exception ex)
            {
                lblError.Text = "An error occurred:" + ex.ToString();
                lblError.Visible = true;
                gvJoinedQueryResults.Visible = false;
            }
        }

        private DataTable GetJoinedQueryResults()
        {
            SPListItemCollection joinedResults = null;
            DataTable joinedResultsDataTable = null;

            SPWeb site = SPContext.Current.Web;
            SPList listFaculty = site.Lists["Faculty"];
            SPList listCourses = site.Lists["Courses"];
            SPQuery query = new SPQuery();
            query.Query = "<Where><Eq><FieldRef Name=\"TargetGroup\"/>" +
            "<Value Type=\"Text\">Developer</Value></Eq></Where>";
            query.Joins = "<Join Type=\"Inner\" ListAlias=\"courseLecturers\">" +
            "<Eq><FieldRef Name=\"Lecturer\" RefType=\"Id\" />" +
            "<FieldRef List=\"courseLecturers\" Name=\"Id\" /></Eq></Join>";
            query.ProjectedFields =
            "<Field Name='Email' Type='Lookup' List='courseLecturers' ShowField='Email'/>";
            query.ViewFields = "<FieldRef Name=\"Title\" /><FieldRef Name=\"Lecturer\" />" +
            "<FieldRef Name=\"Email\" /><FieldRef Name=\"TargetGroup\" />";
            joinedResults = listCourses.GetItems(query);

            if (joinedResults != null && joinedResults.Count > 0)
            {
                int fieldCount = joinedResults.Fields.Count;

                joinedResultsDataTable = joinedResults.GetDataTable();
            }

            return joinedResultsDataTable;
        }

}

Once we run this application page in the browser, we can see the results in the grid:

SharePoint 2010 FAST Search Server - Erase/Reset the content index and Clear the content collection

In SharePoint 2010 FAST Search, if you have crawled your site and after that you have deleted some documents. Again, you have full crawled your site, but the document you have deleted still show while search. Because the content index and content collection is not reset for these documents.

In SharePoint Server 2010 to reset the Content index, we need to follow following steps:

1. Open Central Administration and in the Application Management section, click Manage service applications.
2. On the Service Applications page, in the list of service applications, click your FAST Search Content SSA.



3. On the Search Administration page, under Crawling, click Index Reset.




4. On the Search Service Application: Index Reset page, click Reset Now. A confirmation dialog box appears; click OK to confirm the content index reset. The Search Service Application: Search Administration page opens and the System Status is displayed.

Before you start any new crawls, you must manually clear the content from the content collection your FAST Search Content Search Service Application was feeding to. The default collection name is sp.
Note - that clearing the content collection is irreversible.

Manually Clear the content collection:

1. On the Start menu, click All Programs, Click Microsoft FAST Search Server 2010 for SharePoint.






2. Click the Microsoft FAST Search Server 2010 for SharePoint shell.
3. At the Microsoft FAST Search Server 2010 for SharePoint shell command prompt, type the following command:
Clear-FASTSearchContentCollection -Name [collection name]
e.g.:
       Clear-FASTSearchContentCollection -Name sp






Wait for the command to finish. After successful completion, you content collection will be empty.

And after that, if you do Full Crawl, the the deleted documents will not be available.

Thanks.

Delete old versions of List Item via Poweshell SharePoint 2010


Most of the doucments were having lots of versions so the need was to remove all the existing versions except the latest version.


You can change this script to complete all the operation at one time means for all the libraries and lists under a web or all the site collections or all the web applications with in a farm.




The following script will remove all the existing versions of the documents except latest one.
PowerShell Command Prompt:


get-spWeb http://myweburl/
ForEach-Object {ForEach($_.list in $_.Lists){If($_.EnableVersioning -eq $True){if($_.Title -eq "ListName"){Write-host "List:"$_.Title "- List ID"$_.Id;$_.MajorVersionLimit = 1;$_.Update();ForEach($_.item in $_.items){$_.item.URL;$_.update()}}}}}




Note:
http://myweburl - Replace with your web URL
ListName - Replace with your list or library name
MajorVersionLimit = 1 - Change 1 to your specific limit

Saturday, December 10, 2011

Create Custom sharepoint list using ECMA scripts (Sharepoint 2010 Client Object Model)

Many a time we have a requirement that we need to create a Sharepoint list without writing any server side code.

This requirement can be achieved by using Sharepoint 2010 ECMA scripts (Sharepoint 2010 Client Object Model).

Please follow the below steps.

Step 0: Create a new site page.

Step 1: Add a content editor webpart.

Step 2: Open the HTML souce for this content editor webpart and add the below code as it is and save it.


// JScript source code

<script type="text/javascript">

//ExecuteOrDelayUntilScriptLoaded(CreateList, "sp.js");
function CreateList()
{ 
    var site;
    var context;
    var ListName = document.getElementById('listName').value;
    var field1 = document.getElementById('field1').value;
    var field2 = document.getElementById('field2').value;


    var lstDesc = "List Description";
    context = SP.ClientContext.get_current();

    var site = context.get_web();

    var SetNewList = new SP.ListCreationInformation();
    SetNewList.set_templateType(SP.ListTemplateType.genericList);
    SetNewList.set_title(ListName);
    SetNewList.set_description(lstDesc);
    //Add the list name in QuickLaunch
    SetNewList.set_quickLaunchOption(SP.QuickLaunchOptions.on);

    var NewList = site.get_lists().add(SetNewList);
    // Add fields to the newly created list.
    var NewField1 = NewList.get_fields().addFieldAsXml(
    '<Field DisplayName=\''+ field1 +'\' Type=\'Text\' />', true,
    SP.AddFieldOptions.defaultValue);
    var NewField2 = NewList.get_fields().addFieldAsXml(
    '<Field DisplayName=\''+ field2 +'\' Type=\'Text\' />', true,
    SP.AddFieldOptions.defaultValue);

    context.load(NewField1);
    context.load(NewField2);

    context.executeQueryAsync(CreateListSucceeded, CreateListFailed);
}

function CreateListSucceeded() {
  alert('List has been created Succesfully.');
}

function CreateListFailed(sender, args) {
  alert('List Creation Failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


 </script>


 //HTML code
 <b>List Name</b>
 <input id="listName" width="150px"/>
 <br/>
 <b>Field0</b>
 <input id="field1" width="150px"/>
 <b>Field1</b>
 <input id="field2" width="150px"/>
 <br/>
 <img onclick="return CreateList();" alt="Create New List" src="/sites/Test/PublishingImages/Create.PNG"/>
After doing this you will see three textbox and one create button. Fill the list name and the field names to be added and click on Create button.
This will create the new list and add the link in the quick launch menu.

Hope it will be a help to you!
Ravish

Friday, December 9, 2011

Enable Item Scheduling through code in SharePoint 2010


Many a times we need to create lists or sites from object model and hence it is often required to enable scheduling on list. Following code will do 3 things that are required to item scheduling:

  1. Enable Content approval
  2. Enable Versioning
  3. Enable Scheduling

Scheduling is dependent on both versions and content approval and should be enabled first.

Scheduling feature is only available in publishing site.


 using (SPSite site = new SPSite("http://sharepoint2010/"))
            {
                using (SPWeb web = site.RootWeb)
                {
                    SPList list=web.Lists["Documents"];
                    list.EnableModeration = true;
                    list.EnableMinorVersions = true;
                    list.Update();
                    Microsoft.SharePoint.Publishing.PublishingWeb.EnableScheduling(list);
                }
            }


list.EnableModeration = true; code will be actually doing the setting shown below:


list.EnableMinorVersions = true; this code will enable the minor versioning on the list as shown below:



Microsoft.SharePoint.Publishing.PublishingWeb.EnableScheduling(list); This code will actually enable scheduling on this list




To disable Scheduling in the list we can use following command:

Microsoft.SharePoint.Publishing.PublishingWeb.DisableScheduling(list);

###############################################################

We can also make use of powershell script for the same

$list= $SPList = Get-SPList -url "http://sharepoint2010/" -List Documents
$list.EnableModeration=$true
$list.EnableMinorVersions=$true
# To enable Scheduling in the list
[Microsoft.SharePoint.Publishing.PublishingWeb]::EnableScheduling($list)
# To disable Scheduling in the list
[Microsoft.SharePoint.Publishing.PublishingWeb]::DisableScheduling($list)