I need to add a custom menu action to a custom content type programmatically in c#. This is because I will not know the URL I need to link to beforehand. The URL to link to will be pulled from configuration when the feature is activated. I have tried the following:
Added the CustomAction in my Element.xml file as:
<CustomAction
Id="MyID"
RegistrationType="ContentType"
RegistrationId="0x010100ef19b15f43e64355b39431399657766e"
Location="EditControlBlock"
Sequence="1000"
Title="My Menu Item">
<UrlAction Url="" />
</CustomAction>
In my feature receiver FeatureActivated method, I have:
SPElementDefinitionCollection eleCollection =
properties.Feature.Definition.GetElementDefinitions(
new System.Globalization.CultureInfo(1));
foreach (SPElementDefinition ele in eleCollection)
{
if (ele.Id == "MyID")
{
System.Xml.XmlNode node = ele.XmlDefinition.FirstChild;
node.Attributes[0].Value = "MY URL";
ele.FeatureDefinition.Update(true);
}
}
I would expect this code to update the UrlAction Url with "MY URL" but it does not. If I hard code a URL in the XML it works but I must be able to do it programmatically.
You can use the SPUserCustomActionCollection on the SPWeb object:
using (SPSite site = new SPSite("http://moss.dev.com"))
using (SPWeb web = site.OpenWeb())
{
SPContentType contentType = web.ContentTypes["Curriculum Vitae"];
SPUserCustomAction action = web.UserCustomActions.Add();
action.RegistrationType = SPUserCustomActionRegistrationType.ContentType;
action.RegistrationId = contentType.Id.ToString();
action.Location = "EditControlBlock";
action.Sequence = 450;
action.Title = "Test";
action.Rights = SPBasePermissions.EditListItems;
action.Url = "http://www.google.com";
action.Update();
}
This way, you can set the URL to whatever you want. If you are updating an existing custom action, you can iterate through the collection and update the one you are looking for. Updating the element XML definition after you've installed the custom action doesn't do anything.