2011-02-03 3 views
2

У меня есть небольшая проблема здесь в отношении модификации файлов web.config в Feature Штамповка (SP2010 [Web Feature Уровень приложений, Активация по умолчанию])Проблема изменения Web.Config в SharePoint

я столкнулся два странных Вопросы

  1. Применяемая модификация типа (добавление дочернего узла) появляется несколько раз в web.config.
  2. При отключении функции, я удаляю модификацию против владельца, она получает модификацию, но Они не удаляются.

Я использую следующий снимок кода во время активации функции.

ModificationEntry[] enries = 
{ 
    new ModificationEntry("someName", "someSection", SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode) 
}; 

    SPWebApplication WebApp = (SPWebApplication)properties.Feature.Parent; 
WebApp.WebConfigModifications.Clear(); 

foreach (ModificationEntry entry in enries) 
{ 
    // CreateModification simply return me SPWebConfigModification 
    SPWebConfigModification configModificationItem = CreateModification(entry, properties.Feature.DefinitionId.ToString()); 
    if (!WebApp.WebConfigModifications.Contains(configModificationItem)) 
    { 
     WebApp.WebConfigModifications.Add(configModificationItem); 
    } 
} 

WebApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications(); 
WebApp.Update(); 

Это то, что я делаю при деактивации функции.

if (webApp != null) 
{ 
    Collection<SPWebConfigModification> collection = webApp.WebConfigModifications; 
    int iStartCount = collection.Count; 

    // Remove any modifications that were originally created by the owner. 
    for (int c = iStartCount - 1; c >= 0; c--) 
    { 
     SPWebConfigModification configMod = collection[c]; 
     if (configMod.Owner == properties.Feature.DefinitionId.ToString()) 
      collection.Remove(configMod); 
    } 

    // Apply changes only if any items were removed. 
    if (iStartCount > collection.Count) 
    { 
     webApp.Update(); 
     webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications(); 
    } 
} 

Прокомментируйте!

+0

где код для модификацииEntry/CreateModification. Кажется, у вас нет переменной «path» (если это не someSection), но тогда где «значение», – djeeg

ответ

