none
Webconfigmodification using c#

    Question

  • Hi,

    I am trying to update the webconfig using spwebconfigmodification.

    While feature activated event the entry was getting updated, But while deactivation the is not geeting removed. instead it is adding again, if the entry is not already present.

     SPWebApplication webApplication = properties.Feature.Parent as SPWebApplication;
                SPWebConfigModification myModification = new SPWebConfigModification();
                myModification.Path = "configuration/appSettings";
                myModification.Name = @"add[@key='SQLConnectionString']";
    
                myModification.Owner = "UserName";
                myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                myModification.Value = @"<add key='SQLConnectionString' value='Data Source=WEBDV03;Initial Catalog=net_Fa;User Id=sql; password=password@123;' />";
                           webApplication.WebConfigModifications.Add(myModification);
                            webApplication.Update();
                
                            webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();

    On deactivation

     SPWebApplication webApplication =(SPWebApplication) properties.Feature.Parent;
     Collection<SPWebConfigModification> modsCollection = webApplication.WebConfigModifications;
                SPWebConfigModification configModFound = null;
    
                // Find the most recent modification of a specified owner
                int modsCount1 = modsCollection.Count;
                for (int i = modsCount1 - 1; i > -1; i--)
                {
                    if (modsCollection[i].Owner == "UserName")
                    {
                        configModFound = modsCollection[i];
                    }
                }
    
                // Remove it and save the change to the configuration database  
                modsCollection.Remove(configModFound);
               // webApplication.WebConfigModifications.Remove(configModFound);
                webApplication.Update();
    webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();

    Please let me know what was the issue.

    Thanks,

    Sudarsanan K


    • Edited by Sudan12 Friday, November 15, 2013 7:47 AM
    Friday, November 15, 2013 7:46 AM

