Search This Blog

Thursday, 28 June 2012

SharePoint 2010 Ribbon Button

Add New Custom Button on ListItem Ribbon

1. Display an alert message in the button action using javascript

Code Snippet:

    <CustomAction
      Id="CustomRibbonButton"
      RegistrationId="100"
      RegistrationType="List"
      Location="CommandUI.Ribbon"
      Sequence="10"
      Title="CustomRibbonButton">
        <CommandUIExtension>
            <CommandUIDefinitions>
                <CommandUIDefinition Location="Ribbon.ListItem.Manage.Controls._children">
                    <Button
                        Id="Ribbon.ListItem"
                        Alt="CustomRibbon"
                        Sequence="10"
                        Command="CustomButton"
                        LabelText ="Custom Button"
                        Image16by16="/_layouts/images/actionseditpage16.gif"
                        Image32by32="/_layouts/images/actionssettings.gif"
                        TemplateAlias="o1" />
                </CommandUIDefinition>
            </CommandUIDefinitions>
            <CommandUIHandlers>
                <CommandUIHandler Command="CustomButton"
                                  CommandAction="javascript: alert('My Command!');" />
            </CommandUIHandlers>
        </CommandUIExtension>
    </CustomAction>

Snapshot













2. Enable custom ribbon button after select an item

Change the below code
<CommandUIHandlers>
                <CommandUIHandler Command="CustomButton"
                                  EnabledScript="javascript: var EnableDisable = function() {  this.clientContext = SP.ClientContext.get_current();  this.selectedItems = SP.ListOperation.Selection.getSelectedItems(this.clientContext);  var ci = CountDictionary(selectedItems);  return (ci > 0);  };  EnableDisable();"
                                  CommandAction="javascript: alert('My Command!');" />
</CommandUIHandlers>


Snapshot


















3. Calling an Application page in Custom Button Action

Code snippet:

    <CustomAction
        Id="SkynetCustomRibbonButton"
        RegistrationId="100"
        RegistrationType="List"
        Location="CommandUI.Ribbon"
        Sequence="5"
        Title="CustomRibbon">

        <CommandUIExtension>
            <CommandUIDefinitions>
                <CommandUIDefinition Location="Ribbon.ListItem.Manage.Controls._children">
                    <Button
                        Id="Ribbon.ListItem"
                        Alt="CustomRibbon"
                        Sequence="5"
                        Command="Skynet_Test_Button"
                        Image16by16="/_layouts/images/actionseditpage16.gif"
                        Image32by32="/_layouts/images/actionssettings.gif"
                        LabelText ="Custom Button"
                        TemplateAlias="o1" />
                </CommandUIDefinition>

            </CommandUIDefinitions>

            <CommandUIHandlers>
                <CommandUIHandler
                Command="Skynet_Test_Button"
                CommandAction="javascript: function resultCallback(result, value) 
  {
  SP.UI.Notify.addNotification('Success!'); 
  SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK); 
  }
  var ctx = SP.ClientContext.get_current();
  var items = SP.ListOperation.Selection.getSelectedItems(ctx);
  var myItems = '';
  var i;  
  for (i in items)
  {
  myItems += '|' + items[i].id;
  }  
  if(myItems != '') 
  { 
  var options =
  { 
  url: '/_layouts/CustomRibbonButton/sampleApplnPage.aspx?Items=' + myItems , 
  tite: 'My Page', 
  allowMaximize: false, 
  showClose: true,
  width: 500, 
  height: 160, 
  dialogReturnValueCallback: resultCallback
  };  
  SP.UI.ModalDialog.showModalDialog(options);
  }" />

            </CommandUIHandlers>
        </CommandUIExtension>
    </CustomAction>

Snapshot













4. Show custom button based on the rights

Scenario: Here my scenario is, the custom button should show only users who has full control.

Code Snippet:

do the below changes, add rights in Custom Action as follows

<CustomAction Rights="ManageWeb"
        Id="SkynetCustomRibbonButton"
        RegistrationId="100"
        RegistrationType="List"
        Location="CommandUI.Ribbon"
        Sequence="5"
        Title="CustomRibbon">

Snapshot

User with out Full Control














Full Control User
















Source download links

Link 1

Link 2

Link 3

Link 4


Friday, 22 June 2012

Export All WSP's from Central Administration using Powershell


$dirName = "c:\Exported Solutions\"
if (!(Test-Path -path $dirName))
{
New-Item $dirName -type directory
}
Write-Host Exporting solutions to $dirName
foreach ($solution in Get-SPSolution)
{
    $id = $Solution.SolutionID
    $title = $Solution.Name
    $filename = $Solution.SolutionFile.Name
    Write-Host "Exporting ‘$title’ to …\$filename" -nonewline
    try {
        $solution.SolutionFile.SaveAs("$dirName\$filename")
        Write-Host " – done" -foreground green
    }
    catch
    {
        Write-Host " – error : $_" -foreground red
    }
}

