У меня есть файл parameters.xml, который только частично вызывает замену web.config через setparameters.xml - PullRequest
0 голосов
/ 11 июля 2019

Я начинаю использовать файл parameters.xml для замены значений в файле web.config в WebAPI.У меня был некоторый успех при использовании этого метода, и я смог заменить значения в разделе AppSettings конфигурации, показанной ниже: -

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
    <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
    </configSections>
    <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
        <add key="BusinessApiUrl" value="" />
        <add key="AutoCatImageUrl" value="https://www.autocatplus.co.uk/acweb/images/" />
        <!--<add key="ApiKeyUrl" value="" />-->
        <add key="ApiKeyUrl" value="http://localhost:58059/api/Security" />
        <add key="AppToken" value="CAC71CC7-A3A1-488E-ADD6-AADDEE0" />
        <add key="NewRelic.AppName" value="" />
        <add key="NewRelic.AgentEnabled" value="True" />
        <add key="Nlog.AppName" value="SellerServices" />
        <add key="QuoteExpiryHours" value="365" />
        <add key="LookupRefreshMins" value="60" />
        <add key="VrmUsername" value="" />
        <add key="VrmPassword" value="" />
        <add key="VrmUsername2" value="" />
        <add key="VrmPassword2" value="" />
        <add key="AutoCatUsername" value="" />
        <add key="AutoCatPassword" value="" />
        <add key="orderCatUsername" value="" />
        <add key="orderCatPassword" value="" />
    </appSettings>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
    <variable name="myvar" value="myvalue" />
    <targets>
      <target name="fileTarget" xsi:type="File" fileName="C:\logs\seller.log" layout=" -------------- ${level} (${longdate}) --------------${newline} ${newline} Call Site: ${callsite}${newline} Exception Type: ${exception:format=Type}${newline} Exception Message: ${exception:format=Message}${newline} Stack Trace: ${exception:format=StackTrace}${newline} Additional Info: ${message}${newline}" />
      <target name="databaseTarget" xsi:type="Database" connectionStringName="NLog" commandText="exec dbo.InsertLog                             @level,                             @callSite,                             @type,                             @message,                             @stackTrace,                             @innerException,                             @additionalInfo,                             @machineName,                             @process,                             @appDomain,                             @appId,                             @appGrouping,                             @loggedOnDate">
        <parameter name="@level" layout="${level}" />
        <parameter name="@callSite" layout="${callsite}" />
        <parameter name="@type" layout="${level}" />
        <parameter name="@message" layout="${message}" />
        <parameter name="@stackTrace" layout="${stacktrace}" />
        <parameter name="@innerException" layout="${exception}" />
        <parameter name="@additionalInfo" layout="" />
        <parameter name="@machineName" layout="${machinename}" />
        <parameter name="@process" layout="${processname}" />
        <parameter name="@appDomain" layout="${appdomain}" />
        <parameter name="@appId" layout="0" />
        <parameter name="@appGrouping" layout="0" />
        <parameter name="@loggedOnDate" layout="${date}" />
      </target>
    </targets>
    <rules>
      <logger minlevel="Trace" name="*" writeTo="databaseTarget" />
    </rules>
  </nlog>
    <connectionStrings>
        <add name="SellerServicesApiEntities" connectionString="metadata=res://*/Data.SellerServicesApi.csdl|res://*/Data.SellerServicesApi.ssdl|res://*/Data.SellerServicesApi.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=aaguk.database.windows.net;initial catalog=SellerServicesApi;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
        <add name="AutopartEntities" connectionString="metadata=res://*/Data.Autopart.csdl|res://*/Data.Autopart.ssdl|res://*/Data.Autopart.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=bi.groupauto.co.uk;initial catalog=Autopart_VIEW;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
        <add name="DevelopmentEntities" connectionString="metadata=res://*/AutoPartDevelopment.csdl|res://*/AutoPartDevelopment.ssdl|res://*/AutoPartDevelopment.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=ci.loudauto.co.uk;initial catalog=SellerServicesExtension;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
        <add name="NLog" connectionString="Data Source=aaguk.database.windows.net;Initial Catalog=ECULogging;" providerName="System.Data.SqlClient" />
        <add name="SecurityEntities" connectionString="Server=aaguk.database.windows.net;Database=APISECURITY;" />
        <add name="MasterData" connectionString="Server=aaguk.database.windows.net;Database=MasterData;" />
    </connectionStrings>
    <system.web>
        <compilation debug="true" targetFramework="4.6.1" />
        <httpRuntime targetFramework="4.6.1" />
        <httpModules>
            <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
        </httpModules>
    </system.web>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <modules>
            <remove name="ApplicationInsightsWebTracking" />
            <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
            <remove name="TelemetryCorrelationHttpModule" />
            <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
        </modules>
        <handlers>
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
            <remove name="OPTIONSVerbHandler" />
            <remove name="TRACEVerbHandler" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>
        <httpRedirect enabled="true" destination="/swagger" childOnly="true" />

    </system.webServer>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
                <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="Microsoft.AspNet.TelemetryCorrelation" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-1.0.3.0" newVersion="1.0.3.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="MAMCatalogueSoap">
                    <security mode="Transport" />
                </binding>
                <binding name="MAMCatalogueSoap1" />
                <binding name="SellerServicesSoap" />
                <binding name="VrmLookupSoap">
                    <security mode="Transport" />
                </binding>
                <binding name="VrmLookupSoap1" />
            </basicHttpBinding>
            <customBinding>
                <binding name="MAMCatalogueSoap12">
                    <textMessageEncoding messageVersion="Soap12" />
                    <httpsTransport />
                </binding>
                <binding name="VrmLookupSoap12">
                    <textMessageEncoding messageVersion="Soap12" />
                    <httpsTransport />
                </binding>
            </customBinding>
        </bindings>
        <client>
            <endpoint address="https://ac2.autocatplus.com/mamcat/mamcat.asmx" binding="basicHttpBinding" bindingConfiguration="MAMCatalogueSoap" contract="AutoCatSoap.MAMCatalogueSoap" name="MAMCatalogueSoap" />
            <endpoint address="https://ac2.autocatplus.com/mamcat/mamcat.asmx" binding="customBinding" bindingConfiguration="MAMCatalogueSoap12" contract="AutoCatSoap.MAMCatalogueSoap" name="MAMCatalogueSoap12" />

            <!--New Dev-->
            <endpoint address="http://aagss.mamonline.co.uk:6115/ow-globaltest/sellerservices.asmx"
                binding="basicHttpBinding" bindingConfiguration="SellerServicesSoap"
                contract="MAMSSUK.SellerServicesSoap" name="SellerServicesSoap" />

            <endpoint address="https://vrm.mamsoft.co.uk/vrmlookup/vrmlookup.asmx" binding="basicHttpBinding" bindingConfiguration="VrmLookupSoap" contract="MamVrmSoap.VrmLookupSoap" name="VrmLookupSoap" />
            <endpoint address="https://vrm.mamsoft.co.uk/vrmlookup/vrmlookup.asmx" binding="customBinding" bindingConfiguration="VrmLookupSoap12" contract="MamVrmSoap.VrmLookupSoap" name="VrmLookupSoap12" />
        </client>
    </system.serviceModel>
    <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
            <parameters>
                <parameter value="mssqllocaldb" />
            </parameters>
        </defaultConnectionFactory>
        <providers>
            <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
    </entityFramework>
    <system.web>
    </system.web>
