Microsoft MVP성태의 닷넷 이야기
.NET Framework: 294. Master web.config 파일을 수정하려면? [링크 복사], [링크+제목 복사],
조회: 17316
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

Master web.config 파일을 수정하려면?

예를 드는 것이 빠를 것 같군요. ^^

ASP.NET Case Study: Lost session variables and appdomain recycles
 - How do you determine what caused an appdomain restart?
; https://www.tessferrandez.com/blog/2006/08/02/aspnet-case-study-lost-session-variables-and-appdomain-recycles.html

위의 글을 보면, 웹 애플리케이션이 Recycle 되는 원인을 이벤트 로그에 남기도록 하는 설정을 추가하는 방법이 설명되어 있습니다. 이를 위해, master web.config 파일, 즉 "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG" 폴더에 있는 web.config 파일을 변경해 주어야하는데요. 대충 다음과 같은 설정이 추가되어야 합니다.

<healthMonitoring>
    <rules>
        ...[생략]...
        <add name="Application Lifetime Events Default" eventName="Application Lifetime Events"
            provider="EventLogProvider" profile="Default" minInstances="1"
            maxLimit="Infinite" minInterval="00:01:00" custom="" />
    </rules>
</healthMonitoring>

그런데, 이런 작업을 수작업으로 해주는 것이 여간 귀찮아야 말이죠. ^^ 코딩으로 자동화해주는 것이 어떨까요?

하지만, 애석하게도 '제가 아는 방법 내에서는' "Master web.config" 파일을 자연스럽게 업데이트 하는 방법은 없었습니다. (혹시 아시는 분은 공개 좀 부탁드립니다. ^^)

엄밀히 말하면, 내용을 업데이트해서 메모리에 들고 있는 것까지는 가능한데 그것을 저장하는 방법이 '멋있지 않습니다.'




하나씩 풀어볼까요? 우선, "master web.config" 파일을 로드해야 하는데요. 다행히 OpenWebConfiguration 메서드를 이용하면 "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG" 경로를 지정해야만 하는 부담감을 덜 수 있습니다.

Configuration config = WebConfigurationManager.OpenWebConfiguration(null);

이렇게 null 인자를 주면 알아서 "master web.config" 파일을 로드해 줍니다. 그 다음부터는 원하는 Config Section을 얻어내서 변경을 가해주면 되는데요. 위의 healthMonitoring 같은 경우에는 아래와 같이 코딩을 해줄 수 있습니다.

ConfigurationSection section = config.GetSection("system.web/healthMonitoring");
if (section == null)
{
    return;
}

HealthMonitoringSection healthSection = section as HealthMonitoringSection;
if (healthSection == null)
{
    return;
}

foreach (RuleSettings rule in healthSection.Rules)
{
    if (rule.Name == "Application Lifetime Events Default" 
        && rule.EventName == "Application Lifetime Events")
    {
        return;
    }
}

RuleSettings ruleSettings = new RuleSettings(
        "Application Lifetime Events Default", "Application Lifetime Events", 
        "EventLogProvider", "Default", 1, Int32.MaxValue, new TimeSpan(0, 1, 0));

healthSection.Rules.Add(ruleSettings);

여기까지 코드를 실행하면, 메모리에 있는 config 인스턴스에만 내용이 변경된 상태입니다. 자... 문제는 이렇게 변경된 내용을 다시 "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG" 경로에 저장해야 한다는 것인데요. 아쉽게도 이 방법이 제공되고 있지 않습니다.

일단, Configuration.Save와 Configuration.SaveAs 메서드가 제공되고 있기는 하지만 각각 문제가 있습니다.

Configuration.Save의 경우에는 "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG" 폴더에 저장을 시도하긴 하지만 파일명을 무작위로 변환해서 저장합니다. 즉, 기존 master web.config 파일을 덮어쓰지 않습니다.

