Execute code when activating a feature

Hi,
I need to execute some code, when my feature is activated. How cann I do that Is there an event handler for that How do I implement it

Reason is: I have several lists, that I need for this feature. Some of these lists have lookup fields on other lists. For these lookup lists I need their GUID to refer to them and I don't know them, when I write my CAML-files. So I need to create/update the lists, getting the GUID of them and inserting the lookup fields into the lists where needed.


Answer this question

Execute code when activating a feature

  • Andrei Kuzmenkov

    Dear Uwe82

    Have you successfully accomplished this If so can you post some sample code, i have the exact same scenario

    Kind regards


  • aaks

    Solution:

    Create a class inherited from SPFeatureReceiver. Implement the methods FeatureActivated, FeatureDeactivating, FeatureInstalled and FeatureUninstalling by overriding the base methods.

    Write your code into the FeatureActivated-method.

    Now change your feature.xml in the props ReceiverClass and ReceiverAssembly and set the corresponding values there for your assembly.

  • Stricken618

    No problem. You have to create a class, here's mine for example:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.SharePoint;
    using System.Diagnostics;
    using Microsoft.Office.Workflow;
    namespace Urlaubsantrag.Lists
    {
    public class FeatureEventHandler : SPFeatureReceiver
    {
    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
    SPSite site = properties.Feature.Parent as SPSite;
    SPWeb web = site.OpenWeb();
    SPList urlaubsanspruchList = web.Lists["Urlaubsanspruch"];
    SPList feiertagsgruppeList = web.Lists["Feiertagsgruppe"];
    if (!urlaubsanspruchList.Fields.ContainsField("Feiertagsgruppe"))
    urlaubsanspruchList.Fields.AddLookup(
    "Feiertagsgruppe", feiertagsgruppeList.ID, false);
    }
    public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
    {
    //throw new Exception("The method or operation is not implemented.");
    }
    public override void FeatureInstalled(SPFeatureReceiverProperties properties)
    {
    //throw new Exception("The method or operation is not implemented.");
    }
    public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
    {
    //throw new Exception("The method or operation is not implemented.");
    }
    }
    }

    This sample adds a lookup field to the list Urlaubsanspruch. In the feature definition, you need to set the following attributes according to your own assembly:

    ReceiverAssembly="Urlaubsantrag.Lists, Version=1.0.0.0, Culture=neutral, PublicKeyToken=527e592493732533"
    ReceiverClass="Urlaubsantrag.Lists.FeatureEventHandler"

    That's all ;)


  • Execute code when activating a feature