</configuration>
<!--ProjectGuid: CD5EDD27-396C-4E42-AAFC-964F9EE54D57-->

Это основано на использовании следующего файла parameters.xml, показанного ниже, который находит значения в файле web.config и заменяет их значениями по умолчанию, указанными в файле parameters.xml.

Parameters.xml: -

<parameters>
  <parameter name="BusinessApiUrl"
             description="Specify the BusinessApiUrl endpoint"
             defaultValue="__SWAPBUSINESSAPIURL__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;BusinessApiUrl&quot;]/@value" />
  </parameter>
  <parameter name="AutoCatImageUrl"
             description="Specify the AutoCatImageUrl"
             defaultValue="__SWAPAUTOCATIMAGEURL__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;AutoCatImageUrl&quot;]/@value" />
  </parameter>
  <parameter name="ApiKeyUrl"
             description="Specify the security API URL"
             defaultValue="__SWAPAPIKEYURL__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;ApiKeyUrl&quot;]/@value" />
  </parameter>
  <parameter name="AppToken"
             description="Specify the App security based token"
             defaultValue="__SWAPAPPTOKEN__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;AppToken&quot;]/@value" />
  </parameter>
  <parameter name="NewRelic.AppName"
             description="Specify the new relic AppName"
             defaultValue="__SWAPNEWRELICAPPNAME__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;NewRelic.AppName&quot;]/@value" />
  </parameter>
  <parameter name="NewRelic.AgentEnabled"
             description="Specify if the new relic agent is enabled"
             defaultValue="__SWAPNEWRELICAGENTENABLED__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;NewRelic.AgentEnabled&quot;]/@value" />
  </parameter>
  <parameter name="Nlog.AppName"
             description="Specify the Nlog application name"
             defaultValue="__SWAPNLOGAPPNAME__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;Nlog.AppName&quot;]/@value" />
  </parameter>
  <parameter name="QuoteExpiryHours"
             description="Specify the Quote Expiry in hours"
             defaultValue="__SWAPQUOTEEXPIRYHOURS__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;QuoteExpiryHours&quot;]/@value" />
  </parameter>
  <parameter name="LookupRefreshMins"
             description="Specify the lookup refresh in mins"
             defaultValue="__SWAPLOOKUPREFRESHMINS__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;LookupRefreshMins&quot;]/@value" />
  </parameter>
  <parameter name="VrmUsername"
             description="Specify the VrmUsername"
             defaultValue="__SWAPVRMUSERNAME__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;VrmUsername&quot;]/@value" />
  </parameter>
  <parameter name="VrmPassword"
             description="Specify the VrmPassword"
             defaultValue="__SWAPVRMPASSWORD__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;VrmPassword&quot;]/@value" />
  </parameter>
  <parameter name="VrmUsername2"
             description="Specify the VrmUsername2"
             defaultValue="__SWAPVRMUSERNAME2__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;VrmUsername2&quot;]/@value" />
  </parameter>
  <parameter name="VrmPassword2"
             description="Specify the VrmPassword2"
             defaultValue="__SWAPVRMPASSWORD2__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;VrmPassword2&quot;]/@value" />
  </parameter>
  <parameter name="AutoCatUsername"
             description="Specify the AutoCatUsername"
             defaultValue="__SWAPAUTOCATUSERNAME__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;AutoCatUsername&quot;]/@value" />
  </parameter>
  <parameter name="AutoCatPassword"
             description="Specify the AutoCatPassword"
             defaultValue="__SWAPAUTOCATPASSWORD__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;AutoCatPassword&quot;]/@value" />
  </parameter>
  <parameter name="orderCatUsername"
             description="Specifiy the orderCatUsername"
             defaultValue="__SWAPORDERCATUSERNAME__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;orderCatUsername&quot;]/@value" />
  </parameter>
  <parameter name="orderCatPassword"
             description="Specify the orderCatPassword"
             defaultValue="__SWAPORDERCATPASSWORD__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/appSettings/add[@key=&quot;orderCatPassword&quot;]/@value" />
  </parameter>
  <parameter name="minlevel"
             description="Specify the Nlog minimum logging level"
             defaultValue="__SWAPNLOGLEVEL__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/nlog/rules/logger[@writeTo=&quot;databaseTarget&quot;]/@minlevel" />
  </parameter>