2
public sealed class EnableServiceAdapterFeatureReceiver : SPFeatureReceiver 
    { 
     private string psSiteUrl = ""; 

    #region Not Implemented 

    /// <summary> 
    /// Install of feature - not implemented 
    /// </summary> 
    /// <param name="properties"></param> 
    public override void FeatureInstalled(SPFeatureReceiverProperties properties) 
    { 
    } 

    /// <summary> 
    /// Uninstall of feature - not implemented 
    /// </summary> 
    /// <param name="properties"></param> 
    public override void FeatureUninstalling(SPFeatureReceiverProperties properties) 
    { 
    } 

    #endregion 

    #region Base Class Overrides 

    /// <summary> 
    /// Activation of feature - adds modifications into web.config and change masterpage. 
    /// </summary> 
    /// <param name="properties"></param> 
    public override void FeatureActivated(SPFeatureReceiverProperties properties) 
    { 
     using (SPSite site = properties.Feature.Parent as SPSite) 
     { 
      psSiteUrl = site.Url; 

      SPWebApplication webApplication = site.WebApplication; 
      if (webApplication == null) 
      { 
       return; 
      } 

      Modification(webApplication, site.RootWeb.Title.Trim(), true); 

      webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications(); 
      webApplication.Update(); 
     } 
    } 

    /// <summary> 
    /// Deactivation of feature - removes modifications from web.config 
    /// </summary> 
    /// <param name="properties"></param> 
    public override void FeatureDeactivating(SPFeatureReceiverProperties properties) 
    { 

     using (SPSite site = properties.Feature.Parent as SPSite) 
     { 
      SPWebApplication webApplication = site.WebApplication; 
      if (webApplication == null) 
      { 
       return; 
      } 

      Modification(webApplication, site.RootWeb.Title.Trim(), false); 

      webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications(); 
      webApplication.Update(); 
     } 
    } 

    #endregion 

    #region Private Methods 

    /// <summary> 
    /// Modifies web.config file to add/remove SL Service Adapter support for the application 
    /// </summary> 
    /// <param name="webApplication"></param> 
    /// <param name="add"></param> 
    private void Modification(SPWebApplication webApplication, string webTitle, bool add) 
    { 
     // system.serviceModel 
     SPWebConfigModification svcModelConfigSection = new SPWebConfigModification(); 
     svcModelConfigSection.Name = "system.serviceModel"; 
     svcModelConfigSection.Path = "configuration"; 
     svcModelConfigSection.Value = "" + 
            "<system.serviceModel>" + 
            "<bindings>" + 
            "<netTcpBinding>" + 
            "<binding name=\"NetTcpBinding_IAdapterService\" closeTimeout=\"00:01:00\" openTimeout=\"00:01:00\" receiveTimeout=\"00:30:00\" sendTimeout=\"00:30:00\" transactionFlow=\"false\" transferMode=\"Buffered\" transactionProtocol=\"OleTransactions\" hostNameComparisonMode=\"StrongWildcard\" listenBacklog=\"10\" maxBufferPoolSize=\"524288\" maxBufferSize=\"65536\" maxConnections=\"10\" maxReceivedMessageSize=\"10240000\">" + 
            "<readerQuotas maxDepth=\"32\" maxStringContentLength=\"8192\" maxArrayLength=\"16384\" maxBytesPerRead=\"4096\" maxNameTableCharCount=\"16384\" />" + 
            "<reliableSession ordered=\"true\" inactivityTimeout=\"00:10:00\" enabled=\"false\" />" + 
            "<security mode=\"Transport\">" + 
            "<transport clientCredentialType=\"Windows\" protectionLevel=\"None\" />" + 
            "</security>" + 
            "</binding>" + 
            "<binding name=\"tcp_Unsecured\">" + 
            "<security mode=\"None\" />" + 
            "</binding>" + 
            "</netTcpBinding>" + 
            "</bindings>" + 
            "<client>" + 
            "<endpoint address=\"net.tcp://slrsptm03.curie.sl.se/AdapterService/AdapterService\" binding=\"netTcpBinding\" bindingConfiguration=\"tcp_Unsecured\" contract=\"TDIWcfService.IAdapterService\" name=\"NetTcpBinding_IAdapterService\">" + 
            "</endpoint>" + 
            "<endpoint address=\"net.tcp://slrsptm04.curie.sl.se:8890/slHafas\" binding=\"netTcpBinding\" bindingConfiguration=\"tcp_Unsecured\" contract=\"TDIWcfService.IAdapterService\" name=\"HafasControllerService\" />" + 
            "<!-- Endpoint adress for SL Client to MobileAdapter.ServiceController WCF service-->" + 
            "<endpoint address=\"net.tcp://slrsptm04.curie.sl.se:8889/slMobile\" binding=\"netTcpBinding\" bindingConfiguration=\"tcp_Unsecured\" contract=\"TDIWcfService.IAdapterService\" name=\"MobileControllerService\" />" + 
            "</client>" + 
            "<diagnostics>" + 
            "<!-- Enable Message Logging here. -->" + 
            "<!-- log all messages received or sent at the transport or service model levels -->" + 
            "<messageLogging logEntireMessage=\"true\" maxMessagesToLog=\"65000\" logMessagesAtServiceLevel=\"true\" logMalformedMessages=\"true\" logMessagesAtTransportLevel=\"true\" />" + 
            "</diagnostics>" + 
            "</system.serviceModel>"; 
     svcModelConfigSection.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode; 

     // appSettings 
     SPWebConfigModification appSettingsConfigSection = new SPWebConfigModification(); 
     appSettingsConfigSection.Name = "appSettings"; 
     appSettingsConfigSection.Path = "configuration"; 
     appSettingsConfigSection.Value = "" + 
            "<appSettings>" + 
            "<add key=\"MainUrl\" value=\"" + psSiteUrl + "/Planeradtrafik/default.aspx\" />" + 
            "<add key=\"TDIUrl\" value=\"" + psSiteUrl + "/TDI/default.aspx\" />" + 
            "<add key=\"HAFASUrl\" value=\"" + psSiteUrl + "/HAFAS/default.aspx\" />" + 
            "<add key=\"MOBILEUrl\" value=\"" + psSiteUrl + "/MOBILE/default.aspx\" />" + 
            "<add key=\"SessionTimeOut\" value=\"10\" />" + 
            "<add key=\"HitPageUrl\" value=\"" + psSiteUrl + "/hitpage.html\" />" + 
            "<add key=\"SPGroup\" value=\"" + webTitle + " Members;" + webTitle + " Visitors\" />" + 
            "</appSettings>"; 
     appSettingsConfigSection.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode; 

     // connectionStrings 
     SPWebConfigModification connStringConfigSection = new SPWebConfigModification(); 
     connStringConfigSection.Name = "connectionStrings"; 
     connStringConfigSection.Path = "configuration"; 
     connStringConfigSection.Value = "" + 
            "<connectionStrings>" + 
            "<add name=\"SL_Portal_DBConnectionString\" connectionString=\"Data Source=.;Initial Catalog=SL_Portal_DB;Integrated Security=false;user id=sl_portal_db_user;password=[password]\" providerName=\"System.Data.SqlClient\" />" + 
            "</connectionStrings>"; 
     connStringConfigSection.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode; 

     // httpModules 
     SPWebConfigModification httpModuleConfigSection = new SPWebConfigModification(); 
     httpModuleConfigSection.Name = "add[@name='Session']"; 
     httpModuleConfigSection.Path = "configuration/system.web/httpModules"; 
     httpModuleConfigSection.Value = 
      "<add name=\"Session\" type=\"System.Web.SessionState.SessionStateModule\"/>"; 
     httpModuleConfigSection.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode; 

     if (add) 
     { 
      webApplication.WebConfigModifications.Add(svcModelConfigSection); 
      webApplication.WebConfigModifications.Add(appSettingsConfigSection); 
      webApplication.WebConfigModifications.Add(connStringConfigSection); 
      webApplication.WebConfigModifications.Add(httpModuleConfigSection); 
     } 
     else 
     { 
      webApplication.WebConfigModifications.Add(httpModuleConfigSection); 
      webApplication.WebConfigModifications.Remove(connStringConfigSection); 
      webApplication.WebConfigModifications.Remove(appSettingsConfigSection); 
      webApplication.WebConfigModifications.Remove(svcModelConfigSection); 
     } 
    } 

    #endregion 
} 
0

Этот класс обладает всеми необходимыми атрибутами и содержит значение.

ModificationEntry("someName", "someSection", “Value”, SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode) 

Это не проблема, я могу добавить записи конфигурации в файл web.config. Проблемы, как я описал выше.

1

Поскольку вы не разместили код для CreateModification(), я должен угадать, но я думаю, что там что-то не так.

Важно, что свойство Name SPWebConfigModification имеет значение, соответствующее правилу XPath. Предположим, что это то, что вы пытаетесь:

добавить [ключ = «testadd»]

Это выглядит хорошо, но это не так. Так как «ключ» является атрибутом, как «имя» и другие, это правильный путь:

добавить [@ ключ = «testadd»]

Это вызывает множество записей и делает изменение невозможно удалить ,

Смежные вопросы