Thursday 13 December 2012

ECMA Script to update today’s date in all list items in SharePoint 2010


1)      Create a column in the list with the “Date and Time” as its field type.
2)      Add the Content Editor Web Part & copy the below script
3)      Give your list name & list column name wherever required.
<script>
var clientContext;
var web = null;
    ExecuteOrDelayUntilScriptLoaded(UpdateList, 'sp.js');
    function UpdateList()
    {
     if (SP.ClientContext != undefined && SP.ClientContext != null) {
            clientContext = new SP.ClientContext.get_current();
            if (clientContext != undefined && clientContext != null) {
                    var siteColl =                     web = siteColl.get_rootWeb();
                    var list = web.get_lists().getByTitle('List Name');
                    var query = SP.CamlQuery.createAllItemsQuery();
                    this.listItems= list.getItems(query);
                    clientContext.load(this.listItems, 'Include(Column Name)');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccess), Function.createDelegate(this, this. onListItemsLoadFailed));
       }
   }
}
   function onListItemsLoadSuccess()
    {
            var listEnumerator = this.listItems.getEnumerator();
            while(listEnumerator.moveNext())
            {
                var todaysDate = new Date();
                var oListItem = listEnumerator.get_current();
                var currentdate = oListItem.get_item('Column Name');
                oListItem.set_item('DueDate',todaysDate);
                oListItem.update();
           }
           clientContext.executeQueryAsync(Function.createDelegate(this, this.ListItemsUpdateSuccess), Function.createDelegate(this, this.ListItemsUpdateFailed));
  }

    function onListItemsLoadFailed ()
    {
        alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
    }

