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.

Monday 6 August 2012

Site Collection Restore Script

If we want to restore a single site collection through Powershell we use the following command:

Restore-SPSite "SiteURL" -path "Pathofbackupfile\backupfilename.bak" -Force -DatabaseServer DataBaseInstanceName -DatabaseName "ContentDataBase"

This will restore a single site collection. But if we have to restore many site collections then running the above command every time will not be feasible & is a waste of time.
Now the way out in this situation is to prepare a Powershell script & run the script once & it will restore all the site collections we want. This Powershell script reads the site URL, backup name, DataBase Server name & Content DataBase Name from a csv file. We will enter the url's & their respective backup file names, Server Name & ContentDataBase name in the csv file type & give the path of the csv file in the script. This script now reads the values one by one from each row & restores the site collections.
When the rows are finished from the csv file then it stops the script. In this way we can restore large number of site collections by running a single command.

The Powershell script is as follows:

$backupfolder= "Path of Backup files"
$filePath = "Path of .csv file"
$csv_info = Import-Csv $filePath
$count =$csv_info.count
#iterate Csv File
foreach ($line in $csv_info)
{
$siteurl = $line.SiteUrl.trim()
$DatabaseInstance = $line.DatabaseInstance.trim()
$ContentDatabase = $line.ContentDatabase.trim()
$backuppath = $backupfolder + "\" + $line.BackupPath.trim()
#cls
Restore-SPSite -Identity $siteurl -Path $backuppath -Force -DatabaseServer $DatabaseInstance -DatabaseName $ContentDatabase
#Write-Host $siteurl
Write-Host $backuppath
Write-Host "Sucess"
}


Save the file with the .ps1 extension. e.g.- "restorescript.ps1".

Create a csv file & insert the entries as follows:


SiteUrl,BackupPath,DatabaseInstance,ContentDatabase
http://siteurl,siteurl.bak,InstanceName,WSS_Content_DBName
http://webapp/sites/siteurl2,siteurl2.bak,InstanceName,WSS_Content__DBName2
http://iconnectstaging/sites/siteurl3,siteurl3.bak,InstanceName,WSS_Content__DBName3
http://iconnectstaging/sites/siteurl4,siteurl4.bak,InstanceName,WSS_Content__DBName4


 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.- Restore-Path\restorescript.ps1.

The script will stop after all the site collection restoration is finished.

Site Collections Backup Script

If we want to take backup of a single site collection through Powershell we use the following command:

Backup-SPSite "http://sitecollectionurl" -Path "PhysicalPath\backupname.bak"

This will take the backup of a single site collection. But if we have to take the backup of many site collections then running the above command every time will not be feasible & is a waste of time.
Now the way out in this situation is to prepare a Powershell script & run the script once & it will take the backup of all the site collections we want. This Powershell script reads the site URL & the backup name from a csv file. We will enter the url's & their respective backup file names in the csv file type & give the path of the csv file in the script. This script now reads the values one by one from each row & takes the backup.
When the rows are finished from the csv file then it stops the script. In this way we can take the backup of large number of site collections by running a single command.

The Powershell script is as follows:

$backupfolder= "Folder Path where the backup is to be stored"
$filePath = "Path of the .csv file"
$csv_info = Import-Csv $filePath
$count =$csv_info.count
#iterate Csv File
foreach ($line in $csv_info)
{
$siteurl = $line.SiteUrl.trim()
$backuppath = $backupfolder + "\" + $line.BackupPath.trim()
#cls
Backup-SPSite -Identity $siteurl -Path $backuppath -Force
#Write-Host $siteurl
Write-Host $backuppath
Write-Host "Sucess"
}  


Save the file with the .ps1 extension. e.g.- "backupscript.ps1".

Create a csv file & insert the entries as follows:

SiteUrl,BackupPath
http://siteurl,siteurl.bak
http://webapp/sites/siteurl2,siteurl2.bak
http://webapp/sites/siteurl3,siteurl3.bak
http://webapp/sites/siteurl4,siteurl4.bak


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.- Backup-Path\backupscript.ps1.

