Exemplo n.º 1
0
 public Status CheckFeature(SPFeature feature)
 {
     Status status = new Status();
     try
     {
         status.FeatureId = feature.DefinitionId;
     }
     catch
     {
         status.Faulty = true;
     }
     try
     {
         status.CompatibilityLevel = FeatureManager.GetFeatureCompatibilityLevel(feature.Definition);
     }
     catch
     {
         status.Faulty = true;
     }
     try
     {
         // a feature activated somewhere with no manifest file available causes
         // an error when asking for the DisplayName
         // If this happens, we found a faulty feature
         status.DisplayName = feature.Definition.DisplayName;
     }
     catch
     {
         status.Faulty = true;
     }
     return status;
 }
        /// <summary>
        /// Creates a new child lifetime scope that is as nested as possible,
        /// depending on the scope of the specified feature.
        /// In a SPSite or SPWeb-scoped feature context, will return a web-specific
        /// lifetime scope (allowing you to inject InstancePerSite and InstancePerWeb
        /// objects).
        /// In a SPFarm or SPWebApplication feature context, will return a child
        /// container of the root application container (preventing you from injecting
        /// InstancePerSite, InstancePerWeb or InstancePerRequest objects).
        /// Please dispose this lifetime scope when done (E.G. call this method from
        /// a using block).
        /// Prefer usage of this method versus resolving indididual dependencies from the 
        /// ISharePointServiceLocator.Current property.
        /// </summary>
        /// <param name="feature">The current feature that is requesting a child lifetime scope</param>
        /// <returns>A new child lifetime scope which should be disposed by the caller.</returns>
        public ILifetimeScope BeginFeatureLifetimeScope(SPFeature feature)
        {
            ILifetimeScope newChildScopeAsNestedAsPossible = null;

            SPSite currentFeatureSite = feature.Parent as SPSite;
            SPWeb currentFeatureWeb = null;

            if (currentFeatureSite == null)
            {
                // this is a Web-scoped feature, not a Site-scoped one
                currentFeatureWeb = feature.Parent as SPWeb;
            }
            else
            {
                // this is a Site-scope feature, use the RootWeb as current
                currentFeatureWeb = currentFeatureSite.RootWeb;
            }

            if (currentFeatureWeb == null)
            {
                // Can't use an AddOnProvidedServiceLocator this way outside a SPSite context (e.g. no SPFarm or SPWebApp scoped feature will work)
                throw new InvalidOperationException("The AddOnProvidedServiceLocator can only work withing a SPSite's context: i.e. only from SPSite or SPWeb-scoped feature event receivers.");
            }
            else
            {
                this.EnsureServiceLocatorAccessorForCurrentSiteContext(currentFeatureWeb.Site);

                // We are dealing with a SPSite or SPWeb-scoped feature.
                // Always return a web scope (even for Site-scoped features - as being in a site-scoped feature means you are in the RootWeb context)
                newChildScopeAsNestedAsPossible = this.locatorAccessor.ServiceLocatorInstance.BeginFeatureLifetimeScope(feature);
            }

            return newChildScopeAsNestedAsPossible;
        }
