Home > ASP.NET, C#, MOSS 2007, SharePoint > SharePoint 2010: Custom action that executes custom code

SharePoint 2010: Custom action that executes custom code


In 2007 it was possible to create a custom action and then link it to some code.

You did this by first declaring your custom action in an elements.xml file (which you would then deploy as part of a feature):

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
    Id="MyCustomAction"
    RegistrationType="List"
    GroupId="ActionsMenu"
    Location="Microsoft.SharePoint.StandardMenu"
    Sequence="1000"
    ControlAssembly="[Fully qualified assembly name]"
    ControlClass="MyNamespace.MyCustomAction">
  </CustomAction>
</Elements>

In the ControlAssembly and ControlClass attributes you specified your custom assembly and your custom class (a WebControl) that contained your custom code.

Then you created your custom WebControl:

public class MyCustomAction : WebControl 
{
    protected override void CreateChildControls() 
    {
        // Do some stuff
    }
}

Using this way we were able able to execute some custom code when someone clicked our custom action.

However, it seems that we cannot use this method in SharePoint 2010 although there are a few workarounds to achieve the same result. Below I will show you a way I used.

To start off with, I created an elements.xml file with the following declaration:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Id="ContentTypeRibbonCustomization" RegistrationId="10005" RegistrationType="List" Location="CommandUI.Ribbon.ListView" Sequence="95" Title="Run Custom Code">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.List.Settings.Controls._children">
          <Button Id="ContentTypeTest.Button" Image16by16="/_layouts/images/LSTPEND.gif" Image32by32="/_layouts/images/centraladmin_configurationwizards_farmconfiguration_32x32.png" Command="ContentTypeCommand" CommandType="General" Description="Runs some custom Code" TemplateAlias="o2" Sequence="95" LabelText="Perform My Action"/>
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler Command="ContentTypeCommand" CommandAction="/MyWeb/_layouts/CustomPages/MyCustomApplicationPage.aspx" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
</Elements>

This specifies that my Custom Action will appear on my custom list with TemplateType of 10005 (specified in the RegistrationId attribute) in the list view section.

I then used a Feature to depoy my Custom Action.

All my Custom Action does is to send the user to a custom page that is located in the Layouts folder:

/MyWeb/_layouts/CustomPages/MyCustomApplicationPage.aspx

I then created my custom aspx page. Below is the mark up for the page:

<%@ Assembly Name="MyCustomAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e246903334b3e97b" %>
<%@ Page Language="C#" AutoEventWireup="true" Inherits="MyCustomNamespace.MyCustomControl"
    Debug="true" %>

And finally, below is the code behind for the aspx page:

namespace MyCustomNamespace
{
    public class MyCustomControl: UserControl
    {    
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            // run some custom code
            // then redirect the user back to the original page
        }
    }
}

Using this way I was able to link some custom code that would execute in response to someone clicking my custom action.

For everything you need to know about customising the SharePoin Ribbon please go here to Chris O’Brien’s blog post.

After spending a lot of time investigating how to customise the Ribbon to meet the requirements I had I can safely say this is by far the best and most comprehensive blog post I found on the net.

As I said earlier there are other ways you can use to achieve the same objective. You can easily link a custom action to execute some javascript function. I guess one option would be to link it to a javascript function that then invoked some server side code. I havent tried this myself so I cannot say for sure if this approach would work.

If you had a similar issue to the one I had above, I would be interested in hearing what approach you used to resolve it (if different to the approach I used).

