Thursday, May 17, 2012

SharePoint 2010 : Placing the SharePoint:PeopleEditor icons on right instead of bottom.

Goal

The SharePoint:PeopleEditor show the icons on the right side instead of bottom.

Sample Page : ASPX

<style type="text/css">
        .ppimg{border: 0px;vertical-align: middle !important;}
    </style>
    <br /><br /><br /><br />
    <table border="0" cellpadding="10" cellspacing="5" style="border:1px solid #808080">
        <tr>
            <td colspan="2">People picker on right instead of bottom</td>
        </tr>
        <tr>
            <td>
                Default
            </td>
            <td>
                <SharePoint:PeopleEditor AllowEmpty="false" ValidatorEnabled="true" ID="ppDefault"
                    runat="server" ShowCreateButtonInActiveDirectoryAccountCreationMode="false" SelectionSet="User,SPGroup"
                    Rows="1" Width="300px" />
            </td>
        </tr>
        <tr>
            <td nowrap="nowrap">
                Custom View
            </td>
            <td>
                <table>
                    <tr>
                        <td>
                            <SharePoint:PeopleEditor AllowEmpty="false" ValidatorEnabled="true" ID="ppCustom"
                                runat="server" ShowCreateButtonInActiveDirectoryAccountCreationMode="false" SelectionSet="User,SPGroup"
                                Rows="1" Width="300px" ShowButtons="false" />
                        </td>
                        <td valign="top">
                            <a id="aPPChekNames" runat="server" title="Check Name" href="javascript:">
                                <img src="/_layouts/images/checknames.png" alt="Check Names" class="ppimg" /></a>
                        </td>
                        <td valign="top">
                            <a id="aPPBrowse" runat="server" title="Browse" href="javascript:">
                                <img src="/_layouts/images/addressbook.gif" alt="Browse" class="ppimg" /></a>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>


Sample Page : Code

//Apply the Javascript to the Icons
aPPChekNames.Attributes.Add("onclick", "if(!ValidatePickerControl('" + ppCustom.ClientID + "')){ ShowValidationError(); return false;} var arg=getUplevel('" + ppCustom.ClientID + "'); var ctx='" + ppCustom.ClientID + "';EntityEditorSetWaitCursor(ctx);WebForm_DoCallback('" + ppCustom.UniqueID + "',arg,EntityEditorHandleCheckNameResult,ctx,EntityEditorHandleCheckNameError,true);return false;");
aPPBrowse.Attributes.Add("onclick", "javascript:__Dialog__" + ppCustom.ClientID + "(); return false;");


Result



I am not sure if many know about this or this is normal, but just wanted to share. Let me know if this helped.

SharePoint 2010 : Call server side function from XSL.

Goal

To use a server side function from a XSL used in a web part.

Solution

It is simple to use a server side function. Just need to make sure the dll should be deployed in GAC. In this example I created a class with name "ClassName", the project name is "SampleApplication". Deployed the dll in GAC. Modify the XSL head and add xmlns:helper="SampleApplication.ClassName" on the head. "helper" is like an tag which will point to the class.

XSL
<xsl:stylesheet 
  version="1.0" 
  exclude-result-prefixes="x d xsl msxsl cmswrt helper"
  xmlns:x="http://www.w3.org/2001/XMLSchema" 
  xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" 
  xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
  xmlns:cmswrt="http://schemas.microsoft.com/WebParts/v3/Publishing/runtime"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt"
  xmlns:helper="SampleApplication.ClassName">


SampleApplication.ClassName
#region System
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#endregion

namespace SampleApplication
{
    public class ClassName
    {
        #region Properties
        
        /// <summary>
        /// Name 
        /// </summary>
        private static string Name = "Maulik Dhorajia";
        
        /// <summary>
        /// Today Date
        /// </summary>
        private static string TodayDate = System.DateTime.Now.ToString();

        #endregion