function ListItemsUpdateSuccess()
{
        alert('Success ');
}
function ListItemsUpdateFailed()
{
      alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
 

</script>

JQuery to display today's date on list column using HTML tag


1.       Create a column in my list called "DateField", use the calculation field with ="<B></B>" as the calculation
2.        Create a Content Edit Web Part and use the source below:


<script src="/path/jquery.min.js" type="text/javascript"></script>
<script src="/path/jquery-1.4.2.min.js" type="text/javascript"></script>

<script type="text/javascript">

//get current date
var currentTime = new Date()
var month = currentTime.getMonth()+1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var CurrentDate = month + "/"+ day + "/" + year

//check for our html tag to replace the value
$(document).ready(function(){
$(".ms-vb2:contains('<B')").each(function(){
var tempB = document.createElement ("B");
tempB.style.cursor = "pointer";
tempB.innerHTML = $(this).text();
$(this).text(CurrentDate);
$(this).append(tempB);
});
});

</script>

Script for shrinking DataBase Logs SharePoint 2010


The below script when run on the DataBase Server creates a temporary table, gets all the logs of all the sites of the Web Application in that table, shrinks all the logs & then deletes the temporary table.

CREATE TABLE #TransactionLogFiles (DatabaseName VARCHAR(150), LogFileName VARCHAR(150) )
-- step 1. get hold of the entire database names from the database server
DECLARE DataBaseList CURSOR FOR
SELECT name FROM SYS.sysdatabases

WHERE NAME NOT IN ('master','tempdb','model','msdb','distribution')

DECLARE @DataBase VARCHAR(128)
DECLARE @SqlScript VARCHAR(MAX)
-- step 2. insert all the database name and corresponding log files' names into the temp table
OPEN DataBaseList FETCH
NEXT FROM DataBaseList INTO @DataBase
WHILE @@FETCH_STATUS <> -1
BEGIN

SET @SqlScript = 'USE [' + @DataBase + '] INSERT INTO #TransactionLogFiles(DatabaseName, LogFileName) SELECT '''
+ @DataBase + ''', Name FROM sysfiles WHERE FileID=2'
--SELECT @SqlScript
EXEC(@SqlScript)
FETCH NEXT FROM DataBaseList INTO @DataBase END

DEALLOCATE DataBaseList

-- step 3. go through the each row and execute the shrinkfile script against each database log file on the server
DECLARE TransactionLogList CURSOR FOR
SELECT DatabaseName, LogFileName FROM #TransactionLogFiles
DECLARE @LogFile VARCHAR(128)

OPEN TransactionLogList FETCH
NEXT FROM TransactionLogList INTO @DataBase, @LogFile
WHILE @@FETCH_STATUS <> -1
BEGIN
SELECT @SqlScript = 'USE [' + @DataBase + '] '
+ 'ALTER DATABASE [' + @DataBase + '] SET RECOVERY SIMPLE WITH NO_WAIT '
+ 'DBCC SHRINKFILE(N''' + @LogFile + ''', 1) '
+ 'ALTER DATABASE [' + @DataBase + '] SET RECOVERY FULL WITH NO_WAIT'
EXEC(@SqlScript)

FETCH NEXT FROM TransactionLogList INTO @DataBase, @LogFile END
DEALLOCATE TransactionLogList
--SELECT * FROM #TransactionLogFiles

-- step 4. clean up
DROP TABLE #TransactionLogFiles

Configuring Adobe PDF iFilter 9 for 64-bit platforms for MS SharePoint 2010


Note: The steps mentioned below are as per suggested by Microsoft. Please refer to links below for appropriate Microsoft KB articles.
http://support.microsoft.com/?id=555209

1. Install Adobe PDF iFilter 9 for 64-bit platforms.
http://blogs.msdn.com/ifilter/archive/2007/03/29/indexing-pdf-documents-with-adobe-reader-v-8-and-moss-2007.aspx

2. Verify that PDF has been added to the registry.

a. Run Regedit by browsing to c:\Windows\system32\regedt32.exe and double-clicking it. 
b. Within left-side tree, browse to: \\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office 
Server\12.0\Search\Applications\{site GUID}\Gather\Portal_Content\Extensions\ExtensionList 
c. If PDF extension is present, skip to Step 3  . If PDF extension is not present, continue with 
Step d. 
d. Right click on right-side Extension List pane and choose New > String Value 
e. Add a name to the new Registry Key (e.g. “38”) 
f. Double click the new Registry Key. For “Value data”, enter “pdf”

Note: This can also be achieved via SharePoint Server Search Administration page by adding ‘pdf’ to list
of File Types in Search Administration->File Types. This would automatically add an entry for ‘pdf’ filetype as mentioned above in step 1

3. Verify that PDF has the correct settings in a second registry location.

a. While still in Regedit, within the left-side tree, browse to: \\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\12.0\Search\Setup\Filters\.pdf 
b. Verify the following values. If values are not as shown, edit them. 
i. <REG_SZ> Default = <value not set>
ii. <REG_SZ> Extension = pdf
iii. <REG_DWORD> FileTypeBucket = 1
iv. <REG_SZ> MimeTypes = application/pdf

4. Verify that PDF has the correct settings in a third registry location.

a. While still in RegEdit, within the left-side tree, browse to:
\\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\OfficeServer\12.0\Search\Setup\ContentIndexCommon\Filters\Extension\.pdf 
b. Verify the following values. If values are not as shown, edit them. 
i. <REG_MULTI_SZ> Default = {E8978DA6-047F-4E3D-9C78-CDBE46041603}

5. Verify that pdf.gif is present at the following location:
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\IMAGES

6. Add an entry in docicon.xml for the pdf icon:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\XML
<Mapping Key="pdf" Value="pdf.gif">

Note: Step 4 & 5 are done in order to have the pdf icon in SharePoint while it displays the search results.

7. Restart all SharePoint services as well as IIS.

a. Launch the DOS Shell (Start > All Programs > Accessories > Command Prompt). 
b. Type the following at the prompt: “net stop osearch”. Wait for success message.
c. Type the following at the prompt: “net start osearch”. Wait for success message.
d. Type the following at the prompt: “iisreset”. Wait for success message.Close the Command Prompt window.

8. Perform a Full Crawl

9. Microsoft Office SharePoint Server can now index PDF files. Also, PDF icon should show in File Types list.

JQuery to Display Slide Show Images within fixed size SharePoint 2010


The Slide Show Web part displays the images from the given picture library with its actual size i.e the size of the Slide Show Web part varies according to the size of the image. We can restrict the size of the web part through Edit Web Part properties but this does not change the size of the image. To display the whole image within that restricted area we have to change the height & width of the image during runtime to fit to the size. Only change the image size will not display the image in the middle position. To do this we first have to change the size of the table td tag to fit to the Slide Show Web Part screen.

Below script first sets the size of the table td tag & then sets the size of the image.

<script type="text/javascript">

$(document).ready(function() {   
//get the ID of the DIV inside td within which the slide show web part is present
var tdlist=$("div[id^='WebPartct100']");
var currtd=$("td[id$='td']"); tdlist.height('100%');  
tdlist.width('100%');  
//assign the height & width to the td
currtd.height('150px');  
currtd.width('240px');
//get the ID of the DIV of slide show web part

var divList = $("div[id^='MSOPictureLibrarySlideshowWebPart']");  
var currImage= $("img[id$='curr']");  
divList.height('100%');  
divList.width('100%');  
//assign the height & width to the image
currImage.height('130px');  
currImage.width('230px');  
});


</script>

Powershell Script to Display Developer Dashboard

Below is the Powershell command to enable the Developer Dashboard for the SharePoint 2010 sites

$sp2010= [Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashboardSettings;
$sp2010.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::OnDemand
$addsetting.Update()

Save Site as Template Powershell Command


You can save your site as template even with the publishing feature using the following Powershell command

$Web=Get-SPWeb http://Server/Site
$Web.SaveAsTemplate("Template Name","Template Title","Template Description",1)

In the forth parameter of SaveAsTemplate(), if you want to save the specified site as template along with data use 1, otherwise use 0.
After running above commands, the newly created template will be available in site collection "Solutions" gallery

An unhandled exception occurred in the Silverlight application SharePoint 2010


In SharePoint 2010 you may receive the error "an unhandled exception occurred in the Silverlight application SharePoint 2010" on sites. This will generally occur when trying to create new Lists, Libraries, Sites or Pages. This happens because Silverlight is unable to connect to the Windows Communication Foundation endpoint for enabling the Client Object Model, if Security validation is Off. To resolve the problem navigate to Central Administration and enable the Web Page Security Validation for the Web Application. Do the following:


1.       Open Central Administration
2.        Select Application Management
3.        Select Manage Web Applications
4.        Select the Web Application where the error occurs
5.        In the ribbon, select General Settings
6.        In the Web Application General Settings dialog box, find Web Page Security      Validation and select On.

Tuesday 28 August 2012

Script to Hide Workspace field in Calendar NewForm

The User can create a calendar using Calendar Template in SharePoint. The user can add the daily details in the calendar. To add the details the user clicks on "Add" link & the NewForm.aspx page opens to enter the details of the item as shown below.



Now the admin does not want the user to create his own workspace. So the Workspace field should not be visible to the user. To hide the Workspace field open the NewForm.aspx page in seperate tab. Now edit the page & add a CEWP & add the following javascript in the CEWP.


<script language="javascript" type="text/javascript">
 
_spBodyOnLoadFunctionNames.push("hideWorkSpacefield");

function hideWorkSpacefield()
{
     var control = findacontrol("Workspace");
   control.parentNode.parentNode.style.display="none";
}

function findacontrol(FieldName) 
{
   var arr = document.getElementsByTagName("!");
   // get all comments
   for (var i=0;i < arr.length; i++ )
   {
      // now match the field name
      if (arr[i].innerHTML.indexOf(FieldName) > 0)
      {         return arr[i];      }
   }
}

</script>

The above script hides the Workspace field whenever the user clicks on the NewForm.aspx page as shown below.



Monday 27 August 2012

Change the Text "Respond to this Survey" in Survey list

We can create Survey in SharePoint using the Survey Template & add questions in the survey. After creating the survey, user can see the details of the survey as shown below.




Now to respond to the survey user clicks on the "Respond to this survey" link.

In the same way I want to create a quiz using the survey template. But after creating the quiz it shows "Respond to this survey" link which I don't want. I want to display "Respond to this Quiz". Also I want to change the text "Survey Name" & "Survey Description" to "Quiz Name" & "Quiz Description" respectively.

We can achieve this by adding the Javascript. Add a CEWP on the Survey page & add the following script in the CEWP. 


<script type="text/javascript">
$(document).ready(function() {
$('[title]').removeAttr('title');
changespantext();
changeName();
});

function changespantext()
{
  var spans = document.getElementsByTagName("span");
    for(var i=0;i<spans.length; i++)
   {
    if(spans[i].innerHTML == "Respond to this Survey")
     {                                                //is this the "Respond to this Survey" span?
        spans[i].innerHTML = "Respond to this Quiz";  //change to new value
         break;                                      //hop out of the loop, we're done
     }
   }
}

function changeName()
{
   var tdid= document.getElementById("overview01");
   var tdid1= document.getElementById("overview02");

   tdid.innerHTML="Quiz Name:";
   tdid1.innerHTML="Quiz Description:";
}

 </script>

Now stop editing the page & you will see the changes as follows.





Thursday 23 August 2012

Hide "Show Quoted Messages" in discussion Board

I have created a discussion in a discussion board list. When I participate in the Discussion, after every reply there is a link displayed at the end of the discussion saying "Show Quoted Messages". I don't want these links to appear anywhere in the discussion screen.

To hide the "Show Quoted Messages" link edit the page & add a CEWP at the top of the list. Now add the following script in the CEWP.


<script type="text/javascript">
$(document).ready(function() {
var elements = document.getElementsByTagName("a");
for (var key = 0; key < elements.length; key++){   
    if (elements[key].innerHTML.indexOf("Show Quoted Messages") != -1){
        elements[key].style.display = 'none';
    }
}
});</script>


Now stop editing the page & you will notice that "Show Quoted Messages" link is no more visible.

Also we can hide the View Properties link next to the Reply link.

To hide the View Properties link add the following script in the CEWP


<style type="text/css">
TABLE.ms-disc-bar TD A[id^='DisplayLink'] {
    DISPLAY: none
}
TABLE.ms-disc-bar TD.ms-separator IMG {
    DISPLAY: none
}</style>

Get Internal Name of Custom List Template

I was trying to create the document libraries & lists by selecting the custom library & list templates. Creating each list & library was a time consuming task. So I decided to create lists & libraries using powershell script. After creating the powershell script I fetched the list /library name & the custom template name from the csv file.

To know more about the script visit this link
http://spcodes.blogspot.in/2012/08/create-multiple-libraries-using-custom.html

When I executed the script, it came to the observation that the name of the custom template in the csv file should be the internal name of that template & not the display name.

To get the internal name of the Custom Template use the following powershell script:


$site = Get-SPSite -Identity http://applicationname/sites/sitename
$site.GetWebTemplates(1081) |  Where-Object {$_.name -like "*[CustomLibraryTemplateDisplayName]*"} | Select Name


Save the following code with the .ps1 extension & execute the script using SharePoint Management Shell.

Script to Create Multiple Libraries using Custom Template


Creating a document library is very simple. But always adding columns & setting the view of that library same as other becomes a time consuming task. So, to avoid these tasks I performed all the necessary tasks on library & saved that document library as template (CustomLibraryTemplate.stp) & then while creating a new document library I selected the same template(CustomLibraryTemplate) while creating new document library. This solution made it easier to create document libraries with the specified columns & the default view.

Now creating limited libraries is possible, but creating multiple document libraries using the same template again became the time consuming task as I had to create each document library manually. Then I searched for the powershell script which can create these libraries on One click.

The below given script gets the name of the Document Library & the name of the template using which the document library is to be created from the CreateDocumentLibraries.csv file & creates the libraries or lists as per the information stored in the csv file. 

This script creates the libraries & lists using the custom template as well as the default templates(DocumentLibrary, PictureLibrary).



$url = "http://servername/sites/sitename"
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
$spSite = New-Object Microsoft.SharePoint.SPSite($url)
$spWeb = $SPSite.OpenWeb()
$listTemplates = $spSite.GetCustomListTemplates($spWeb)
$listTemplate1 = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
$listTemplate2 = [Microsoft.SharePoint.SPListTemplateType]::PictureLibrary
$filePath= "FilePaht\CreateDocumentLibraries.csv"
$data = Import-Csv $filePath
$spListCollection = $spWeb.Lists
 foreach($line in $data)
 {
 $DocLibs=$line.DocLibs.trim()
 #$DocDescription=$line.DocDescription.trim()
 $listTemplate=$line.listTemplate.trim()
 $spWeb.ListTemplates | ForEach{ write-host $_.Name }
 if($listTemplate -eq "DocumentLibrary")
 {
    $spWeb.Lists.Add($DocLibs,"",$listTemplate1)
 }
 if($listTemplate -eq "PictureLibrary")
 {
    $spWeb.Lists.Add($DocLibs,"",$listTemplate2)
 }
 if($listTemplate -eq "CustomLibraryTemplate")
 {
    $spWeb.Lists.Add($DocLibs,"",$listTemplates["CustomLibraryTemplate"])
 }

 if($listTemplate -eq "CustomListTemplate")
 {
    $spWeb.Lists.Add($DocLibs,"",$listTemplates["CustomListTemplate"])
 }

 if($listTemplate -eq "CustomAnnouncementTemplate")
 {
    $spWeb.Lists.Add($DocLibs,"",$listTemplates["CustomAnnouncementTemplate"])
 }

 if($listTemplate -eq "CustomDiscussionBoardTemplate")
 {
    $spWeb.Lists.Add($DocLibs,"",$listTemplates["DiscussionBoardTemplate"])
 }

 $docLib = $spWeb.Lists[$DocLibs]
 $docLib.Update()
 Write-Host Created document library $line.DocLibs
 }


The entries in the csv file are as follows:

DocLibs,listTemplate
DocumentLibrary,CustomLibraryTemplate
List,CustomListTemplate
Pictures,PictureLibraryTemplate
AnnouncementList,CustomAcnnouncementTemplate
DiscussionBoardList,CustomDiscussionBoardTemplate


 When we have finished creating both the files, now open the Powershell Management tool & run a single command which contains only the path of the powershell script. e.g.- FilePaht\CreateDocumentLibraries.ps1.

The script will stop after all the lists & libraries are created within the site collection.


Tuesday 7 August 2012

Change Default List Layout using css during runtime


To hide the Header of the list we can insert the following css in the CEWP above the list or anywhere on page.

.ms-viewheadertr {
    DISPLAY: none
}

To hide the new.gif image in front of the Name of newly added item we can insert the following css
IMG.ms-newgif {
    DISPLAY: none
}

To highlight the row of the list item in different color on the mouse hover on the item insert the following css. Here in the below example we will make the background transparent.

.ms-itmhover {
    BACKGROUND-COLOR: transparent
}
.ms-vb2 {
    COLOR: black; FONT-WEIGHT: normal
}


.ms-alternating {
    BACKGROUND-COLOR: transparent
}


To change the background of the bottom paging to transperant insert the following css

.ms-bottompagingline1 {
    BACKGROUND: #f7f7f7
}
.ms-bottompaging .ms-vb {
    BACKGROUND: #f7f7f7
}
.ms-bottompagingline2 {
    BACKGROUND: #f7f7f7
}
.ms-bottompagingline3 {
    BACKGROUND: #f7f7f7
}

Display Slide Show Images within fixed size


The Picture Library Slide Show Web Part show the images stored in a picture library with slide show effect.
This slide show web part displays the images with it's original size. Due to this the web part changes its size according to the image size. If we want the slide show to run within the specific size on the page then we need to control the size of the images to the fixed length during runtime.

To achieve this we need to add the CEWP above the picture Library Slide Show web part & insert the following script in that web part.

<style type="text/css">
.ms-WPBody TD {
    PADDING-BOTTOM: 0px; BORDER-RIGHT-WIDTH: 0px; MARGIN: 0px; PADDING-LEFT: 0px; WIDTH: auto !important; PADDING-RIGHT: 0px; BORDER-TOP-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; HEIGHT: auto !important; VERTICAL-ALIGN: middle; BORDER-LEFT-WIDTH: 0px; PADDING-TOP: 0px
}
.ms-WPBody TD DIV {
    PADDING-BOTTOM: 0px; BORDER-RIGHT-WIDTH: 0px; MARGIN: 0px; PADDING-LEFT: 0px; WIDTH: 100% !important; PADDING-RIGHT: 0px; BORDER-TOP-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; HEIGHT: auto !important; VERTICAL-ALIGN: middle; BORDER-LEFT-WIDTH: 0px; PADDING-TOP: 0px
}
.ms-WPBody TD IMG {
    PADDING-BOTTOM: 0px; BORDER-RIGHT-WIDTH: 0px; MARGIN: 0px; PADDING-LEFT: 0px; WIDTH: 260px !important; PADDING-RIGHT: 0px; BORDER-TOP-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; HEIGHT: 190px !important; VERTICAL-ALIGN: middle; BORDER-LEFT-WIDTH: 0px; PADDING-TOP: 0px; align: center
}
.s4-wpcell-plain {
    PADDING-BOTTOM: 0px; BORDER-RIGHT-WIDTH: 0px; MARGIN: 0px; PADDING-LEFT: 0px; WIDTH: 100% !important; PADDING-RIGHT: 0px; BORDER-TOP-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; HEIGHT: auto !important; VERTICAL-ALIGN: middle; BORDER-LEFT-WIDTH: 0px; PADDING-TOP: 0px
}
.ms-PartSpacingVertical {
    MARGIN-TOP: 0px
}
.style1 {
    COLOR: #808080
}</style>


We can fix the height & width of the image in the .ms-WPBody TD IMG css.