// Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = (SPSite)properties.Feature.Parent;

            using (SPWeb rootWeb = site.OpenWeb())
            {
                SPFeatureProperty types   = properties.Feature.Properties[Content.SPFileTypes];
                SPFeatureProperty sizes   = properties.Feature.Properties[Content.SPFileSizes];
                SPFeatureProperty actives = properties.Feature.Properties[Content.SPFileTypesActive];
                Helper.RemoveBagProperty(rootWeb, types.Name);
                Helper.RemoveBagProperty(rootWeb, sizes.Name);
                Helper.RemoveBagProperty(rootWeb, actives.Name);
            }
        }
        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}

        private static bool ApplyWebConfigMods(SPFeatureReceiverProperties properties)
        {
            bool bApplyChanges = true;
            SPFeaturePropertyCollection featureProps = properties.Feature.Properties;

            if (featureProps != null && featureProps.Count > 0)
            {
                SPFeatureProperty applyModsProp = null;
                try
                {
                    applyModsProp = featureProps["ApplyWebConfigModifications"];

                    if (applyModsProp != null)
                    {
                        bool.TryParse(applyModsProp.Value, out bApplyChanges);
                    }
                }
                catch (Exception)
                {
                    // we'll go ahead and make the web.config changes if the property is not present..
                }
            }
            return(bApplyChanges);
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            eventType = (PowerEventType)Enum.Parse(typeof(PowerEventType), Request["Type"]);

            web     = SPContext.Current.Web;
            list    = SPContext.Current.List;
            feature = web.Features[PowerEventReceiversConstants.FeatureId];

            switch (eventType)
            {
            case PowerEventType.Item:
                propNameScript      = PowerEventReceiversConstants.PowerItemEventReceiverPropNamePrefixScript + list.RootFolder.Url;
                propNameSequence    = PowerEventReceiversConstants.PowerListEventReceiverPropNamePrefixSequence + list.RootFolder.Url;
                propNameSynchronous = PowerEventReceiversConstants.PowerWebEventReceiverPropNamePrefixSynchronous + list.RootFolder.Url;
                eventDefinitionType = typeof(PowerItemEventReceiver).FullName;
                targetName          = list.Title;
                redirectUrl         = list.ParentWeb.Url + "/_layouts/listedit.aspx?List=" + HttpUtility.UrlEncode(list.ID.ToString());
                break;

            case PowerEventType.List:
                propNameScript      = PowerEventReceiversConstants.PowerListEventReceiverPropNamePrefixScript + list.RootFolder.Url;
                propNameSequence    = PowerEventReceiversConstants.PowerListEventReceiverPropNamePrefixSequence + list.RootFolder.Url;
                propNameSynchronous = PowerEventReceiversConstants.PowerWebEventReceiverPropNamePrefixSynchronous + list.RootFolder.Url;
                eventDefinitionType = typeof(PowerListEventReceiver).FullName;
                targetName          = list.Title;
                redirectUrl         = list.ParentWeb.Url + "/_layouts/listedit.aspx?List=" + HttpUtility.UrlEncode(list.ID.ToString());
                break;

            case PowerEventType.Web:
                propNameScript      = PowerEventReceiversConstants.PowerWebEventReceiverPropNamePrefixScript;
                propNameSequence    = PowerEventReceiversConstants.PowerWebEventReceiverPropNamePrefixScript + web.ID.ToString();
                propNameSynchronous = PowerEventReceiversConstants.PowerWebEventReceiverPropNamePrefixSynchronous + web.ID.ToString();
                eventDefinitionType = typeof(PowerWebEventReceiver).FullName;
                targetName          = web.Title;
                redirectUrl         = web.Url + "/_layouts/settings.aspx";
                break;

            default:
                throw new Exception("Unknown event type!");
            }

            scriptProperty      = feature.Properties[propNameScript];
            sequenceProperty    = feature.Properties[propNameSequence];
            synchronousProperty = feature.Properties[propNameSynchronous];

            if (web.CurrentUser.IsSiteAdmin == false)
            {
                throw new SecurityException();
            }

            if (IsPostBack == false)
            {
                if (scriptProperty != null)
                {
                    scriptBox.Text = scriptProperty.Value;
                }
                else
                {
                    switch (eventType)
                    {
                    case PowerEventType.Item:
                        scriptBox.Text = PowerEventReceiversConstants.PowerItemEventReceiverScriptTemplate;
                        break;

                    case PowerEventType.List:
                        scriptBox.Text = PowerEventReceiversConstants.PowerListEventReceiverScriptTemplate;
                        break;

                    case PowerEventType.Web:
                        scriptBox.Text = PowerEventReceiversConstants.PowerWebEventReceiverScriptTemplate;
                        break;

                    default:
                        throw new Exception("Unknown event type!");
                    }
                }

                if (sequenceProperty != null)
                {
                    sequenceNumber.Text = sequenceProperty.Value;
                }
                if (synchronousProperty != null)
                {
                    checkBoxSynchronous.Checked = Boolean.Parse(synchronousProperty.Value);
                }
            }

            saveButton.Click   += new EventHandler(saveButton_Click);
            cancelButton.Click += new EventHandler(cancelButton_Click);
        }
        void saveButton_Click(object sender, EventArgs e)
        {
            if (PowerEventReceiversHelper.IsUserInPowerEventReceiversGroup == false)
            {
                throw new SecurityException("Access Denied! Current user is not a farm administrator.");
            }

            if (scriptProperty == null)
            {
                scriptProperty = new SPFeatureProperty(propNameScript, scriptBox.Text);
                feature.Properties.Add(scriptProperty);
            }
            else
            {
                scriptProperty.Value = scriptBox.Text;
            }

            if (sequenceProperty == null)
            {
                sequenceProperty = new SPFeatureProperty(propNameSequence, sequenceNumber.Text);
                feature.Properties.Add(sequenceProperty);
            }
            else
            {
                sequenceProperty.Value = sequenceNumber.Text;
            }

            if (synchronousProperty == null)
            {
                synchronousProperty = new SPFeatureProperty(propNameSynchronous, checkBoxSynchronous.Checked.ToString());
                feature.Properties.Add(synchronousProperty);
            }
            else
            {
                synchronousProperty.Value = checkBoxSynchronous.Checked.ToString();
            }

            feature.Properties.Update();

            //clean power event receivers
            List <SPEventReceiverDefinition> receiversToDelete = new List <SPEventReceiverDefinition>();

            SPEventReceiverDefinitionCollection receivers = null;

            if (eventType == PowerEventType.Item || eventType == PowerEventType.List)
            {
                receivers = list.EventReceivers;
            }
            else
            {
                receivers = web.EventReceivers;
            }

            foreach (SPEventReceiverDefinition receiver in receivers)
            {
                if (receiver.Class == typeof(PowerItemEventReceiver).FullName)
                {
                    receiversToDelete.Add(receiver);
                }
            }

            foreach (SPEventReceiverDefinition receiver in receiversToDelete)
            {
                receiver.Delete();
            }

            if (!String.IsNullOrEmpty(sequenceNumber.Text))
            {
                Runspace runspace = null;
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(() => {
                        runspace = RunspaceFactory.CreateRunspace();
                        runspace.Open();
                        Pipeline pipe = runspace.CreatePipeline(scriptBox.Text);
                        pipe.Invoke();

                        pipe = runspace.CreatePipeline("get-childitem function:\\");
                        Collection <PSObject> results = pipe.Invoke();

                        string[] receiverTypes = Enum.GetNames(typeof(SPEventReceiverType));

                        foreach (PSObject obj in results)
                        {
                            FunctionInfo func = (FunctionInfo)obj.BaseObject;

                            if (receiverTypes.Contains(func.Name))
                            {
                                SPEventReceiverDefinition eventReceiverDef = null;
                                if (eventType == PowerEventType.Web)
                                {
                                    eventReceiverDef = web.EventReceivers.Add();
                                }
                                else
                                {
                                    eventReceiverDef = list.EventReceivers.Add();
                                }

                                eventReceiverDef.Assembly        = Assembly.GetExecutingAssembly().FullName;
                                eventReceiverDef.Class           = eventDefinitionType;
                                eventReceiverDef.Type            = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), func.Name);
                                eventReceiverDef.SequenceNumber  = int.Parse(sequenceNumber.Text);
                                eventReceiverDef.Synchronization = (Boolean.Parse(synchronousProperty.Value) || func.Name.Contains("ing"))
                                                                       ? SPEventReceiverSynchronization.Synchronous
                                                                       : SPEventReceiverSynchronization.Asynchronous;
                                eventReceiverDef.Update();
                            }
                        }
                    });
                    Response.Redirect(redirectUrl, true);
                }
                catch (Exception ex)
                {
                    literalError.Text  = String.Format("<div style='Color:red'><b>{0}</b></div>", ex.Message);
                    literalError.Text += String.Format("<div>{0}</div>", HttpUtility.HtmlEncode(ex.StackTrace));
                }
                finally
                {
                    if (runspace != null && runspace.RunspaceStateInfo.State != RunspaceState.Closed)
                    {
                        runspace.Close();
                        runspace = null;
                    }
                }
            }
        }
        /// <summary>
        /// Get the SPSite from the siteUrl property of the feature xml. If value is not present, use localhost as default.
        /// </summary>
        /// <param name="siteUrlProperty">SiteUrl property.</param>
        /// <returns></returns>
        private SPSite GetSite(SPFeatureProperty siteUrlProperty)
        {
            string url;
            if (null == siteUrlProperty || string.IsNullOrEmpty(siteUrlProperty.Value))
            {
                //Feature definition is missing 'SiteUrl' property, determining default webApp.
                url = GetDefaultWebAppUrl();
            }
            else
            {
                url = siteUrlProperty.Value;
            }

            SPSite site;
            try
            {
                site = new SPSite(url);
            }
            catch (FileNotFoundException e)
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
                    "Property 'SiteUrl' contains an invalid URL. Import failed with the following exception message: {0}", e.Message), "properties");
            }

            return site;
        }
        /// <summary>
        /// Returns the full path of the Model file.
        /// </summary>
        /// <param name="featureProperty">ModelFileName feature property.</param>
        /// <param name="featureFolder">Full path of the feature folder.</param>
        /// <returns>Full path of the Model File.</returns>
        private string GetModelFilePath(SPFeatureProperty featureProperty, string featureFolder)
        {
            this.modelFileName = featureProperty.Value;

            string modelFilePath = String.Empty;
            try
            {
                modelFilePath = Path.Combine(featureFolder, this.modelFileName);
            }
            catch (ArgumentException ex)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    "Feature property 'ModelFileName' has invalid value. Feature activation failed with the following message: {0}", ex.Message));
            }

            if (File.Exists(modelFilePath) == false)
            {
                throw new InvalidDataException(string.Format(CultureInfo.CurrentCulture,
                    "Model file '{0}' does not exist.", modelFilePath));
            }
            return modelFilePath;
        }
        /// <summary>
        /// Returns the AdministrationMetadataCatalog from the Url of the Site or WebApplication.
        /// </summary>
        /// <param name="siteUrlProperty">SiteUrl property used to get the SPSite.</param>
        /// <returns>AdministrationMetadataCatalog object.</returns>
        private void CreateAdministrationMetadataCatalog(SPFeatureProperty siteUrlProperty)
        {
            SPServiceContext context = null;
            SPSite site = null;

            try
            {
                site = GetSite(siteUrlProperty);
                context = SPServiceContext.GetContext(site);
            }
            finally
            {
                if (site != null)
                {
                    site.Dispose();
                }
            }

            var bdcService = parentFarm.Services.GetValue<BdcService>();
            if (bdcService == null)
            {
                throw new InvalidOperationException("Unable to contact BdcService.");
            }

            amc = bdcService.GetAdministrationMetadataCatalog(context);
            if (amc == null)
            {
                throw new InvalidOperationException("Unable to create AdministrationMetadataCatalog.");
            }
        }
        /// <summary>
        /// Returns the full paths of all the resource files.
        /// </summary>
        /// <param name="featureProperty">ResourceFileNames property.</param>
        /// <param name="featureFolder">Full path of the feature folder.</param>
        /// <returns>Full paths of the resoucre model files.</returns>
        private static string[] GetResourceModelFilesPaths(SPFeatureProperty featureProperty, string featureFolder)
        {
            //Resources are optional.
            if (featureProperty == null || string.IsNullOrEmpty(featureProperty.Value))
            {
                return null;
            }

            string[] resourceFilesPaths = ParseSemicolonDelimitedNames(featureProperty.Value);

            //Make it into full file name path.
            for (int i = 0; i < resourceFilesPaths.Length; i++)
            {
                try
                {
                    resourceFilesPaths[i] = Path.Combine(featureFolder, resourceFilesPaths[i]);
                }
                catch (ArgumentException ex)
                {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                        "Feature property 'ResourceFiles' has invalid value. Feature activation failed with the following message: {0}", ex.Message));
                }

                if (File.Exists(resourceFilesPaths[i]) == false)
                {
                    throw new InvalidDataException(string.Format(CultureInfo.CurrentCulture,
                        "Resource file {0} does not exist.", resourceFilesPaths[i]));
                }
            }
            return resourceFilesPaths;
        }
        /// <summary>
        /// Get the value of the IncrementalUpdate flag. If the IncrementalUpdate is not present then it will return false.
        /// </summary>
        /// <param name="incrementalUpdateProperty">SPFeatureProperty for the IncrementalUpdate property.</param>
        /// <returns>Value for the IncrementalUpdate property.</returns>
        private static bool GetIncrementalUpdate(SPFeatureProperty incrementalUpdateProperty)
        {
            // Optional, default=false
            if (null == incrementalUpdateProperty || String.IsNullOrEmpty(incrementalUpdateProperty.Value))
            {
                return false;
            }

            return Convert.ToBoolean(incrementalUpdateProperty.Value, CultureInfo.InvariantCulture);
        }