        /// <summary>
        /// Gets the property
        /// </summary>
        /// <param name="propertyKey"></param>
        /// <returns></returns>
        public static string GetProperty(string propertyKey)
        {
            if (propertyKey == "Name")
            {
                return Name;
            }
            else if (propertyKey == "TodayDate")
            {
                return TodayDate;
            }
            else 
            {
                return "";
            }
        }
    }
}


Calling the function from XSL
<xsl:value-of select="helper:GetLabel('Name')"/>
<xsl:value-of select="helper:GetLabel('TodayDate')"/>


This should be all to show the stuff on the page. Let me know if this helped.

Wednesday, May 16, 2012

SharePoint 2010 : Insert custom icon in a custom group on Ribbon of Document Library.

Goal

Insert a custom icon(Email icon) on the SharePoint Document Library. The Icon should show in a Custom Group.

Challange

I thought getting the Icon on the top was easy(actually it was easy to place an icon on the top). But to place the icon in a Custom Group was a bit tough that it seems.

Follow the steps to achieve

  1. Open Visual Studio 2010, Create an empty SharePoint Application.
  2. Add a Module, Edit the Element.xml
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <CustomAction
          Id="EmailDocsCustom"
          Location="CommandUI.Ribbon"
          RegistrationType="ContentType"
          RegistrationId="0x01">
        <CommandUIExtension>
          <CommandUIDefinitions>
            <CommandUIDefinition Location="Ribbon.Documents.Groups._children">
              <Group
                  Id="EmailDocsCustomGroup"
                  Sequence="100"
                  Description="E-Mail Controls"
                  Title="E-Mail Controls"
                  Template="EmailDocsCustomGroupTemplate">
                <Controls Id="EmailDocsCustomGroupControl">
                  <Button
                      Id="EmailDocsCustomGroupControlButton"
                      Sequence="5"
                      Command="SimpleAlert"
                      Image32by32="/_layouts/1033/images/formatmap32x32.png" Image32by32Left="-448" Image32by32Top="-128"
                      ToolTipTitle="Email Documents"
                      ToolTipDescription="Select the documents which you want to email!"
                      LabelText="Email Selected Documents"
                      TemplateAlias="o1" />
                </Controls>
              </Group>
            </CommandUIDefinition>
            <CommandUIDefinition Location="Ribbon.Templates._children">
              <GroupTemplate Id="EmailDocsCustomGroupTemplate">
                <Layout Title="LargeLarge">
                  <OverflowSection Type="OneRow" TemplateAlias="o1" DisplayMode="Large"/>
                  <OverflowSection Type="OneRow" TemplateAlias="o2" DisplayMode="Large"/>
                </Layout>
              </GroupTemplate>
            </CommandUIDefinition>
            <CommandUIDefinition Location="Ribbon.Documents.Scaling._children">
              <MaxSize Id="Ribbon.Documents.Scaling.Custom.MaxSize" Sequence="15" GroupId="EmailDocsCustomGroup" Size="LargeLarge" />
            </CommandUIDefinition>
          </CommandUIDefinitions>
          <CommandUIHandlers>
            <CommandUIHandler Command="SimpleAlert" CommandAction="javascript:OpenEmailPage();" />
          </CommandUIHandlers>
        </CommandUIExtension>
      </CustomAction>
    
      <CustomAction
       Id="EmailRelatedScript"
       Location="ScriptLink"
       ScriptSrc ="/_layouts/WhatEvePathYouHave/EmailScript.js"/>
      
    </Elements>
    
  3. Place the EmailScript.js at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\WhatEvePathYouHave(You can map the folder and do this). With the help of this script you can do manipulations on the click of the icon placed on the top ribbon. Below is the script in EmailScript.js.
    //Get the current user and add the values found in the Email settings list
    function OpenEmailPage() {
    
        //Gets the current Context
        var _ctx = new SP.ClientContext.get_current();
        //Selected Items Variables
        var _itemIds = "";
        //Get current list id
        var _listId = SP.ListOperation.Selection.getSelectedList();
        var _listUrl = window.location.href;
        //get all selected list items
        var _selectedItems = SP.ListOperation.Selection.getSelectedItems(_ctx);
        //collect selected item ids
        for (var i = 0; i < _selectedItems.length; i++) {
            if (_itemIds == "")
            { _itemIds += _selectedItems[i].id; }
            else
            { _itemIds += "," + _selectedItems[i].id; }
        }
    
        alert('ListID = ' + _listId + "\nListUrl = " + _listUrl + "\nIDs=" + _itemIds);    
    }
  4. Before deploying the solution, check a document library. The ribbon on the top in the documents should like the below given image.
  5. Deploy the solution. Visit a Document Library, select docs and the new Icon should show up on the top right corner.