Result:














You can download the script here

Get a specific wsp from SharePoint Central Administration

Code Snippet :

$dirName = "c:\Exported Solutions\"
if (!(Test-Path -path $dirName))
{
New-Item $dirName -type directory
}
Write-Host Exporting solution to $dirName
$farm = Get-SPFarm
$file = $farm.Solutions.Item("hfreports.wsp").SolutionFile
$file.SaveAs($dirName + "hfreports.wsp ")


You can download the script here

Thursday, 14 June 2012

Show Quick Launch on SharePoint 2010 Webpart Page


When you create a webpart page on SharePoint 2010, the quick launch will vanish.

To display quick launch we have to Open the Page in SharePoint Designer and do the following changes

Find the below lines
<asp:Content ContentPlaceHolderId="PlaceHolderPageImage" runat="server"></asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderLeftNavBar" runat="server"></asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderNavSpacer" runat="server"></asp:Content>
and comment or Remove it

you also need to comment or delete the following style:

< style type="text/css">
body #s4-leftpanel {
display:none;
}
.s4-ca {
margin-left:0px;
}
</style>

Now the quick launch will display on the web part page.

More References


Create webpart page in SharePoint 2010 through PowerShell(Publishing Page)



Recently I had a situation to create multiple webpart page. It’s not suitable to do this in OOB(doing as default).  So I have gone with PowerShell script.

After a minimal number of tries, I achieved this, I posted the script below.


if((Get-PSSnapin "Microsoft.SharePoint.PowerShell" ) -eq $null)
{
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Publishing")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Publishing.PublishingWeb")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Publishing")
[System.Reflection.Assembly]::LoadWithPartialName("System")


$site = new-object Microsoft.SharePoint.SPSite("http://chesgh201tw1v:2020")
$web = $site.OpenWeb();