The script will stop after all the site collection backup is finished.


Thursday 2 August 2012

Play Video clips in browser saved in Document Library

We will run the video clips on the same page in the player which are saved in the Document Library.

Steps:

  Step 1: Create a document library named “Videos”.
  Step 2: Upload the video clips in the Videos document library.
 Step 3: Create a web part page named “Preview” & add the web part zones in two columns as shown below.

  Step 4: In the left column add the Videos Document library & in the second column add a CEWP.
  Step 5: In the CEWP insert the following code of the windows media player to play the related file.
The functions in the following codes reads the current video from the document library & runs it in the media player.

<div align="center" id="Player">
<object width="400" height="400" id="contentPlayer" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
<param name="url"/><param name="uiMode" value="full"/>
<param name="autoStart" value="-1"/>
<param name="stretchToFit" value="-1"/>
<param name="windowlessVideo" value="0"/><param name="enabled" value="-1"/>
<param name="enableContextMenu" value="-1"/>
<param name="fullScreen" value="0"/></object>&#160;</div>
<script type="text/javascript">
function getParameter(szName)
{
// Get value out of supplied parameter
var szUrl = window.location.search;
szUrl = szUrl.toLowerCase();
szName = szName.toLowerCase();
var szValue = "";
var nBegin = szUrl.indexOf(szName);
if (nBegin != -1)
{
szValue = szUrl.substring(nBegin + (szName.length + 1));
}
var nEnd = szValue.indexOf("&");
if (szValue != "" && nEnd != -1)
{
szValue = szValue.substring(0, nEnd);
}
return szValue;
}

function wmpCreate(url) {
var str = "";
var agt = navigator.userAgent.toLowerCase();
var is_ie = (agt.indexOf("msie") != -1);
if (is_ie) {
// create the WMP for IE
str = '<object id="contentPlayer" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="400" height="400">';
} else {
// create it for FF.
str = '<object id="contentPlayer" type="application/x-ms-wmp" data="'+url+'" width="400" height="400">';
}
str += '<param name="url" value=""/>';
str += '<param name="uiMode" value="full">';
str += '<param name="autoStart" value="-1" />';
str += '<param name="stretchToFit" value="-1" />';
str += '<param name="windowlessVideo" value="0" />';
str += '<param name="enabled" value="-1" />';
str += '<param name="enableContextMenu" value="-1" />';
str += '<param name="fullScreen" value="0" />';
str += '</object>';
return str;
}
function videoCreate() {
document.getElementById('Player').innerHTML = wmpCreate();
var wmp = document.getElementById('contentPlayer');
wmp.URL = getParameter("url");
wmp.controls.play();
}
_spBodyOnLoadFunctionNames.push("videoCreate"); </script>

The page will look as follows:



 
        Step 6: Open the Preview page in the SharePoint Designer.
        Step 7: Add a new column to the right of the document library as shown below.


      
        Step 8:  A new column to the right gets added as shown below.
      
                

             


       Step 9: Keep the cursor in the last column of the first entry i.e. Demo Video.
       Step 10: Click on the Hyperlink tab in Insert ribbon of the designer. The hyperlink popup will appear.

      Step 11: In the Text to display field type the name Preview & in the Address field type the following JavaScript:

javascript: {ddwrt:GenFireServerEvent(concat('__redirect={Preview.aspx?url=http://Demo/sites/sitename/Videos/',@FileLeafRef,'}'))}

       

 
Where:
 Preview.aspx = The name of the page
url= The path of the corresponding document library from where the video is to be played.
     
         Step 12:   Click OK. The Preview name will be displayed in the last column as shown below.

       

        Step 13: Save & close the file from SharePoint Designer & open the page in the browser. The page will appear as follows





 Step 14: The Preview link appears automatically in front of the item whenever a new video clip is uploaded in the document library.
 Step 15: When the user clicks on the Preview link the corresponding clips runs in the media player.