I am not very good with Ribbons and spent a lot of time to get just this portion. So thought if this can help many other who dont have time and have to get this quickly.

Friday, April 6, 2012

SharePoint 2010 : Use Resouce(resx) file in a Multilingual site.

Goal

Our site is created using variations in both English and Spanish. Create a Visual Web Part which can use the resource file(.resx) to show different texts for different language.

Steps to achieve goal

  • Create a SharePoint project with name "Sample".
  • Add a web part with name "SampleWebPart".
  • Add a "Mapped Folder" to "Resources". 2 files needs to be added.
    1. SampleWebPart.en-US.resx - English version resource file. Add some text to the resource.
    2. SampleWebPart.es-ES.resx - Spanish version resource file. Add some text to the resource.
  • At this point the project "Solution Explorer" will look like
  • For applying the resource, Open the Feature1 properties. And make the 2 changes shown in the below given image.
  • Use the HTML and C# Code below.
  • Once the above given steps are done, deploy the web part and They will display as below given image.


HTML - SampleWebPartUserControl.ascx

<h1><asp:Literal ID="ltrlTitle" runat="server" /></h1>
<hr />
<h3>
    <asp:Literal ID="ltrlDescription" runat="server" />
</h3>


C# - SampleWebPartUserControl.ascx.cs

#region System
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
#endregion

namespace Sample.SampleWebPart
{
    /// <summary>
    /// Simple example to use Resouce file with English/Spanish language.
    /// </summary>
    public partial class SampleWebPartUserControl : UserControl
    {
        #region Events

        /// <summary>
        /// Page Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            ltrlTitle.Text = LoadResource( ResourceName.Title );
            ltrlDescription.Text = LoadResource(ResourceName.Description);
        }

        #endregion

        #region Resource Reader

        /// <summary>
        /// Name for the Version to be considered.
        /// NOTE :- Use exactly same "Name" as used in Resource(resx) file.
        /// </summary>
        public enum ResourceName
        { 
            Title,
            Description
        }

        /// <summary>
        /// Gets the text on the basis of "Name" in Resource(resx).
        /// </summary>
        private string LoadResource(ResourceName _resName)
        {
            return Microsoft.SharePoint.Utilities.SPUtility.GetLocalizedString("$Resources:" + _resName.ToString(),
                "SampleWebPart"
            , (uint)System.Globalization.CultureInfo.CurrentUICulture.LCID); 
        }

        #endregion
    }
}


Happy Coding

Get all properties of Object using Javascript.

Goal

Assuming we are working on an a task. On a process we get an object. We don't know what exactly is there in the object or what properties the object is having. The javascript mentioned will print the list of properties of an object.

Solution

<script language="javascript" type="text/javascript">       
    var _jsonObject = {"Property1":1,"Property2":"Simple String","Property3":true};
    alert(_jsonObject);

    var _html = "";
    for (var key in _jsonObject) {
        _html = _html + key + " : " + _jsonObject[key] + "<br />" ;
    }
    document.writeln(_html);
</script>


Output