Exemplo n.º 3
0
        //: this(spParent, feature.Definition, imageIndex, installed)
        public FeatureNode(object spParent, SPFeature feature, int imageIndex, bool installed)
        {
            this.SPParent = spParent;
            this.ImageIndex = imageIndex;
            this.SelectedImageIndex = imageIndex;
            this.IsInstalled = installed;

            Color nodeColor = this.ForeColor;
            string addText = string.Empty;

            try
            {

                if (feature.Definition != null)
                {
                    this.Tag = feature.Definition;

                    if (feature.Definition.Hidden)
                    {
                        nodeColor = Color.DarkGray;
                        addText = " (Hidden)";
                    }

                    _Text = feature.Definition.GetTitle(SPMConfig.Instance.CultureInfo) + addText;
                    _ToolTip = feature.Definition.GetDescription(SPMConfig.Instance.CultureInfo);
                    _Name = feature.Definition.Id.ToString();

                    this.ForeColor = nodeColor;
                }
                else
                {
                    this.Tag = null;

                    _Text = SPMLocalization.GetString("Feature_Message01");
                    _ToolTip = SPMLocalization.GetString("Feature_Message02");
                    _Name = feature.DefinitionId.ToString();
                }
            }
            catch(Exception ex)
            {

                this.ForeColor = Color.DarkRed;
                _Text = "(Error: Feature missing)";
                _ToolTip = ex.Message;
                _Name = feature.DefinitionId + string.Empty;
            }

            this.Setup();

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
Exemplo n.º 4
0
        public static ActivatedFeature ToActivatedFeature(this SPFeature spFeature, Guid parentId, Scope parentScope, string parentUrl)
        {
            FeatureDefinition definition = null;
            bool faulty = false;

            string definitionInstallationScope = GetDefinitionInstallationScope(spFeature.FeatureDefinitionScope == SPFeatureDefinitionScope.Farm, parentUrl);

            try
            {
                if (spFeature.Definition != null)
                {
                    var fDef = spFeature.Definition;
                    definition = fDef.ToFeatureDefinition(definitionInstallationScope);
                }
                else
                {
                    definition = FeatureDefinitionFactory.GetFaultyDefinition(spFeature.DefinitionId, parentScope, spFeature.Version, definitionInstallationScope);
                    faulty     = true;
                }
            }
            catch (Exception)
            {
                faulty = true;
            }


            var feature = ActivatedFeatureFactory.GetActivatedFeature(
                spFeature.DefinitionId,
                parentId,
                definition,
                faulty,
                spFeature.Properties == null ? null :
                spFeature.Properties.ToProperties(),
                spFeature.TimeActivated,
                spFeature.Version,
                definitionInstallationScope
                );

            return(feature);
        }
Exemplo n.º 5
0
 protected void Button1_Click1(object sender, EventArgs e)
 {
     using (SPSite mySite = new SPSite(SPContext.Current.Site.ID))
     {
         Guid      featureID = new Guid("6e1e5426-2ebd-4871-8027-c5ca86371ead");
         SPFeature feature   = mySite.Features[featureID];
         if (feature == null)
         {
             feature = mySite.Features.Add(featureID);
         }
         string p = feature.TimeActivated.ToString() + "    " + feature.Definition.Status;
         //foreach (SPFeatureProperty prop in define.Properties)
         //{
         //    p = prop.Name + "    " + prop.Value + "-------";
         div_Message.InnerHtml += p + "<br/>";
         //}
     }
     ////#1
     //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "UpdatePanel1", "alert(1)", true);
     ////#2
     //ScriptManager.RegisterStartupScript(this.UpdatePanel2, this.GetType(), "UpdatePanel2", "alert(2)", true);
 }
 private void EnsureWebFeatureActivated(Guid featureGuid, SPSite lSite, SPWeb lWeb)
 {
     using (SPSite site = new SPSite(lSite.ID))
     {
         using (SPWeb web = site.OpenWeb(lWeb.ID))
         {
             site.AllowUnsafeUpdates = true;
             web.AllowUnsafeUpdates  = true;
             SPFeature feature = null;
             try
             {
                 feature = web.Features[featureGuid];
             }
             catch
             {
                 web.Features.Add(featureGuid);
             }
             site.AllowUnsafeUpdates = false;
             web.AllowUnsafeUpdates  = false;
         }
     }
 }
        public static void UpgradeFeatures(ref SPSite site, Guid featureId)
        {
            SPFeatureQueryResultCollection features = null;

            try
            {
                features = site.QueryFeatures(featureId, true);
            }
            catch {// not contained
            }

            if (features != null)
            {
                IEnumerator <SPFeature> featureEnumerator = features.GetEnumerator();
                featureEnumerator.Reset();
                while (featureEnumerator.MoveNext())
                {
                    SPFeature feature = featureEnumerator.Current;
                    feature.Upgrade(false);
                }
            }
        }
Exemplo n.º 8
0
        public static FeatureParent GetFeatureParent(SPFeature feature, SPFeatureScope scope)
        {
            try
            {
                if (feature != null && feature.Parent != null && scope != SPFeatureScope.ScopeInvalid)
                {
                    switch (scope)
                    {
                    case SPFeatureScope.Farm:
                        var f = feature.Parent as SPWebService;     // SPWebService.ContentService.Features
                        return(GetFeatureParent(f));

                    case SPFeatureScope.WebApplication:
                        var wa = feature.Parent as SPWebApplication;
                        return(GetFeatureParent(wa));

                    case SPFeatureScope.Site:
                        var s = feature.Parent as SPSite;
                        return(GetFeatureParent(s));

                    case SPFeatureScope.Web:
                        var w = feature.Parent as SPWeb;
                        return(GetFeatureParent(w));

                    default:
                        return(GetFeatureParentUndefined());
                    }
                }
                else
                {
                    return(GetFeatureParentUndefined());
                }
            }
            catch (Exception ex)
            {
                return(GetFeatureParentUndefined(ex.Message));
            }
        }
Exemplo n.º 9
0
        public void AddActivatedFeature(SPFeature feature)
        {
            if (feature == null)
            {
                return;
            }

            try
            {
                var activatedFeature = ActivatedFeature.GetActivatedFeature(feature);

                // update activated features
                this.ActivatedFeatures.Add(activatedFeature);


                // update featureDefinition (and its activated instances)
                var featureDef = this.FeatureDefinitions.FirstOrDefault(fd => fd.Id == activatedFeature.Id);

                if (featureDef != null)
                {
                    // add activated feature to feature definition
                    featureDef.ActivatedFeatures.Add(activatedFeature);
                }
                else
                {
                    // fyi - if we get here, we have most likely a group of faulty features ...

                    // create feature definition and add features
                    var newFeatureDef = FeatureDefinition.GetFeatureDefinition(activatedFeature);
                    this.FeatureDefinitions.Add(newFeatureDef);
                    Log.Warning("Unexpected - Feature Definition of activated Feature was not available - please Reload");
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error when trying to add new feature to InMemorySharePointDb", ex);
            }
        }
Exemplo n.º 10
0
        private void AddFeaturesForScope(TreeNode pnode, List <SPFeatureDefinition> fds, SPFeatureCollection active)
        {
            TreeNode fnode = new TreeNode("Features", 9, 9);

            pnode.Nodes.Add(fnode);

            foreach (SPFeatureDefinition fd in fds)
            {
                SPFeature f = active[fd.Id];

                TreeNode chnode;
                if (f == null)
                {
                    chnode = new TreeNode(fd.DisplayName, 1, 1);
                }
                else
                {
                    chnode = new TreeNode(fd.DisplayName, 0, 0);
                }
                chnode.Tag = f;
                fnode.Nodes.Add(chnode);
            }
        }
            // Modif JPI - Début
            protected static void DeactivateFeature(List <SPSite> siteCollections, List <Guid?> featureIds)
            {
                try {
                    if (siteCollections != null && featureIds != null && featureIds.Count > 0)
                    {
                        log.Info(res.FeatureDeactivation);
                        foreach (SPSite siteCollection in siteCollections)
                        {
                            foreach (Guid?featureId in featureIds)
                            {
                                if (featureId == null)
                                {
                                    continue;
                                }

                                SPFeature feature = siteCollection.Features [featureId.Value];
                                if (feature == null)
                                {
                                    continue;
                                }

                                siteCollection.Features.Remove(featureId.Value);
                                log.Info(siteCollection.Url + " : " + featureId.Value.ToString());
                            }
                        }
                    }
                } catch (ArgumentException ex)                  // Missing assembly in GAC
                {
                    log.Warn(ex.Message, ex);
                } catch (InvalidOperationException ex)                  // Missing receiver class
                {
                    log.Warn(ex.Message, ex);
                } catch (SqlException ex) {
                    throw new InstallException(ex.Message, ex);
                }
            }
Exemplo n.º 12
0
 protected internal override bool Execute()
 {
     try
     {
         // Modif JPI - Début
         ReadOnlyCollection <Guid?> featureIds = InstallConfiguration.FeatureIdList;
         if (featureIds != null && featureIds.Count > 0)
         {
             foreach (Guid?featureId in featureIds)
             {
                 if (featureId != null)
                 {
                     SPFeature feature = FeatureActivator.ActivateOneFeature(SPWebService.AdministrationService.Features, featureId.Value, log);
                 }
             }
         }
         return(true);
         // Modif JPI - Fin
     }
     catch (Exception ex)
     {
         throw new InstallException(ex.Message, ex);
     }
 }
 /// <summary>
 /// Begins the lifetime scope.
 /// </summary>
 /// <param name="feature">The feature.</param>
 /// <returns>A lifetime scope.</returns>
 public ILifetimeScope BeginLifetimeScope(SPFeature feature)
 {
     return InnerServiceLocator.BeginLifetimeScope(feature);
 }
Exemplo n.º 14
0
        void rootTable_DataBinding(object sender, EventArgs e)
        {
            Table       rootTable = (Table)sender;
            GridViewRow row       = (GridViewRow)rootTable.NamingContainer;
            int         itemID    = int.Parse(DataBinder.Eval(row.DataItem, Fields.IDField).ToString());
            SPFile      itemFile  = settings.DocumentLibrary.GetItemById(itemID).File;

            string fileurl = new Uri(new Uri(settings.DocumentLibrary.ParentWeb.Url), String.Format("{0}?ID={1}", settings.DocumentLibrary.Forms[PAGETYPE.PAGE_DISPLAYFORM].ServerRelativeUrl, itemID)).OriginalString;


            //Bind image controls
            Image  docIconImage = (Image)rootTable.FindControl(DocIconID);
            string iconUrl      = itemFile.IconUrl;

            docIconImage.ImageUrl = "/_layouts/images/" + iconUrl.TrimStart('/');

            //Bind the title link
            HyperLink titleLink = (HyperLink)rootTable.FindControl(TitleLinkID);

            titleLink.Text        = (String.IsNullOrEmpty(itemFile.Title)) ? itemFile.Name : itemFile.Title;
            titleLink.NavigateUrl = fileurl;

            //check if SLK feature is activated to show e-learning action link
            SPFeature SLKFeature = settings.DocumentLibrary.ParentWeb.Features[new Guid(SLKFeatureID)];

            if (SLKFeature != null)
            {
                //Bind Actions link
                HyperLink actionsImage = (HyperLink)rootTable.FindControl(ActionsLinkID);
                actionsImage.NavigateUrl = String.Format(ELearningActionsUrl, settings.DocumentLibrary.ParentWebUrl.TrimEnd('/'), settings.ListID, itemID);
                actionsImage.ImageUrl    = "/_layouts/SharePointLearningKit/Images/ActionsIcon.gif";
                actionsImage.ToolTip     = settings.ActionsLinkText;
            }

            //Bind the details row
            if (settings.Keywords.Count > 0)
            {
                TableCell             detailsCell     = (TableCell)rootTable.FindControl(DetailsCellID);
                IDictionaryEnumerator keywordIterator = settings.Keywords.GetEnumerator();
                while (keywordIterator.MoveNext())
                {
                    Label  keywordLabel = new Label();
                    string keyword      = keywordIterator.Key.ToString();
                    string fieldTitle   = settings.SelectedContentType.Fields.GetFieldByInternalName(keyword).Title;
                    keywordLabel.Text = String.Format("{0}:{1}", fieldTitle, DataBinder.Eval(row.DataItem, keyword).ToString());

                    detailsCell.Controls.Add(keywordLabel);
                    detailsCell.Controls.Add(new LiteralControl("<BR>"));
                }
            }


            string tempAuthor = String.Empty;
            string tempSize   = String.Empty;
            string tempdate   = string.Empty;


            if (DataBinder.Eval(row.DataItem, Fields.Created_By).GetType() != typeof(DBNull))
            {
                tempAuthor = " - " + DataBinder.Eval(row.DataItem, Fields.Created_By).ToString();
            }


            if (DataBinder.Eval(row.DataItem, Fields.FileSizeDisplayField).GetType() != typeof(DBNull))
            {
                //format size
                long sizeInBytes = long.Parse(DataBinder.Eval(row.DataItem, Fields.FileSizeDisplayField).ToString());
                tempSize = " - " + SPUtility.FormatSize(sizeInBytes);
            }

            if (DataBinder.Eval(row.DataItem, Fields.CreatedField).GetType() != typeof(DBNull))
            {
                DateTime creationDate = DateTime.Parse(DataBinder.Eval(row.DataItem, Fields.CreatedField).ToString());

                tempdate = " - " + SPUtility.FormatDate(settings.DocumentLibrary.ParentWeb, creationDate, SPDateFormat.DateOnly);
            }


            LiteralControl summaryText = (LiteralControl)rootTable.FindControl(SummaryControlID);

            summaryText.Text = String.Format(SummaryControlHTML, fileurl, (tempSize + tempAuthor + tempdate));
        }
Exemplo n.º 15
0
 private bool IsFeatureFaulty(SPFeature feature)
 {
     if (feature.Definition == null)
     {
         return true;
     }
     FeatureChecker checker = new FeatureChecker();
     if (checker.CheckFeature(feature).Faulty)
     {
         return true;
     }
     return false;
 }
Exemplo n.º 16
0
        public static ActivatedFeature ToActivatedFeature(
            this SPFeature spFeature,
            Location location)
        {
            FeatureDefinition definition = null;
            bool faulty = false;

            string  featureUniqueId;
            string  displayName;
            Version definitionVersion;

            try
            {
                var fDef = spFeature.Definition;

                if (fDef != null)
                {
                    if (spFeature.FeatureDefinitionScope == SPFeatureDefinitionScope.Web)
                    {
                        definition = fDef.ToFeatureDefinition(location.UniqueId);
                    }
                    else if (spFeature.FeatureDefinitionScope == SPFeatureDefinitionScope.Site)
                    {
                        if (location.Scope == Scope.Web)
                        {
                            definition = fDef.ToFeatureDefinition(location.ParentId);
                        }
                        else
                        {
                            // only other location with featuredefinitionscope site can be site collection
                            // therefore, location id for sandboxed solution is current location (site)
                            definition = fDef.ToFeatureDefinition(location.UniqueId);
                        }
                    }
                    else
                    {
                        // Featuredefinitionscope must be farm or none now, in both cases, no location will be assigned to feature definition ...
                        definition = fDef.ToFeatureDefinition(null);
                    }

                    featureUniqueId   = definition.UniqueIdentifier;
                    displayName       = definition.DisplayName;
                    definitionVersion = definition.Version;
                }
                else
                {
                    faulty = true;

                    featureUniqueId = Core.Common.StringHelper.GenerateUniqueId(
                        spFeature.DefinitionId,
                        Core.Common.Constants.Labels.FaultyFeatureCompatibilityLevel
                        );
                    displayName       = Core.Common.Constants.Labels.FaultyFeatureName;
                    definitionVersion = null;
                }
            }
            catch (Exception)
            {
                faulty = true;

                featureUniqueId = Core.Common.StringHelper.GenerateUniqueId(
                    spFeature.DefinitionId,
                    Core.Common.Constants.Labels.FaultyFeatureCompatibilityLevel
                    );
                displayName       = Core.Common.Constants.Labels.FaultyFeatureName;
                definitionVersion = null;
            }

            var feature = ActivatedFeatureFactory.GetActivatedFeature(
                featureUniqueId,
                location.UniqueId,
                displayName,
                faulty,
                spFeature.Properties == null ? null :
                spFeature.Properties.ToProperties(),
                spFeature.TimeActivated,
                spFeature.Version,
                definitionVersion,
                spFeature.FeatureDefinitionScope.ToFeatureDefinitionScope()
                );

            return(feature);
        }
Exemplo n.º 17
0
 private string GetFeatureSolutionInfo(SPFeature feature)
 {
     string text = "";
     try
     {
         if (feature.Definition != null
             && feature.Definition.SolutionId != Guid.Empty)
         {
             text = string.Format("SolutionId={0}", feature.Definition.SolutionId);
             SPSolution solution = SPFarm.Local.Solutions[feature.Definition.SolutionId];
             if (solution != null)
             {
                 try {
                     text += string.Format(", SolutionName='{0}'", solution.Name);
                 } catch { }
                 try {
                     text += string.Format(", SolutionDisplayName='{0}'", solution.DisplayName);
                 } catch { }
                 try {
                     text += string.Format(", SolutionDeploymentState='{0}'", solution.DeploymentState);
                 } catch { }
             }
         }
     }
     catch
     {
     }
         return text;
 }
Exemplo n.º 18
0
 /// <summary>
 /// Creates a new child lifetime scope that is as nested as possible,
 /// depending on the scope of the specified feature.
 /// In a SPSite or SPWeb-scoped feature context, will return a web-specific
 /// lifetime scope (allowing you to inject InstancePerSite and InstancePerWeb
 /// objects).
 /// In a SPFarm or SPWebApplication feature context, will return a child
 /// container of the root application container (preventing you from injecting
 /// InstancePerSite, InstancePerWeb or InstancePerRequest objects).
 /// Please dispose this lifetime scope when done (E.G. call this method from
 /// a using block).
 /// Prefer usage of this method versus resolving manually from the Current property.
 /// </summary>
 /// <param name="feature">The current feature that is requesting a child lifetime scope</param>
 /// <returns>A new child lifetime scope which should be disposed by the caller.</returns>
 public static ILifetimeScope BeginLifetimeScope(SPFeature feature)
 {
     return(innerLocator.BeginLifetimeScope(feature));
 }
Exemplo n.º 19
0
        /// <summary>
        /// activate a feature
        /// </summary>
        /// <param name="features">collection of features</param>
        /// <param name="featureId">feature ID of feature to handle</param>
        /// <param name="force">with or without force</param>
        /// <returns>the activated feature</returns>
        /// <remarks>attention, might throw exception!</remarks>
        internal static SPFeature UpgradeFeatureInFeatureCollection(SPFeatureCollection features, Guid featureId, bool force)
        {
            SPFeature spFeature = null;

            IEnumerable <Exception> upgradeErrors;
            bool success = true;

            string upgradeErrorsAsString = null;

            spFeature = features[featureId];

            var definitionVersion = spFeature.Definition.Version;

            if (spFeature.Version < definitionVersion)
            {
                upgradeErrors = spFeature.Upgrade(force);
            }
            else
            {
                var errMsg = string.Format("Feature '{0}' does not require upgrade.", featureId);

                throw new ApplicationException(errMsg);
            }

            if (upgradeErrors != null && upgradeErrors.Count() > 0)
            {
                success = false;

                foreach (Exception x in upgradeErrors)
                {
                    upgradeErrorsAsString += string.Format(
                        "Error: {0}\n",
                        x.Message
                        );
                }
            }


            if (spFeature.Version != definitionVersion || !success)
            {
                var errMsg = string.Format("Feature upgrade for feature '{0}' failed. Feature version: '{1}', definition version: '{2}'.",
                                           featureId,
                                           spFeature.Version,
                                           definitionVersion);

                if (!force)
                {
                    errMsg += " You might want to try again with 'force' enabled.";
                }

                if (!string.IsNullOrEmpty(upgradeErrorsAsString))
                {
                    errMsg += upgradeErrorsAsString;
                }


                throw new ApplicationException(errMsg);
            }

            return(spFeature);
        }
Exemplo n.º 20
0
 public static Guid GetFeatureId(this SPFeature feature)
 {
     return(feature.Definition.Id);
 }
        /// <summary>
        /// Ensures the approval workflow on list.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="list">The list.</param>
        /// <param name="events">The events.</param>
        /// <param name="useSamlWorkflow">Whether to use the SAML Approval workflow</param>
        /// <returns>
        /// The workflow subscription id
        /// </returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static Guid EnsureApprovalWorkflowOnList(SPWeb web, SPList list, List <WorkflowStartEventType> events, bool useSamlWorkflow)
        {
            Guid subscriptionId = Guid.Empty;

            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            // Remove existing 2010 workflow associations
            SPWorkflowAssociationCollection existingWorkflows = list.WorkflowAssociations;

            if (existingWorkflows != null)
            {
                for (int i = 0; i < existingWorkflows.Count; i++)
                {
                    list.WorkflowAssociations.Remove(existingWorkflows[i]);
                }
            }

            //SPFeature customWorkflowActivitiesFeature = web.Features[customWorkflowActivitiesFeatureId];

            //if (customWorkflowActivitiesFeature == null)
            //{
            //    customWorkflowActivitiesFeature = web.Features.Add(customWorkflowActivitiesFeatureId);
            //}

            SPFeature customWorkflowFeature = web.Features[customWorkflowFeatureId];

            if (customWorkflowFeature == null)
            {
                customWorkflowFeature = web.Features.Add(customWorkflowFeatureId);
            }

            if (customWorkflowFeature != null)
            {
                if (!list.EnableModeration || !list.ForceCheckout)
                {
                    list.EnableModeration = true;
                    list.ForceCheckout    = true;
                    list.EnableVersioning = true;
                    list.Update();
                }

                Dictionary <string, string> workflowPropertyData = GetApprovalWorkflowSettings(web, list.Title);

                SPList taskList = EnsureWorkflowTaskList(web, "/lists/workflowtasks", string.Empty);

                SPList historyList = EnsureWorkflowHistoryList(web, "/workflowhistory", string.Empty);

                if (taskList != null && historyList != null)
                {
                    bool workflowTaskContentTypeAssociated = false;
                    foreach (SPContentType contentType in taskList.ContentTypes)
                    {
                        if (contentType.Parent.Id.ToString().Equals(ContentTypeWorkflowTaskSharePoint2013, StringComparison.OrdinalIgnoreCase))
                        {
                            workflowTaskContentTypeAssociated = true;
                            break;
                        }
                    }

                    if (!workflowTaskContentTypeAssociated)
                    {
                        SPContentType           wftaskContentType = default(SPContentType);
                        SPContentTypeCollection contentTypes      = web.ContentTypes.Count == 0 ? web.Site.RootWeb.ContentTypes : web.ContentTypes;

                        wftaskContentType = contentTypes.Cast <SPContentType>().FirstOrDefault <SPContentType>(c => c.Id.ToString().Equals(ContentTypeWorkflowTaskSharePoint2013, StringComparison.OrdinalIgnoreCase));

                        if (wftaskContentType != null)
                        {
                            taskList.ContentTypes.Add(wftaskContentType);
                        }
                    }

                    string displayName = ResourcesHelper.GetLocalizedString("workflow_approval_instancename");

                    Guid workflowDefId = useSamlWorkflow ? approvalSamlWorkflowDefinitionId : approvalWorkflowDefinitionId;

                    subscriptionId = EnsureWorkflowOnList(web, list, workflowDefId, displayName, events, taskList, historyList, workflowPropertyData, false);

                    EnableWorkflowsRunAsAnApp(web);

                    SubscribeToEventReceivers(list, false);
                }
            }

            return(subscriptionId);
        }
 /// <summary>
 /// Creates a new child lifetime scope that is as nested as possible,
 /// depending on the scope of the specified feature.
 /// In a SPSite or SPWeb-scoped feature context, will return a web-specific
 /// lifetime scope (allowing you to inject InstancePerSite and InstancePerWeb
 /// objects).
 /// In a SPFarm or SPWebApplication feature context, will return a child
 /// container of the root application container (preventing you from injecting
 /// InstancePerSite, InstancePerWeb or InstancePerRequest objects).
 /// Please dispose this lifetime scope when done (E.G. call this method from
 /// a using block).
 /// Prefer usage of this method versus resolving manually from the Current property.
 /// </summary>
 /// <param name="feature">The current feature that is requesting a child lifetime scope</param>
 /// <returns>A new child lifetime scope which should be disposed by the caller.</returns>
 public static ILifetimeScope BeginFeatureLifetimeScope(SPFeature feature)
 {
     return InnerLocator.BeginLifetimeScope(feature);
 }
        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);
        }
 /// <summary>
 /// Creates a new child lifetime scope that is as nested as possible,
 /// depending on the scope of the specified feature.
 /// In a SPSite or SPWeb-scoped feature context, will return a web-specific
 /// lifetime scope (allowing you to inject InstancePerSite and InstancePerWeb
 /// objects).
 /// In a SPFarm or SPWebApplication feature context, this method will throw
 /// an exception of type <see cref="InvalidOperationException"/>. Dynamite components
 /// must be configured under a specific SPSite's scope.
 /// Please dispose this lifetime scope when done (E.G. call this method from
 /// a using block).
 /// Prefer usage of this method versus resolving individual dependencies from the 
 /// ISharePointServiceLocator.Current property.
 /// </summary>
 /// <param name="feature">The current feature that is requesting a child lifetime scope</param>
 /// <returns>A new child lifetime scope which should be disposed by the caller.</returns>
 public static ILifetimeScope BeginFeatureLifetimeScope(SPFeature feature)
 {
     return extensionProvidedServiceLocator.BeginLifetimeScope(feature);
 }