All replies

  • Try something like this:

                List<SPWebConfigModification> modifications = new List<SPWebConfigModification>();
    
                foreach (SPWebConfigModification modification in webApp.WebConfigModifications)
                {
                    if (modification.Owner == ModificationOwner)
                        modifications.Add(modification);
                }
    
                foreach (SPWebConfigModification modification in modifications)
                {
                    webApp.WebConfigModifications.Remove(modification);
                }
    
                webApp.Update();

    Where ModificationOwner is a const equal to your owner ("UserName").


    Trevor Seward, MCC

    Follow or contact me at...
      

    This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

    Friday, November 15, 2013 3:56 PM
    Moderator
  • Hi ,

    I have tried the above code and still instead of removing the entry it keeps adding if the entry is not available.

    When I debug I am able to reach the remove method and webapplication updated.

    am I missing some thing.

    Thanks,

    Sudan

    Friday, November 15, 2013 6:22 PM
  • Hi,

    According to this post: How to add and remove entries from Web.Config using SPWebConfigModification

    Add code to remove the entry when the Feature is deactivated.

    public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
    
    
          {
          __getSiteURL(properties);
          SPWebApplicationwebApp = SPWebApplication.Lookup(newUri(psSiteUrl));
          try
          {
    RemoveEntries(webApp);
    webApp.Update();                webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
    webApp.WebConfigModifications.Clear();
          }
          catch (Exception ex)
          {
    throw ex;
          }
          }
    
    
    //Remove Entries made to web.config by Owner name “Smartrider”                               private void RemoveEntries(SPWebApplicationwebApp)
          {
           try
                {
    List<SPWebConfigModification>entriesToRemove = newList<SPWebConfigModification>();
    foreach (SPWebConfigModificationconfigModinwebApp.WebConfigModifications)
    {
    if (configMod.Owner == "Pravin")
    {
    entriesToRemove.Add(configMod);
    }
           }
    if (entriesToRemove.Count> 0)
    {
    for (inti = entriesToRemove.Count - 1; i>= 0; i--)
    {
    webApp.WebConfigModifications.Remove(entriesToRemove[i]);
    }
           }
         }
          catch
          {
    throw;
          }
        }
    

    If you need more help of SPWebConfigModification, people in SharePoint development forum would be more professional on this:

    SharePoint 2013 - Development and Programming

    http://social.msdn.microsoft.com/Forums/en-US/home?forum=sharepointdevelopment

    Thanks.


    Tracy Cai
    TechNet Community Support


    Monday, November 18, 2013 6:32 AM
    Moderator
  • Can you please share your entire event receiver code?

    Trevor Seward, MCC

    Follow or contact me at...
      

    This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

    Monday, November 18, 2013 6:33 AM
    Moderator
  •   private string psSiteUrl = "";
            string Owner = "username";
            public override void FeatureActivated(SPFeatureReceiverProperties properties)
            {
                //__getSiteURL(properties);
               // SPWebApplication webApp = SPWebApplication.Lookup(new Uri(psSiteUrl));
                SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
                SPWebService service = SPWebService.ContentService;
                SPWebConfigModification proConfigMod = new SPWebConfigModification();
                proConfigMod.Owner = Owner;
                proConfigMod.Path = "configuration/appSettings";
                proConfigMod.Name = String.Format(@"add [@key='SQLConnectionString'] [@value='Data Source=DV03;Initial Catalog=t_Fa;User Id=sql; password=123;']");
                proConfigMod.Value = String.Format(@"<add key='SQLConnectionString' value='Data Source=DV03;Initial Catalog=t_Fa;User Id=sql; password=123;' />");
                proConfigMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                webApp.WebConfigModifications.Add(proConfigMod);
                webApp.Update();
                service.ApplyWebConfigModifications();
               
            }
        
            // Uncomment the method below to handle the event raised before a feature is deactivated.
            public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
            {
              
                SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
                try
                {
                    RemoveEntries(webApp);
                    webApp.Update();
                    webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                    webApp.WebConfigModifications.Clear();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            public void RemoveEntries(SPWebApplication webApp)
            {
                try
                {
                    List<SPWebConfigModification> entriesToRemove = new List<SPWebConfigModification>();
                    foreach (SPWebConfigModification configMod in webApp.WebConfigModifications)
                    {
                        if (configMod.Owner == Owner)
                        {
                            entriesToRemove.Add(configMod);
                        }
                    }
                    if (entriesToRemove.Count > 0)
                    {
                        for (int i = entriesToRemove.Count - 1; i >= 0; i--)
                        {
                            webApp.WebConfigModifications.Remove(entriesToRemove[i]);
                        }
                    }
                }
                catch
                {
                    throw;
                }
            }
        

    The feature is webapplication scoped.

    Thanks,

    Sudan

    Friday, November 22, 2013 1:23 AM
  • Hi,

    I am still unable to get it workin.

    Please let me know if there is any mistake in the code above.

    Thanks,

    Sudan

    Tuesday, November 26, 2013 6:45 PM
  • Try using this code instead:

            public override void FeatureActivated(SPFeatureReceiverProperties properties)
            {
                var webApplication = properties.Feature.Parent as SPWebApplication;
                ModifyWebConfig(webApplication, false);
            }
    
    
            // Uncomment the method below to handle the event raised before a feature is deactivated.
    
            public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
            {
                var webApplication = properties.Feature.Parent as SPWebApplication;
                ModifyWebConfig(webApplication, true);
            }
    
    
            // Uncomment the method below to handle the event raised after a feature has been installed.
    
            //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
            //{
            //}
    
    
            // Uncomment the method below to handle the event raised before a feature is uninstalled.
    
            public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
            {
                var webApplication = properties.Feature.Parent as SPWebApplication;
                ModifyWebConfig(webApplication, true);
            }
    
            // Uncomment the method below to handle the event raised when a feature is upgrading.
    
            //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
            //{
            //}
    
            private static void ModifyWebConfig(SPWebApplication webApplication, bool remove)
            {
                const string assembly = @"Assembly Fully Qualified Name";
                const string _namespace = @"Namespace name";
    
                var modification = new SPWebConfigModification
                {
                    Owner = "Owner Name",
                    Sequence = 0,
                    Path = "configuration/System.Workflow.ComponentModel.WorkflowCompiler/authorizedTypes/targetFx[@version='v4.0']",
                    Name =
                        string.Format(
                            "authorizedType[@Assembly='{0}'][@Namespace='{1}'][@TypeName='*'][@Authorized='True']", assembly,
                            _namespace),
                    Value =
                        string.Format("<authorizedType Assembly='{0}' Namespace='{1}' TypeName='*' Authorized='True'/>",
                                      assembly, _namespace)
                };
    
                if (!remove)
                {
                    webApplication.WebConfigModifications.Add(modification);
                }
                else
                {
                    webApplication.WebConfigModifications.Remove(modification);
                }
    
                webApplication.Update();
                webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }

    Adjust as required to meet your needs.

    The next step would be to debug the the feature deactivating process to see what is happening.


    Trevor Seward, MCC

    Follow or contact me at...
      

    This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

    Tuesday, November 26, 2013 8:18 PM
    Moderator