Configuration.SaveAs 파일은 경로를 지정할 수 있기 때문에 master web.config 파일 경로를 넣어줄 수는 있지만, 실제로 실행해 보면 다음과 같은 예외가 발생합니다.

System.ArgumentException was unhandled
  Message=The file name 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config' is invalid because the same file name is already referenced by the configuration hierarchy you have opened.
  Source=System.Configuration
  StackTrace:
       at System.Configuration.MgmtConfigurationRecord.SaveAs(String filename, ConfigurationSaveMode saveMode, Boolean forceUpdateAll)
       at System.Configuration.Configuration.SaveAsImpl(String filename, ConfigurationSaveMode saveMode, Boolean forceSaveAll)
       at System.Configuration.Configuration.SaveAs(String filename, ConfigurationSaveMode saveMode, Boolean forceSaveAll)
       at System.Configuration.Configuration.SaveAs(String filename)
       at ConsoleApplication1.Program.AddOrUpdateAppDomainRestartEventRule() in D:\...\ConsoleApplication1\Program.cs:line 56
       at ConsoleApplication1.Program.Main(String[] args) in D:\...\ConsoleApplication1\Program.cs:line 20
  InnerException: 

따라서, '수작업'으로 File Copy/Delete/Move와 같은 함수를 호출해서 처리해 주어야 합니다.

이 때문에, 제 경우에는 다음과 같이 기존 master web.config 파일을 web.[날짜].config 파일로 백업하고 새롭게 설정한 내용을 web.config 로 쓰는 방식으로 처리를 했습니다.

// 기존 파일을 backup 해놓고.
string dateTime = GetDateTimeAsString(DateTime.Now);
string backupFilePath = Path.ChangeExtension(config.FilePath, dateTime + ".config");
File.Copy(config.FilePath, backupFilePath);

string oldConfigPath = config.FilePath; // oldConfigPath == web.config
File.Delete(config.FilePath + ".candidate");
config.SaveAs(config.FilePath + ".candidate");
File.Delete(oldConfigPath);

File.Move(config.FilePath, oldConfigPath);

첨부된 파일은 위의 코드를 포함한 예제 프로젝트입니다.

문제는 여기서 끝이 아닙니다. .NET 2.0과 .NET 4.0 폴더가 다르고 x86/x64마다 있으므로 그에 대한 처리를 모두 해줄 수 있어야 합니다.

x86 .NET 2.0: C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG
x86 .NET 4.0: C:\Windows\Microsoft.NET\Framework\v4.0.30319\CONFIG

x64 .NET 2.0: C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG
x64 .NET 4.0: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\CONFIG

각각의 개별 exe 파일을 만들던가... 아니면 web.config 파일 자체를 XML로 다루던가... 마지막으로 이전에 써두었던 다음과 같은 방법을 이용해 보는 것도 좋을 것입니다. ^^

x86/x64로 구분된 코드를 포함하는 경우, 다중으로 어셈블리를 만들어야 할까요?
; https://www.sysnet.pe.kr/2/0/1207

설치된 .NET 버전에 민감한 코드를 포함하는 경우, 다중으로 어셈블리를 만들어야 할까요?
; https://www.sysnet.pe.kr/2/0/1178




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 2/21/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13613정성태5/1/202491닷넷: 2253. C# - Video Capture 장치(Camera) 열거 및 지원 포맷 조회파일 다운로드1
13612정성태4/30/202482오류 유형: 902. Visual Studio - error MSB3021: Unable to copy file
13611정성태4/29/2024231닷넷: 2252. C# - GUID 타입 전용의 UnmanagedType.LPStruct - 두 번째 이야기파일 다운로드1
13610정성태4/28/2024331닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/2024420닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/2024796닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024968닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024955닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024947닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024965오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/20241010닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/20241000닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/20241017닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/20241030닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024957닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/20241006닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/20241014닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241129닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241082닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241105닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241104닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241253C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241224닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241095Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241202닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...