Exemplo n.º 25
0
 protected bool IsFeatureActivated(SPFeature currentFeature)
 {
     return currentFeature != null;
 }
Exemplo n.º 26
0
 protected bool IsFeatureActivated(SPFeature currentFeature)
 {
     return(currentFeature != null);
 }
        /// <summary>
        /// <para>
        /// Creates a new child lifetime scope that is as nested as possible,
        /// depending on the scope of the specified feature.
        /// </para>
        /// <para>
        /// In a SPSite or SPWeb-scoped feature context, will return a web-specific
        /// lifetime scope (allowing you to inject InstancePerSite and InstancePerWeb
        /// objects - InstancePerRequest scoped objects will be inaccessible).
        /// </para>
        /// <para>
        /// In a SPFarm or SPWebApplication feature context, will return a child
        /// container of the root application container (preventing you from injecting
        /// InstancePerSite, InstancePerWeb or InstancePerRequest objects).
        /// </para>
        /// <para>
        /// If more than 1 assembly matches the *.ServiceLocator.DLL pattern in the GAC,
        /// store your preferred ServiceLocator assembly name (with key: 'ServiceLocatorAssemblyName') 
        /// in one of the SPPersistedObject's property bags in the SPWeb-SPSite-SPWebApp-SPFarm 
        /// hierarchy to indicate which ServiceLocator should be used in your context. If
        /// the discriminator setting cannot be found in any of the property bags in the
        /// hierarchy, an error will be logged to ULS and the FallbackServiceLocator will be used
        /// (preventing your AddOn registration modules from being loaded).
        /// </para>
        /// <para>
        /// Please dispose this lifetime scope when done (E.G. call this method from
        /// a using block).
        /// </para>
        /// </summary>
        /// <param name="feature">The current feature context from which we are requesting a child lifetime scope</param>
        /// <returns>A new child lifetime scope which should be disposed by the caller.</returns>
        public ILifetimeScope BeginLifetimeScope(SPFeature feature)
        {
            SPWeb currentFeatureWeb = feature.Parent as SPWeb;
            SPSite currentFeatureSite = feature.Parent as SPSite;
            SPWebApplication currentFeatureWebApp = feature.Parent as SPWebApplication;
            SPFarm currentFeatureFarm = feature.Parent as SPFarm;

            if (currentFeatureWeb != null)
            {
                this.EnsureServiceLocatorAccessorForCurrentContext(currentFeatureWeb);
            }
            else if (currentFeatureSite != null)
            {
                this.EnsureServiceLocatorAccessorForCurrentContext(currentFeatureSite);
            }
            else if (currentFeatureWebApp != null)
            {
                this.EnsureServiceLocatorAccessorForCurrentContext(currentFeatureWebApp);
            }
            else if (currentFeatureFarm != null)
            {
                this.EnsureServiceLocatorAccessorForCurrentContext(currentFeatureFarm);
            }
            else
            {
                throw new NotSupportedException("In order to use a lifetime scope, a context (SPWeb, SPSite, SPWebApplication, or SPFarm) needs to be passed.");
            }

            return this.GetLocatorAccessor(currentFeatureWeb, currentFeatureSite, currentFeatureWebApp, currentFeatureFarm).ServiceLocatorInstance.BeginLifetimeScope(feature);
        }
        /// <summary>
        /// Creates a new child lifetime scope that is as nested as possible,
        /// depending on the scope of the specified feature.
        /// In a SPSite or SPWeb-scoped feature context, will return a web-specific
        /// lifetime scope (allowing you to inject InstancePerSite and InstancePerWeb
        /// objects).
        /// In a SPFarm or SPWebApplication feature context, will return a child
        /// container of the root application container (preventing you from injecting
        /// InstancePerSite, InstancePerWeb or InstancePerRequest objects).
        /// Please dispose this lifetime scope when done (E.G. call this method from
        /// a using block).
        /// Prefer usage of this method versus resolving indididual dependencies from the 
        /// ISharePointServiceLocator.Current property.
        /// </summary>
        /// <param name="feature">The current feature that is requesting a child lifetime scope</param>
        /// <returns>A new child lifetime scope which should be disposed by the caller.</returns>
        public ILifetimeScope BeginFeatureLifetimeScope(SPFeature feature)
        {
            ILifetimeScope newChildScopeAsNestedAsPossible = null;

            SPSite currentFeatureSite = feature.Parent as SPSite;
            SPWeb currentFeatureWeb = null;

            if (currentFeatureSite == null)
            {
                // this is a Web-scoped feature, not a Site-scoped one
                currentFeatureWeb = feature.Parent as SPWeb;
            }
            else
            {
                // this is a Site-scope feature, use the RootWeb as current
                currentFeatureWeb = currentFeatureSite.RootWeb;
            }

            if (currentFeatureWeb == null)
            {
                // We are dealing with a SPWebApplication and SPFarm-scoped feature, so we can
                // only give you a child lifetime that is a direct child of the root container.
                // I.E. this service locator/scope won't be able to resolve any InstancePerSite,
                // InstancePerWeb or InstancePerRequest-registered instances.
                newChildScopeAsNestedAsPossible = this.containerProvider.Current.BeginLifetimeScope();
            }
            else
            {
                // We are dealing with a SPSite or SPWeb-scoped feature.
                // Always return a web scope (even for Site-scoped features - as being in a site-scoped feature means you are in the RootWeb context)
                newChildScopeAsNestedAsPossible = this.containerProvider.EnsureWebScope(currentFeatureWeb).BeginLifetimeScope();
            }

            return newChildScopeAsNestedAsPossible;
        }
        private static ActivatedFeature MapSpFeatureToActivatedFeature(SPFeature feature, FeatureParent parent)
        {
            var af = GetActivatedFeature(feature, parent);

            return(af);
        }