示例#10
0
        void saveButton_Click(object sender, EventArgs e)
        {
            if (SPFarm.Local.CurrentUserIsAdministrator() == false)
            {
                throw new SecurityException("Access Denied! Current user is not a farm administrator.");
            }

            if (scriptProperty == null)
            {
                scriptProperty = new SPFeatureProperty(propNameScript, scriptBox.Text);
                feature.Properties.Add(scriptProperty);
            }
            else
            {
                scriptProperty.Value = scriptBox.Text;
            }

            if (sequenceProperty == null)
            {
                sequenceProperty = new SPFeatureProperty(propNameSequence, sequenceNumber.Text);
                feature.Properties.Add(sequenceProperty);
            }
            else
            {
                sequenceProperty.Value = sequenceNumber.Text;
            }

            feature.Properties.Update();

            //clean power event receivers
            List <SPEventReceiverDefinition> receiversToDelete = new List <SPEventReceiverDefinition>();

            SPEventReceiverDefinitionCollection receivers = null;

            if (eventType == PowerEventType.Item || eventType == PowerEventType.List)
            {
                receivers = list.EventReceivers;
            }
            else
            {
                receivers = web.EventReceivers;
            }

            foreach (SPEventReceiverDefinition receiver in receivers)
            {
                if (receiver.Class == typeof(PowerItemEventReceiver).FullName)
                {
                    receiversToDelete.Add(receiver);
                }
            }

            foreach (SPEventReceiverDefinition receiver in receiversToDelete)
            {
                receiver.Delete();
            }

            if (!String.IsNullOrEmpty(sequenceNumber.Text))
            {
                Runspace runspace = null;
                try
                {
                    runspace = RunspaceFactory.CreateRunspace();
                    runspace.Open();
                    Pipeline pipe = runspace.CreatePipeline(scriptBox.Text);
                    pipe.Invoke();

                    pipe = runspace.CreatePipeline("get-childitem function:\\");
                    Collection <PSObject> results = pipe.Invoke();

                    string[] receiverTypes = Enum.GetNames(typeof(SPEventReceiverType));

                    foreach (PSObject obj in results)
                    {
                        FunctionInfo func = (FunctionInfo)obj.BaseObject;

                        if (receiverTypes.Contains(func.Name))
                        {
                            SPEventReceiverDefinition eventReceiverDef = null;
                            if (eventType == PowerEventType.Web)
                            {
                                eventReceiverDef = web.EventReceivers.Add();
                            }
                            else
                            {
                                eventReceiverDef = list.EventReceivers.Add();
                            }

                            eventReceiverDef.Assembly       = Assembly.GetExecutingAssembly().FullName;
                            eventReceiverDef.Class          = eventDefinitionType;
                            eventReceiverDef.Type           = (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), func.Name);
                            eventReceiverDef.SequenceNumber = int.Parse(sequenceNumber.Text);
                            eventReceiverDef.Update();
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (runspace != null && runspace.RunspaceStateInfo.State != RunspaceState.Closed)
                    {
                        runspace.Close();
                        runspace = null;
                    }
                }
            }

            Response.Redirect(redirectUrl, true);
        }