</parameters>

Все это прекрасно работает дляна раздел appsettings, на который я нацеливаюсь, пожалуйста, игнорируйте любые ошибки в файле web.config, так как я удалил некоторую конфиденциальную информацию из строк подключения и т. д., но нет проблем со строками подключения или чем-либо еще в этом роде.

Проблема, с которой я сталкиваюсь, связана с разделом конфигурации NLog, в котором я пытаюсь выполнить замену, используя ту же технику, что и для раздела appsettings в файле web.config, но по какой-то причине это не работает.

Из файла parameters.xml, как показано выше, у меня есть раздел ниже, посвященный разделу Nlog в моем файле web.config: -

<parameter name="minlevel"
             description="Specify the Nlog minimum logging level"
             defaultValue="__SWAPNLOGLEVEL__">
    <parameterEntry kind="XmlFile" scope="Web.config"
                    match="/configuration/nlog/rules/logger[@writeTo=&quot;databaseTarget&quot;]/@minlevel" />

И в моем веб-конфигурации у меня естьРаздел Nlog, как показано ниже: -

  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
    <variable name="myvar" value="myvalue" />
    <targets>
      <target name="fileTarget" xsi:type="File" fileName="C:\logs\seller.log" layout=" -------------- ${level} (${longdate}) --------------${newline} ${newline} Call Site: ${callsite}${newline} Exception Type: ${exception:format=Type}${newline} Exception Message: ${exception:format=Message}${newline} Stack Trace: ${exception:format=StackTrace}${newline} Additional Info: ${message}${newline}" />
      <target name="databaseTarget" xsi:type="Database" connectionStringName="NLog" commandText="exec dbo.InsertLog                             @level,                             @callSite,                             @type,                             @message,                             @stackTrace,                             @innerException,                             @additionalInfo,                             @machineName,                             @process,                             @appDomain,                             @appId,                             @appGrouping,                             @loggedOnDate">
        <parameter name="@level" layout="${level}" />
        <parameter name="@callSite" layout="${callsite}" />
        <parameter name="@type" layout="${level}" />
        <parameter name="@message" layout="${message}" />
        <parameter name="@stackTrace" layout="${stacktrace}" />
        <parameter name="@innerException" layout="${exception}" />
        <parameter name="@additionalInfo" layout="" />
        <parameter name="@machineName" layout="${machinename}" />
        <parameter name="@process" layout="${processname}" />
        <parameter name="@appDomain" layout="${appdomain}" />
        <parameter name="@appId" layout="0" />
        <parameter name="@appGrouping" layout="0" />
        <parameter name="@loggedOnDate" layout="${date}" />
      </target>
    </targets>
    <rules>
      <logger minlevel="Trace" name="*" writeTo="databaseTarget" />
    </rules>
  </nlog>

Моя цель - изменить узел

  <logger minlevel="Trace" name="*" writeTo="databaseTarget" />

на

<logger minlevel="__SWAPNLOGLEVEL__" name="*" writeTo="databaseTarget" />

, но по какой-то причине этот узел не являетсяпострадавшие.Я проверил свой Xpath в notepad ++, и он правильно идентифицирует атрибут так же, как идентифицируются атрибуты appsettings, но никаких изменений не происходит.

Я не очень хорошо знаком с процессом веб-развертывания и т. Д., Но все, что у меня естьудалось найти в интернете, кажется, подтверждает, что это должно работать, поэтому любая помощь будет высоко ценится.

...