Exemplo n.º 30
0
        public void InstantiateIn(Control container)
        {
            //This table holds all other UI elements for each search result
            //The table is structure with 3 rows:
            //* Header row : holds the document icon, title link and E-learning actions
            //* Details row: holds the details of the fields selected in search
            //* Summary row: holds the summary infomration about the item such as the full url, size, author and creation date

            Table rootTable = new Table();

            rootTable.CellPadding = 0;
            rootTable.CellSpacing = 0;

            TableRow row = new TableRow();

            rootTable.Rows.Add(row);
            TableCell cell = new TableCell();

            row.Cells.Add(cell);
            cell.ColumnSpan = 3;


            Table headerTable = new Table();

            headerTable.CellPadding = 0;
            headerTable.CellSpacing = 0;
            headerTable.Width       = new Unit(100, UnitType.Percentage);

            cell.Controls.Add(headerTable);
            //Create header row
            TableRow headerRow = new TableRow();
            //create header row cells  and controls


            //Doc Icon
            TableCell docIconCell = new TableCell();
            //Holds the document file type icon url
            Image docIcon = new Image();

            docIcon.ID       = DocIconID;
            docIcon.CssClass = Styles.Srch_Icon;

            docIconCell.Controls.Add(docIcon);
            headerRow.Cells.Add(docIconCell);
            //Title link
            TableCell titleCell = new TableCell();

            titleCell.Width = new Unit(100, UnitType.Percentage);
            HyperLink titleLink = new HyperLink();

            titleLink.ID       = TitleLinkID;
            titleLink.CssClass = Styles.Srch_Title;
            titleCell.Controls.Add(titleLink);
            headerRow.Cells.Add(titleCell);
            //E- Learning actions link
            //check if SLK feature is activated to show e-learning action link
            SPFeature SLKFeature = settings.DocumentLibrary.ParentWeb.Features[new Guid(SLKFeatureID)];

            if (SLKFeature != null)
            {
                TableCell actionsCell = new TableCell();
                HyperLink actionsLink = new HyperLink();
                actionsLink.ID       = ActionsLinkID;
                actionsLink.CssClass = Styles.Srch_Icon;
                actionsCell.Controls.Add(actionsLink);
                headerRow.Cells.Add(actionsCell);
            }
            headerTable.Rows.Add(headerRow);

            //Details Row
            TableRow detailsRow = new TableRow();

            rootTable.Rows.Add(detailsRow);
            //This cell holds the table containg the dynamic list of searched fields
            TableCell detailsCell = new TableCell();

            detailsCell.ID         = DetailsCellID;
            detailsCell.ColumnSpan = 3;
            detailsCell.CssClass   = Styles.Srch_Description;
            detailsRow.Cells.Add(detailsCell);
            //Summary row
            TableRow summaryRow = new TableRow();

            rootTable.Rows.Add(summaryRow);


            //File Link
            TableCell fileLinkCell = new TableCell();

            fileLinkCell.CssClass = Styles.Srch_Metadata;
            summaryRow.Cells.Add(fileLinkCell);
            fileLinkCell.ColumnSpan = 3;
            LiteralControl summaryControl = new LiteralControl();

            summaryControl.ID = SummaryControlID;
            fileLinkCell.Controls.Add(summaryControl);



            rootTable.DataBinding += new EventHandler(rootTable_DataBinding);

            container.Controls.Add(rootTable);
        }