Advertisements
  1. Mathieu Diakité
    October 25, 2011 at 4:28 pm

    Hi, your first code works fine on SP2010, you just need to add your WebControls to the safecontrols section of your web.config.

    It can be done by editing your project manifest template, for example:

    <Assembly Location=".dll” DeploymentTarget=”GlobalAssemblyCache” >

    <SafeControl Assembly="$SharePoint.Project.AssemblyFullName$" Namespace="” TypeName=”*” Safe=”True” />

  2. Mathieu Diakité
    October 25, 2011 at 4:36 pm

    Should look Better..

    <Solution xmlns="http://schemas.microsoft.com/sharepoint/">
      <Assemblies>
        <Assembly Location="OddoAM.WebSite.dll" DeploymentTarget="GlobalAssemblyCache" >
           <SafeControls>
              <SafeControl Assembly="$SharePoint.Project.AssemblyFullName$" Namespace="OddoAM.WebSite.WebControls" TypeName="*" Safe="True" />
              <SafeControl Assembly="$SharePoint.Project.AssemblyFullName$" Namespace="OddoAM.WebSite.WebParts" TypeName="*" Safe="True" />
           </SafeControls>
        </Assembly>
      </Assemblies>
    </Solution>
    
  3. May 5, 2012 at 12:40 pm

    Hi Mathieu & Jalil,

    Really Thanks to provide this blog and clear understanding.

    But now I have one small query… as Jalil says I have added one custom button on view item page and on the click on that i just want to fire one custom function but don’t want to open any other page or such like popup. just want to fire one custom function.

    Now as Mathieu said in this reply this may possible through above (First Passage) Code. But can mathieu would you please tell me will it open the new aspx page or just execute directly ? and if it execute directly then should i create new class file under that vs2010 project and compile that ? don’t know the process to achieve that if you can help.

  4. October 22, 2012 at 2:42 pm

    Is it possible to create a custom action for a document library so that when you press the “New Document” button some custom code is executed before the default actions of the button? I have a detailed question posted http://social.technet.microsoft.com/Forums/en-ZA/sharepoint2010programming/thread/1ae408d6-d0d3-487f-87a9-e7874a158570 on the MSDN SharePoint forum.

    I have a OneNote document library that needs to fire off some custom code when a user clicks the “New Document” button. Data is being pulled into a central, dynamic page where this OneNote library sits. If a user wants to add a document then a new site is dynamically created (if one does not already exist) and the user is re-directed to that sub-site. The OneNote file then opens on that sub-site so the user can save the file to that particular library. This way all the dynamic sites and programmatic sites are kept separate. The dynamic sites have no library files. The button is really a call-to-action button for spinning up a real sub-site.

    Thanks

    • jasear
      October 22, 2012 at 10:00 pm

      Hi,

      I am not sure whether it is possible to change the default behaviour of the ‘New Document’ button.

      I read your detailed post where you mentioned you would like to run this custom code before or during the new document is saved.

      Have you considered attaching an ItemAdding event handler to this document library so that when the document is being saved you can run your custom code in there?

  5. January 23, 2013 at 2:24 pm

    Great post! Was hoping you could help me with something. I’m getting an error that it can’t find the assembly MyCustomAssembly. Do I need to build a dll and put it somewhere? Thanks!

    • jasear
      January 23, 2013 at 3:59 pm

      Hi Justin,

      MyCustomAssembly was just an example, you need to replace this with your own dll that contains the Class that in turn contains the method you want to execute.

  6. January 23, 2013 at 5:43 pm

    Thanks for the quick response!! The code code behind of the aspx page needs to reference a dll that has the actual code you want to execute? Is that correct? Also, where does the dll go on the SharePoint server? In the GAC? Thanks for your help!

    • fabgunner
      January 26, 2013 at 2:55 pm

      Hi Justin,

      You can deploy your custom dll either in the bin folder of your Web Application or the GAC.

  7. September 30, 2013 at 10:03 pm

    Simply wish to say your article is as amazing.
    The clarity to your post is just nice and i can assume you’re an expert on this subject.
    Fine with your permission allow me to take hold of your RSS feed to stay up to date with drawing close post.
    Thanks a million and please keep up the rewarding
    work.

  8. April 4, 2014 at 11:29 am

    Hi,

    Great post!
    Although I am still having problems to execute custom code from my custom action. I keep getting the error “Unterminated string constant”.
    Any help would be appreciated.

  9. September 12, 2014 at 11:45 pm

    Excellent items from you, man. I have take note your stuff
    prior to and you are just too fantastic. I really like what you
    have acquired right here, certainly like what you’re saying
    and the way in which wherein you say it. You make it
    entertaining and you still care for to stay it smart. I can’t wait to read far more from you.
    That is actually a terrific website.

  10. September 20, 2014 at 11:55 pm

    This piece of writing is truly a good one it helps new web viewers, who are wishing for blogging.

  11. David Stellini
    September 17, 2015 at 1:19 pm

    Thank you!

  12. February 16, 2017 at 12:03 am

    VMware Certified Advanced Professional 6 (Desktop and Mobility Deployment) – The industry-recognized VCAP6-DTM Deploy certification validates that you know how to deploy and optimize VMware Horizon 6 (with View) environments. It demonstrates that you have the knowledge and abilities required to leverage best practices to provide a scalable and dependable Business Mobility platform for your organization. Some of the subjects include: Configuring and managing Horizon View components, configuring cloud pod archituecture, configuring Group Policy settings related to Horizon View, Configuring and optimizing desktop images for Horizon View & Mirage, Configuring and managing App Volumes AppStacks, Configuring desktop pools, Configuring and deploying ThinApp packaged applications, Configuring VMWare Identity Manager, etc.Sebastian’s take on the VCAP6 examination: “In my own thoughts and opinions VCAP6 examination is way better experience as compared with VCAP5, the newest examination appears just like VMware HOL. The screen is effortless, questions are prepared on the right area of the display, and can be concealed to the side or even restored when necessary. My bits of advice to the questions window: if you wish to make it floating, you must know how to restore it back. I ended up moving it all around for the reason that I fail to remember how to restore it back. The two arrows that appeared to be buttons on top were created to dock the window to right of left. Fonts can be resized, which from my opinion was considerably better than scrolling down and up the question. The response speed of the whole interface was so much faster compared to VCAP5.5, and there was no lagging period experienced when switching from window to window. Something to keep in mind: BACKSPACE key is not working! I believe it is beneficial because you don’t reload your exam window in error, but, it can be frustrating at times whenever you type something mistakenly and you have to select and press Del to remove. The Desktop and shortcuts were organized well, and required programs like browser or Mirage console could be launched. There is a superb user interface for Remote Desktop Manager and you’ll discover all required RDP connection to servers or desktops without having to type account information. The web browser had all the links in the Favorite Bar. Right at that moment I’m penning this, there’s no extra Thirty minute extension for Non-Native English speaker at No-Native English country, which is a bummer. There are thirty-nine question to fill out within the three hours period, which can be actually really hard for non-native English speakers just like me. Quite a few questions take time to complete, therefore it is preferable to skip the questions that you cannot respond to, and finish those you are able to. At the end of the thirty-nine questions, you are able to get back on the uncompleted questions should you still have time. Never squander a long time on one single question! The examination blue print is found on my blog at Szumigalski.com. It is well organized and following it for the examination preparation can really help a lot. Surely, the most beneficial is if you could have plenty of hands on experience! I’m actually very happy with the examination experience, even though I passed this time by tiny margin, but I understand what I missed for the exam, study from the blunders and practice harder to acquaint myself with the environment. This certificates is sure to open up your job prospects!”

  1. November 21, 2010 at 10:02 pm
  2. November 27, 2010 at 12:37 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: