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.