Exemplo n.º 31
0
        internal static void DoInstallation(Package.InstallationStateData installationStateData, BackgroundWorker _wrkr, DoWorkEventArgs e, FileInfo packageContentLocation)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                if (_wrkr.CancellationPending)
                {
                    e.Cancel = true;
                    e.Result = false;
                    return;
                }
                try
                {
                    string _format = "Trying to create or reuse the site collection at {0}, configured site template {1}, LCID {2}.";
                    _wrkr.ReportProgress(1, String.Format(_format, installationStateData.SiteCollectionURL, installationStateData.SiteTemplate, installationStateData.LCID));
                    using (SiteCollectionHelper m_SiteCollectionHelper = SiteCollectionHelper.GetSPSite(
                               FarmHelpers.WebApplication,
                               installationStateData.SiteCollectionURL,
                               installationStateData.Title,
                               installationStateData.Description,
                               installationStateData.LCID,
                               null,
                               installationStateData.OwnerLogin,
                               installationStateData.OwnerName,
                               installationStateData.OwnerEmail))
                    {
                        installationStateData.SiteCollectionCreated = true;
                        _wrkr.ReportProgress(1, "Site collection is created");
                        if (m_SiteCollectionHelper.NewTemplateRequired)
                        {
                            _wrkr.ReportProgress(1, "Applying new template - select required from dialog.");
                            s_EndOFUIAction.Reset();
                            SPWebTemplateCollection _cllctn = m_SiteCollectionHelper.GetWebTemplates(installationStateData.LCID);
                            _wrkr.ReportProgress(1, new SPWebTeplateEventArgs(_cllctn, GetTemplate, 1, "Getting Site template")); //GetTemplate( FarmHelpers.WebApplication.Sites[ _urlSite ], installationStateData );
                            s_EndOFUIAction.WaitOne();
                            _wrkr.ReportProgress(1, String.Format("Applying new template {0}", WebTemplateDialog.SPWebTemplateToString(installationStateData.SPWebTemplate)));
                            m_SiteCollectionHelper.ApplayTemplate(installationStateData.SPWebTemplate);
                        }
                        _format = "The site template is configured to Name: {0}/ Id: {1}.";
                        _wrkr.ReportProgress(1, String.Format(_format, m_SiteCollectionHelper.SiteTemplate, m_SiteCollectionHelper.SiteTemplateID));
                        using (PackageContent _PackageContent = new PackageContent(packageContentLocation))
                        {
                            foreach (Solution _sltn in installationStateData.SolutionsToInstall.Values)
                            {
                                FileInfo _fi = _sltn.SolutionFileInfo(_PackageContent.ContentLocation);
                                _wrkr.ReportProgress(1, String.Format("Deploying solution: {0}", _fi.Name));
                                switch (_sltn.FeatureDefinitionScope)
                                {
                                case FeatureDefinitionScope.Farm:
                                    TimeSpan _timeout            = new TimeSpan(0, 0, Properties.Settings.Default.SolutionDeploymentTimeOut);
                                    string _waitingForCompletion = String.Format("Waiting for completion .... It could take up to {0} s. ", _timeout);
                                    _wrkr.ReportProgress(1, _waitingForCompletion);
                                    SPSolution _sol = null;
                                    if (_sltn.Global)
                                    {
                                        _sol = FarmHelpers.DeploySolution(_fi, _timeout);
                                    }
                                    else
                                    {
                                        _sol = FarmHelpers.DeploySolution(_fi, FarmHelpers.WebApplication, _timeout);
                                    }
                                    _sltn.SolutionGuid = _sol.Id;
                                    _wrkr.ReportProgress(1, String.Format("Solution deployed Name={0}, Deployed={1}, DeploymentState={2}, DisplayName={3} Status={4}", _sol.Name, _sol.Deployed, _sol.DeploymentState, _sol.DisplayName, _sol.Status));
                                    break;

                                case FeatureDefinitionScope.Site:
                                    SPUserSolution _solution = null;
                                    _solution          = m_SiteCollectionHelper.DeploySolution(_fi);
                                    _sltn.SolutionGuid = _solution.SolutionId;
                                    _wrkr.ReportProgress(1, String.Format("Solution deployed: {0}", _solution.Name));
                                    break;

                                case FeatureDefinitionScope.None:
                                default:
                                    throw new ApplicationException("Wrong FeatureDefinitionScope in the configuration file");
                                }
                                _sltn.Deployed = true;
                                foreach (Feature _fix in _sltn.Fetures)
                                {
                                    bool _repeat;
                                    do
                                    {
                                        _repeat = false;
                                        try
                                        {
                                            if (!_fix.AutoActivate)
                                            {
                                                _wrkr.ReportProgress(1, String.Format("Skipping activation of the feature: {0} at: {1} because tha activation is set false", _fix.FetureGuid, m_SiteCollectionHelper.SiteCollection.Url));
                                                break;
                                            }
                                            _wrkr.ReportProgress(1, String.Format("Activating Feature: {0} at: {1}", _fix.FetureGuid, m_SiteCollectionHelper.SiteCollection.Url));
                                            SPFeature _ffeature = m_SiteCollectionHelper.ActivateFeature(_fix.FetureGuid, _sltn.SPFeatureDefinitionScope);
                                            _wrkr.ReportProgress(1, String.Format("Feature activated : {0}", _ffeature.Definition.DisplayName));
                                            _fix.DisplayName = _ffeature.Definition.DisplayName;
                                            _fix.Version     = _ffeature.Version.ToString();
                                            _fix.SPScope     = _ffeature.Definition.Scope;
                                        }
                                        catch (Exception ex)
                                        {
                                            string _msg = String.Format(Properties.Resources.FeatureActivationFailureMBox, ex.Message);
                                            Tracing.TraceEvent.TraceError(516, "SetUpData.Install", _msg);
                                            switch (MessageBox.Show(_msg, "Install ActivateFeature", MessageBoxButton.YesNoCancel, MessageBoxImage.Error, MessageBoxResult.No))
                                            {
                                            case MessageBoxResult.Cancel:
                                                throw ex;

                                            case MessageBoxResult.Yes:
                                                _repeat = true;
                                                break;

                                            default:
                                                break;
                                            }
                                        }
                                    } while (_repeat);
                                }//foreach (Feature _fix in _sltn.Fetures)
                                _sltn.Activated = true;
                            }
                        } //foreach (Solution _sltn
                        //TODO installationStateData.Save();
                        _wrkr.ReportProgress(1, "Product installation successfully completed");
                    }
                }
                catch (Exception ex)
                {
                    //TODO
                    //try
                    //{
                    //  installationStateData.Save();
                    //}
                    //catch ( Exception _SaveEx )
                    //{
                    //  InstallationListBox.AddMessage( _SaveEx.Message );
                    //}
                    string _msg = String.Format(Properties.Resources.LastOperationFailedWithError, ex.Message);
                    _wrkr.ReportProgress(1, _msg);
                    throw ex;
                }
            });
        }
