Microsoft MVP성태의 닷넷 이야기
.NET Framework: 294. Master web.config 파일을 수정하려면? [링크 복사], [링크+제목 복사],
조회: 24095
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 151  [152]  153  154  155  156  157  158  159  160  161  162  163  164  165  ...
NoWriterDateCnt.TitleFile(s)
1249정성태2/26/201230988.NET Framework: 311. .NET 스레드 콜 스택 덤프 (5) - ICorDebug 인터페이스 사용법 [2]파일 다운로드3
1248정성태2/25/201242474.NET Framework: 310. C#의 Shift 비트 연산 정리파일 다운로드1
1247정성태2/25/201225195.NET Framework: 309. .NET 응용 프로그램에 기본 생성되는 스레드들에 대한 탐구 [1]파일 다운로드1
1246정성태2/25/201224768개발 환경 구성: 145. 한영 변환은 되지만, 정작 한글 입력이 안되는 경우
1245정성태2/25/201235474개발 환경 구성: 144. 윈도우에서도 유닉스처럼 명령행으로 원격 접속하는 방법
1244정성태2/24/201232644.NET Framework: 308. .NET System.Threading.Thread 개체에서 Native Thread Id를 구할 수 있을까? [1]파일 다운로드1
1243정성태2/23/201232605개발 환경 구성: 143. Visual Studio 2010 - .NET Framework 소스 코드 디버깅 - 두 번째 이야기 [1]
1242정성태2/20/201239467VC++: 58. API Hooking - 64비트를 고려해야 한다면? EasyHook! [7]파일 다운로드1
1241정성태2/20/201226306.NET Framework: 307. .NET 4.0 응용 프로그램을 위한 ILMerge
1240정성태2/19/201232568디버깅 기술: 48. C/C++ JNI DLL을 Visual Studio로 디버깅하는 방법 [2]
1239정성태2/19/201224210.NET Framework: 306. 컴퓨터에 실행된 프로세스 중에 닷넷 응용 프로그램임을 알 수 있는 방법 - C# [1]파일 다운로드1
1238정성태2/19/201228100.NET Framework: 305. GetPrivateProfileSection / WritePrivateProfileSection의 C# 버전파일 다운로드1
1237정성태2/18/201232407개발 환경 구성: 142. Windows Embedded POSReady 7 설치 [1]
1236정성태2/17/201228231개발 환경 구성: 141. Windows 2008 R2 RDP 라이선스 서버 설치하는 방법
1235정성태2/16/201226683.NET Framework: 304. Hyper-V의 가상 머신을 C#으로 제어하는 방법 [1]파일 다운로드1
1234정성태2/16/201227099.NET Framework: 303. 원본 파일의 공백/라인을 유지한 체 XML 파일을 저장하는 방법 [1]파일 다운로드1
1233정성태2/16/201233182.NET Framework: 302. supportedRuntime 옵션과 System.BadImageFormatException 예외 [5]
1232정성태2/9/201229062VC++: 57. 웹 브라우저에서 Flash만 빼고 다른 ActiveX를 차단할 수 있을까? [3]파일 다운로드1
1231정성태2/8/201238619VC++: 56. Win32 API 후킹 - Trampoline API Hooking [5]파일 다운로드1
1230정성태2/6/201223963개발 환경 구성: 140. 프로젝트 생성 시부터 "Enable the Visual Studio hosting process" 옵션을 끄는 방법
1229정성태2/4/201228982.NET Framework: 301. P/Invoke의 성능을 높이기 위해 C++/CLI가 선택되려면? [5]파일 다운로드1
1228정성태2/4/201278297.NET Framework: 300. C#으로 만드는 음성인식/TTS 프로그램 [47]파일 다운로드1
1227정성태2/3/201229189.NET Framework: 299. 해당 어셈블리가 Debug 빌드인지, Release 빌드인지 알아내는 방법파일 다운로드1
1226정성태1/28/201270085.NET Framework: 298. 홀 펀칭(Hole Punching)을 이용한 Private IP 간 통신 - C# [15]파일 다운로드3
1225정성태1/24/201225693.NET Framework: 297. 특정 EXE 파일의 실행을 Internet Explorer처럼 "Protected Mode"로 실행하는 방법 [1]파일 다운로드1
1224정성태1/21/201237210개발 환경 구성: 139. 아마존 EC2에 새로 추가된 "1년 무료 Windows 서버 인스턴스"가 있다는데, 직접 만들어 볼까요? ^^ [11]
... 151  [152]  153  154  155  156  157  158  159  160  161  162  163  164  165  ...