$pubWeb =[Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
# Create blank web part page
$pl = $pubWeb.GetAvailablePageLayouts() | Where { $_.Name -eq "BlankWebPartPage.aspx" } #you may change "BlankWebPartPage.aspx" to your custom page layout file name
$newPage = $pubWeb.AddPublishingPage("myfile.aspx", $pl) #filename need end with .aspx extension
$newPage.Update()
# Check-in and publish page
$newPage.CheckIn("")
$newPage.ListItem.File.Publish("")
$web.Dispose()

you can download the script here

Note: SharePoint Publishing feature should be in active state to run the above script successfully. Here i posted single peace of my code(Create single page).

Tuesday, 12 June 2012

Javascript PreSaveAction() in SharePoint 2010


You Can Use PreSaveAction function to execute any JavaScript Code in New or Edit Forms for any SharePoint List before Saving the item.

It Validate form without PostBack.

Syntax: 
PreSaveAction()
{
//Add Your JavaScript Code Here Then Return True Or False
return false; // Cancel the item save process
return true; // OK to proceed with the save item
}

“PreSaveAction” function is JavaScript function which allow programmer to write code with in this function which will execute just before saving records. Programmers can use this function in NewForm.aspx or EditForm.aspx. 

Code Example:

<script src="/Shared%20Documents/prototype.js" type="text/javascript"></script>
<script src="/Shared%20Documents/SPUtility.js" type="text/javascript"></script>
<script type="text/javascript">
function PreSaveAction()    {
alert(SPUtility.GetSPField('Title').GetValue());
if(SPUtility.GetSPField('Title').GetValue() != null)
{
     alert('Validation passed, let SharePoint continue');
     return true;
}
else
{
alert('Validation failed, let SharePoint not continue');
     return false;

}
} </script>

To install, you’d simply place the JavaScript above into a Content Editor Web Part on your NewForm.aspx or EditForm.aspx

References:



Working with SPUtility.js in SharePoint 2010


Let me discuss the use of SPUtility.js in SharePoint 2010 with simple examples.

Populate value for the Title field automatically 

Write the following script

Approach 1:
<script src="/Shared%20Documents/prototype.js" type="text/javascript"></script>
<script src="/Shared%20Documents/SPUtility.js" type="text/javascript"></script>
<script type="text/javascript">
Event.observe(window,'load',function(){
    SPUtility.GetSPField('Title').SetValue('Hello world!');
}); </script>

Approach 2:
<script src="/Shared%20Documents/prototype.js" type="text/javascript"></script>
<script src="/Shared%20Documents/SPUtility.js" type="text/javascript"></script>
<script type="text/javascript">
function MyCustomExecuteFunction()
{
     SPUtility.GetSPField('Title').SetValue('Hello world1!');
}
_spBodyOnLoadFunctionNames.push("MyCustomExecuteFunction");</script>

To install, you’d simply place the JavaScript above into a Content Editor Web Part on your NewForm.aspx or EditForm.aspx. Take a look at the SPUtility.js Installation page for detailed instructions.

Get the Title field value in EditForm.aspx

Approach 1:
<script src="/Shared%20Documents/prototype.js" type="text/javascript"></script>
<script src="/Shared%20Documents/SPUtility.js" type="text/javascript"></script>
<script type="text/javascript">
Event.observe(window,'load',function(){
    alert(SPUtility.GetSPField('Title').GetValue());
}); </script>

You can use approach 2 also to get the value.

Reference Links:
Installation documentation:
 
Download scripts

SPUtility.js details



Adding Custom Spelling in SharePoint 2010


While entering the data in SharePoint List/Libraries we have the option to do the spell checking. The Spell checking feature can be activated/deactivated via a Farm Scoped feature.

This Spell check functionality checks any spelling mistake in the content which we are entering into the SharePoint List/Libraries. Suppose if we want to add some new words which should not be considered as spelling mistakes. We can do this by adding our custom dictionary. Let me show this using a example:

1. I will use Task List and in description I will put SharePoint in different ways. The only acceptable way is SharePoint. So my other Sharepoint and SharepoinT will be shown as errors.



 








2. Now I will create a custom dictionary. To do this create a new Document Library, "Spelling" at the root of the site.
3. Create a text file, "Custom Dictionary.txt" and add all the words that should not be recognized as spelling errors in the text file, one word per line.
4. Upload the text file to the newly created Library.











5. Now I will again use these two added words in my task description and spell check will not show any error:






















6. Only one "Custom Dictionary" Document Library is possible for each site collection and the names of the Library and text file need to be exactly same as mentioned. Also the Library must be located at the root of the Portal.

Solved issues:

Changes to the custom dictionary.txt file are not taking effect

You might face a peculiar problem when you implement the custom dictionary functionality in SharePoint. This functionality is documented under "Plan dictionary customizations" section of article http://technet.microsoft.com/en-us/library/cc263367.aspx

All the words in the file uploaded the first time are recognized by the Spell checker. But if you make any modifications to the ‘custom dictionary.txt’ file and upload it again, the spell checker might not pick it up.

To work around this issue, you may clear the system temp location - %systemroot%\temp location and try the spell checker again. You may also search for this custom dictionary file saved in the temp location and delete that single file (name is in the format GUID.txt)

Best wishes,
Belleyedan. 

Monday, 11 June 2012

SharePoint 2010 Managed Paths


Here I am going to discuss “what is a Managed Path” and difference between Explicit Inclusion versus Wildcard Inclusion. 

Why use Managed Paths?
If you have a medium-scale or larger implementation, give serious consideration to extending the default set of managed paths. A managed path is defined as the path in the URI that is managed by SharePoint products. As an example, sites is the managed path in http://<site>/sites/madison. Managed paths cannot be limited for use by specific security groups, nor can they be targeted directly with audiences. They are simply a way to organize a large quantity of site collections.
When using managed paths, you can have two site collections with same name [i.e., 'Meetings']. For Example, http://<site>HR/Meetings and http://<site>Sales/Meetings [have the same site collection name of 'Meetings'].
When adding a new path, you have the option either to include only that path (explicit inclusion) or to specify that path and all subordinate paths (wildcard inclusion). If the path http:/<site>/sites was specified as an explicit inclusion, content could still be served from the WFE file system at http://<site>/sites/path. When creating an explicit inclusion managed path, you can then create a single site collection in the root of that path. If http://<site>/sites was specified as a wildcard inclusion, multiple named site collections could be created under that path.
If that didn't clear things up, then let's take it one step further. 


Explicit Inclusion versus Wildcard Inclusion 

Explicit Inclusion
Includes only the specific path you set. Use explicit inclusions, for example, if you want Windows SharePoint Services to manage a specific path, such as /portal, but not any possible sites below it, such as /portal/webapp. 

Wildcard Inclusion
Includes any sites below the path you set, so you don't have to add them individually. This is the type of inclusion to use for Self-Service Site Creation, when you want users to be able to create top-level Web sites underneath a specific path, such as /sites. 

Example
For example, using an explicit inclusion, you are saying that http://<site>/team/ is a site collection without the possibility of any site collections below it; however, wildcard exclusion allows you to create site collections under http://<site>/team/
 
Conclusion
Having a solid understanding of Managed Paths is a definite must for any SharePoint administrator. Though, I'm sure I'll have to refer to my own blog post the next time I need to configure Managed Paths. 


Few Key points
  • Managed Paths allow SharePoint to determine what portion of a given URL corresponds to the "site collection URL".
  • Managed Paths can be defined per web application (and cannot be defined for host header site collections)
  • Managed Paths can be "Explicit" or "Wildcard"
  • Explicit Managed Paths allow a single spsite to be created at exactly the given url
  • Wildcard Manage Paths allow unlimited spsites to be created under the given url – no spsite can be created at exactly that URL.
  • Limit your managed paths to <20 per web application 

Enjoy!