Exemplo n.º 32
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var definition = model.WithAssertAndCast <FeatureDefinition>("model", value => value.RequireNotNull());

            SPFeatureCollection features = null;
            SPFeature           spObject = null;

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject);

            switch (definition.Scope)
            {
            case FeatureDefinitionScope.Farm:
                assert.SkipProperty(m => m.Scope, "Correct farm scope");

                var farmModelHost = modelHost.WithAssertAndCast <FarmModelHost>("modelHost", value => value.RequireNotNull());
                var farm          = farmModelHost.HostFarm;

                var adminService = SPWebService.AdministrationService;

                features = adminService.Features;

                break;

            case FeatureDefinitionScope.WebApplication:

                assert.SkipProperty(m => m.Scope, "Correct web app scope");

                var webApplicationModelHost = modelHost.WithAssertAndCast <WebApplicationModelHost>("modelHost", value => value.RequireNotNull());
                var webApplication          = webApplicationModelHost.HostWebApplication;

                features = webApplication.Features;

                break;

            case FeatureDefinitionScope.Site:

                assert.SkipProperty(m => m.Scope, "Correct site scope");

                var siteModelHost = modelHost.WithAssertAndCast <SiteModelHost>("modelHost", value => value.RequireNotNull());
                features = siteModelHost.HostSite.Features;
                break;

            case FeatureDefinitionScope.Web:

                assert.SkipProperty(m => m.Scope, "Correct web scope");

                var webModelHost = modelHost.WithAssertAndCast <WebModelHost>("modelHost", value => value.RequireNotNull());
                features = webModelHost.HostWeb.Features;
                break;
            }

            spObject   = GetFeature(features, definition);
            assert.Dst = spObject;

            assert
            .ShouldBeEqual(m => m.Id, o => o.GetFeatureId());

            if (definition.ForceActivate)
            {
                assert
                .SkipProperty(m => m.ForceActivate, "ForceActivate = true. Expect not null feature instance.")
                .ShouldNotBeNull(spObject);
            }
            else
            {
                assert
                .SkipProperty(m => m.ForceActivate, "ForceActivate = false. Skipping.");
            }


            if (definition.Enable)
            {
                assert
                .SkipProperty(m => m.Enable, "Enable = true. Expect not null feature instance.")
                .ShouldNotBeNull(spObject);
            }
            else
            {
                assert
                .SkipProperty(m => m.Enable, "Enable = false. Expect null feature instance.")
                .ShouldBeNull(spObject);
            }
        }
        /// <summary>
        /// Creates a new child lifetime scope that is as nested as possible,
        /// depending on the scope of the specified feature.
        /// 
        /// In a SPSite or SPWeb-scoped feature context, will return a web-specific
        /// lifetime scope (allowing you to inject InstancePerSite and InstancePerWeb
        /// objects - InstancePerRequest scoped objects will be inaccessible).
        /// 
        /// In a SPFarm or SPWebApplication feature context, will return a child
        /// container of the root application container (preventing you from injecting
        /// InstancePerSite, InstancePerWeb or InstancePerRequest objects).
        /// 
        /// If more than 1 assembly matches the *.ServiceLocator.DLL pattern in the GAC,
        /// store your preferred ServiceLocator assembly name (with key: 'ServiceLocatorAssemblyName') 
        /// in one of the SPPersistedObject's property bags in the SPWeb-SPSite-SPWebApp-SPFarm 
        /// hierarchy to indicate which ServiceLocator should be used in your context. If
        /// the disambiguator setting cannot be found in any of the property bags in the
        /// hierarchy, an error will be logged to ULS and the FallbackServiceLocator will be used
        /// (preventing your AddOn registration modules from being loaded).
        /// 
        /// Please dispose this lifetime scope when done (E.G. call this method from
        /// a using block).
        /// </summary>
        /// <param name="feature">The current feature context from which we are requesting a child lifetime scope</param>
        /// <returns>A new child lifetime scope which should be disposed by the caller.</returns>
        public ILifetimeScope BeginLifetimeScope(SPFeature feature)
        {
            SPWeb currentFeatureWeb = feature.Parent as SPWeb;
            SPSite currentFeatureSite = feature.Parent as SPSite;
            SPWebApplication currentFeatureWebApp = feature.Parent as SPWebApplication;
            SPFarm currentFeatureFarm = feature.Parent as SPFarm;

            if (currentFeatureWeb != null)
            {
                this.EnsureServiceLocatorAccessorForCurrentContext(currentFeatureWeb);
            }
            else if (currentFeatureSite != null)
            {
                this.EnsureServiceLocatorAccessorForCurrentContext(currentFeatureSite);
            }
            else if (currentFeatureWebApp != null)
            {
                this.EnsureServiceLocatorAccessorForCurrentContext(currentFeatureWebApp);
            }
            else if (currentFeatureFarm != null)
            {
                this.EnsureServiceLocatorAccessorForCurrentContext(currentFeatureFarm);
            }
            else
            {
                this.EnsureServiceLocatorAccessorForCurrentContext();
            }

            return this.locatorAccessor.ServiceLocatorInstance.BeginLifetimeScope(feature);;
        }
        /// <summary>
        /// Generate ActivatedFeature
        /// </summary>
        /// <param name="spFeature"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public static ActivatedFeature GetActivatedFeature(SPFeature spFeature, FeatureParent parent = null)
        {
            if (spFeature == null)
            {
                return(null);
            }

            // create preliminary feature with default values ...
            ActivatedFeature af = new ActivatedFeature()
            {
                Id                = Guid.Empty,
                Version           = new Version("0.0.0.0"),
                Parent            = parent,
                SharePointFeature = spFeature,
                Name              = "undefined",
                Faulty            = false
            };

            // in case of faulty features, many of these settings can not be set
            // therefore, every property is set in try / catch statement

            // ID
            try
            {
                af.Id = spFeature.DefinitionId;
            }
            catch (Exception ex)
            {
                if (af.Name.Equals("undefined"))
                {
                    af.Name = ex.Message;
                }
                af.Faulty = true;
            }

            // Version
            try
            {
                af.TimeActivated = spFeature.TimeActivated;
            }
            catch (Exception ex)
            {
                if (af.Name.Equals("undefined"))
                {
                    af.Name = ex.Message;
                }
                af.Faulty = true;
            }

            // Version
            try
            {
                af.Version = spFeature.Version;
            }
            catch (Exception ex)
            {
                if (af.Name.Equals("undefined"))
                {
                    af.Name = ex.Message;
                }
                af.Faulty = true;
            }

            // Parent
            try
            {
                af.Parent = parent == null?FeatureParent.GetFeatureParent(spFeature) : parent;
            }
            catch (Exception ex)
            {
                if (af.Name.Equals("undefined"))
                {
                    af.Name = ex.Message;
                }
                af.Faulty = true;
            }

            // SharePointFeature is already set on initialization of af
            // Name
            try
            {
                var def = spFeature.Definition;

                if (def != null)
                {
                    af.Name = def.DisplayName;
                }
                else
                {
                    af.Name   = string.Format(Common.Constants.Text.UndefinedActivatedFeature, af.Id);
                    af.Faulty = true;
                }
            }
            catch (Exception ex)
            {
                if (af.Name.Equals("undefined"))
                {
                    af.Name = ex.Message;
                }
                af.Faulty = true;
            }

            return(af);
        }
        protected override void CreateChildControls()
        {
            SPView excelView       = null;
            SPList excelList       = null;
            string excelListSchema = String.Empty;

            spFeatureSite = spSite.Features[Definitions.featureGuid];
            if (spFeatureSite != null)
            {
                try
                {
                    //Ziskam vsetky XsltListViewWebPart na stranke ak tam su
                    List <XsltListViewWebPart> xsltListCollection = GetListViewWebParts();
                    UserPermission             userPermission     = new UserPermission();

                    if (xsltListCollection != null)
                    {
                        foreach (XsltListViewWebPart xsltWebPart in xsltListCollection)
                        {
                            SPView         currentView            = SPContext.Current.Web.Lists[xsltWebPart.ListId].Views[new Guid(xsltWebPart.ViewGuid)];
                            SPList         currentList            = SPContext.Current.Web.Lists[xsltWebPart.ListId];
                            List <SPField> listFieldsInProperties = new List <SPField>();

                            excelView = currentView;
                            excelList = currentList;

                            //ToDo
                            //Schovanie View tam kde je View pouzite len vo webparzone!
                            //Ak na View nema pravo tak ten control ani nevykresli v pripade ze sa jedna o List tak
                            //sa to osetri v CustomViewSelectorMenu.cs presmerovanom na error page
                            //Nefunguje to pri vyklikanom sposobe vytvorenia listview vo webparzone lebo sa stale vytvara nove VIEW s novym guid
                            if (!viewSelector)
                            {
                                if (userPermission.GetViewPermissionForCurrentUser(currentView))
                                {
                                    xsltWebPart.Hidden = true;
                                    continue;
                                }
                            }

                            listFieldsInProperties = FindFieldsInProperties(currentView, currentList);

                            if (listFieldsInProperties != null)
                            {
                                if (listFieldsInProperties.Count != 0)
                                {
                                    string newXmlDefinition = HideFieldsInXsltDefinition(listFieldsInProperties, xsltWebPart.XmlDefinition);

                                    xsltWebPart.AsyncRefresh  = true;
                                    xsltWebPart.XmlDefinition = newXmlDefinition;

                                    //Toto naplnam pre RenderActiveX prvok
                                    excelListSchema = newXmlDefinition;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    //ToDo
                }
            }

            base.CreateChildControls();

            #region - DataSheet -

            //if (Page.Request.QueryString["ShowInGrid"] == "True")
            //{
            //    spFeatureSite = spSite.Features[Definitions.featureGuid];
            //    if (spFeatureSite != null)
            //    {
            //        if (!excelListSchema.Equals(String.Empty))
            //        {
            //            try
            //            {
            //                Control controlPlaceHolderMain = this.findControl(this.Page, "PlaceHolderMain");
            //                if (controlPlaceHolderMain != null)
            //                {
            //                    Control controlParent = controlPlaceHolderMain.Parent;
            //                    if (controlParent != null)
            //                    {

            //                        //Schovame stary ActiveX prvok
            //                        Literal newStyle = new Literal();
            //                        newStyle.Text = "<style type=\"text/css\">#STSListControlWPQ2{ display:none }</style>";
            //                        controlPlaceHolderMain.Controls.Add(newStyle);

            //                        Guid webGuid = spWeb.ID;
            //                        Guid listGuid = excelList.ID;
            //                        Guid viewGuid = excelView.ID;

            //                        string ListData = EncodeString(excelList.Items.Xml);
            //                        string ViewSchema = EncodeString(excelListSchema);
            //                        string ListSchema = EncodeString(excelList.SchemaXml);
            //                        string UrlLink = EncodeString(spWeb.Url);

            //                        string csScript = "<script type='text/javascript'>RenderActiveX('\u003cobject id=\u0022STSListControlWPQ3\u0022 name=\u0022STSListControlWPQ3\u0022 classid=CLSID:65BCBEE4-7728-41a0-97BE-14E1CAE36AAE class=\u0022ms-dlgDisable\u0022 width=\u002299\u0025\u0022 tabindex=\u00221\u0022\u003e\u003cparam name=\u0022ListName\u0022 value=\u0022{" + listGuid + "}\u0022\u003e\u003cparam name=\u0022ViewGuid\u0022 value=\u0022{" + viewGuid + "}\u0022\u003e\u003cparam name=\u0022ListWeb\u0022 value=\u0022" + UrlLink + "\u002f_vti_bin\u0022\u003e\u003cparam name=\u0022ListData\u0022 value=\u0022" + ListData + "\u0022\u003e\u003cparam name=\u0022ViewSchema\u0022 value=\u0022" + ViewSchema + "\u0022\u003e\u003cparam name=\u0022ListSchema\u0022 value=\u0022" + ListSchema + "\u0022\u003e\u003cparam name=\u0022ControlName\u0022 value=\u0022STSListControlWPQ3\u0022\u003e\u003cp class=\u0022ms-descriptiontext\u0022\u003eThe Datasheet view of this list cannot be displayed. Please wait while the page is redirected to Standard view. If your list does not appear in a few moments, \u003ca href=\u0022?ShowInGrid=False\u0022 target=_self\u003eopen the list in Standard view\u003c\u002fa\u003e\u003c\u002fp\u003e\u003c\u002fOBJECT\u003e');</script>";

            //                        //Funkcie na ovladanie DataSheetu
            //                        string csScriptFunctions = "<script type='text/javascript'>function WPQ2ShowHideTaskPane() { CoreInvoke('GCShowHideTaskPane', document.STSListControlWPQ3 );} function WPQ2ShowHideTotalsRow() { CoreInvoke('GCShowHideTotalsRow', document.STSListControlWPQ3 );} function WPQ2Refresh() { CoreInvoke('GCRefresh', document.STSListControlWPQ3 );} function WPQ2GridNewRow() { CoreInvoke('GCGridNewRow', document.STSListControlWPQ3 );CoreInvoke('GCActivateAndFocus',document.STSListControlWPQ3);} function WPQ2AddColumn() { CoreInvoke('GCAddNewColumn', document.STSListControlWPQ3 , \"" + spWeb.Url + "\" );} function WPQ2ChangeColumn() { CoreInvoke('GCEditDeleteColumn', document.STSListControlWPQ3 , \"" + spWeb.Url + "\" );} function WPQ2GridNewFolder() { CoreInvoke('GCNewFolder', document.STSListControlWPQ3 );}</script> <script type='text/javascript' for='STSListControlWPQ3' event='onresize'>CoreInvoke('GCOnResizeGridControl',document.STSListControlWPQ3);</script> <script type='text/javascript' for='window' event='onresize'>CoreInvoke('GCWindowResize',document.STSListControlWPQ3);</script> <script type='text/javascript'> function _spBodyOnLoad(){CoreInvoke('GCWindowResize',document.STSListControlWPQ3);CoreInvoke('GCActivateAndFocus',document.STSListControlWPQ3);} </script> <script type='text/javascript' for='document' event='onreadystatechange'>if (document.readyState == 'complete') {if (CoreInvoke('TestGCObject', document.STSListControlWPQ3)) { CoreInvoke('GCActivateAndFocus',document.STSListControlWPQ3);} else { CoreInvoke('GCNavigateToNonGridPage'); } }</script>";

            //                        LiteralControl RenderActiveX = new LiteralControl();
            //                        RenderActiveX.Text = csScript + csScriptFunctions;

            //                        controlParent.Controls.Add(RenderActiveX);
            //                    }
            //                }

            //            }
            //            catch
            //            {
            //                //todo
            //            }
            //        }
            //    }
            //}

            #endregion
        }
Exemplo n.º 36
0
 public SPFeatureInstance(ObjectInstance prototype, SPFeature feature)
     : this(prototype)
 {
     this.m_feature = feature;
 }
        protected override void OnLoad(EventArgs e)
        {
            spFeatureSite = spSite.Features[Definitions.featureGuid];
            if (spFeatureSite != null)
            {
                try
                {
                    SPWeb contextWeb = SPControl.GetContextWeb(this.Context);
                    if ((contextWeb != null) && (contextWeb.UIVersion <= 3))
                    {
                        this._visible = false;
                        return;
                    }

                    Type baseType = this.Page.GetType().BaseType;
                    if ((baseType == typeof(WebPartPage)) || (baseType == typeof(Page)))
                    {
                        Control control = this.findControl(this.Page, "LTViewSelectorMenu");
                        if (control != null)
                        {
                            if (control.Visible)
                            {
                                viewSelector = true;
                            }
                        }


                        this._visible = true;
                    }

                    #region - Ribbon block functions -

                    //Control control = this.findControl(this.Page, "WebPartWPQ2");
                    //if (control != null)
                    //{
                    //    //control.Visible = false;
                    //}

                    //WebPartWPQ2                               STSListControlWPQ2
                    //Control control = this.findControl(this.Page, "Ribbon.List.ViewFormat.Datasheet-Large");

                    //if (control != null)
                    //{
                    //    SPRibbonButton spRibbonDataSheet = control as SPRibbonButton;
                    //    spRibbonDataSheet.Enabled = false;
                    //}

                    //Ribbon.List.ViewFormat.Datasheet
                    //SPList.DisableGridEditing

                    //var menuItems = document.getElementsByTagName('ie:menuitem');
                    //for (i=0; i<menuItems.length; i++)
                    //    if (menuItems[i].text == 'Edit in Datasheet')
                    //        menuItems[i].removeNode();

                    //$("ie\\:menuitem[text='Edit in Datasheet']").each(function()
                    //{     this.hidden = true; });


                    //if this is a System.Web.UI.Page
                    //SPRibbon ribbon = SPRibbon.GetCurrent(this.Page);
                    //ribbon.TrimById("Ribbon.List.Settings.ListPermissions-Large");
                    //STSListControlWPQ2


                    //Control control2 = this.findControl(this.Page, "STSListControlWPQ2");
                    //control2.Visible = false;

                    #endregion
                }
                catch
                {
                    this._visible = false;
                }
            }

            base.OnLoad(e);
        }
Exemplo n.º 38
0
        //Dynamicke metody na vytvorenie vlastnosti
        //protected static GenericSetter set_TemplateContainer_ControlMode = ILUtils.CreateSetMethod(typeof(TemplateContainer), "ControlMode");
        //protected static GenericSetter set_TemplateContainer_FieldName = ILUtils.CreateSetMethod(typeof(TemplateContainer), "FieldName");

        #endregion

        #region - Base Methods -


        protected override void CreateChildControls()
        {
            spFeatureSite = spSite.Features[Definitions.featureGuid];
            if (spFeatureSite != null)
            {
                UserPermission userPermission = new UserPermission();

                this.Controls.Clear();
                if (this.ControlTemplate == null)
                {
                    throw new ArgumentException("Could not find ListFieldIterator control template.");
                }

                for (int i = 0; i < base.Fields.Count; i++)
                {
                    SPField field = base.Fields[i];

                    String fieldName = field.InternalName;

                    if ((!this.IsFieldExcluded(field)))
                    {
                        TemplateContainer child = new TemplateContainer();
                        this.Controls.Add(child);

                        //Dynamicky vytvorenie metod na nastavenie vlastnosti ControlMode a FieldName
                        //set_TemplateContainer_ControlMode(child, SPControlMode.Display);
                        //set_TemplateContainer_FieldName(child, fieldName);

                        SPUser currentUser = SPContext.Current.Web.CurrentUser;

                        //Zistim nastavenie pre field ci ma byt v Display mode
                        SPControlMode fieldMode;
                        if (formMode != SPControlMode.Display)
                        {
                            if (userPermission.GetFieldPermissionForCurrentUser(field, "ReadOnly", formMode, false, currentUser, null))
                            {
                                fieldMode = SPControlMode.Display;
                            }
                            else
                            {
                                fieldMode = formMode;
                            }
                        }
                        else
                        {
                            fieldMode = formMode;
                        }

                        //Zadefinovane vlastnosti ControlMode a FieldName priamo cez reflexiu
                        SetFieldName(child, field.InternalName);
                        SetControlMode(child, fieldMode);

                        this.ControlTemplate.InstantiateIn(child);
                    }
                }
            }
            else
            {
                base.CreateChildControls();
            }
        }
Exemplo n.º 39
0
 public static DirectoryInfo Directory(this SPFeature instance)
 {
     return(new DirectoryInfo(instance.Definition.RootDirectory));
 }
Exemplo n.º 40
0
        protected void InvokeScript(string eventName, SPWebEventProperties properties)
        {
            using (SPSite site = new SPSite(properties.SiteId))
            {
                using (SPWeb web = site.OpenWeb(properties.WebId))
                {
                    SPFeature feature = web.Features[PowerEventReceiversConstants.FeatureId];

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        Runspace runspace = RunspaceFactory.CreateRunspace();

                        runspace.Open();

                        runspace.SessionStateProxy.SetVariable("httpContext", httpContext);
                        runspace.SessionStateProxy.SetVariable("spContext", spContext);
                        runspace.SessionStateProxy.SetVariable("this", this);
                        runspace.SessionStateProxy.SetVariable("properties", properties);
                        runspace.SessionStateProxy.SetVariable("site", site);
                        runspace.SessionStateProxy.SetVariable("web", web);
                        runspace.SessionStateProxy.SetVariable("user", web.SiteUsers[properties.UserLoginName]);

                        string script = feature.Properties[PowerEventReceiversConstants.PowerWebEventReceiverPropNamePrefixScript].Value;

                        try
                        {
                            Pipeline pipe = runspace.CreatePipeline(PowerEventReceiversConstants.PowerEventReceiversPredefinedFunctions);
                            pipe.Invoke();

                            pipe = runspace.CreatePipeline(script);
                            pipe.Invoke();

                            //check if the event's function is defined
                            List <string> functions = PowerEventReceiversHelper.GetFunctions(runspace);
                            if (functions.Contains(eventName.ToLower()) == false)
                            {
                                return;
                            }

                            pipe = runspace.CreatePipeline(eventName);
                            pipe.Invoke();
                            object objProperties = runspace.SessionStateProxy.GetVariable("properties");
                            if (objProperties != null)
                            {
                                if (objProperties is PSObject)
                                {
                                    properties = (SPWebEventProperties)((PSObject)objProperties).BaseObject;
                                }
                                else
                                {
                                    properties = (SPWebEventProperties)objProperties;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                EventLog.WriteEntry(this.GetType().FullName, ex.Message + "\n" + ex.StackTrace, EventLogEntryType.Error);
                            }
                            catch { }

                            properties.Cancel       = true;
                            properties.ErrorMessage = ex.Message;
                        }
                        finally
                        {
                            if (runspace != null && runspace.RunspaceStateInfo.State != RunspaceState.Closed)
                            {
                                runspace.Close();
                                runspace = null;
                            }
                        }
                    });
                }
            }
        }
Exemplo n.º 41
0
        private string DescribeFeatureAndLocation(SPFeature feature)
        {
            string location = LocationInfo.SafeDescribeObject(feature.Parent);

            string msgString = "Faulty Feature found!\n"
                + string.Format("Id: {0}", feature.DefinitionId);
            #if SP2013
            msgString += " Activation=" + feature.TimeActivated.ToString("yyyy-MM-dd");
            #endif
            string solutionInfo = GetFeatureSolutionInfo(feature);
            if (!string.IsNullOrEmpty(solutionInfo))
            {
                msgString += solutionInfo;
            }
            msgString += Environment.NewLine
                + string.Format(" Location: {0}\n", location)
                + string.Format(" Scope: {0}\n", feature.FeatureDefinitionScope)
                + string.Format(" Version: {0}\n", feature.Version)
                + " Should it be removed from the farm?";
            return msgString;
        }