나는 죄를 지었다 .. web.config runtime에서 재 작성… Elmah를 위해
문제
나는 너무 많은 수준에서 죄를 지었다. 누군가 가이 C#을 다시 작성하는 더 좋은 방법을 말해 줄 수 있기를 바랍니다.
런타임에 web.config의 섹션을 수정하여 Elmah 오류 이메일의 피사체를 제거하고 상자 이름을 삽입하는 작업이 주어졌습니다.
그 이유는 우리가 CM 사람들 이이 권리를 일관되게 얻을 수 있다고 믿을 수 없기 때문에 잘못된 상자에 오류를 디버깅하는 오류를 낭비하기 때문입니다.
그래서 나보다 미리 못생성으로 나는 글을 쓰기 시작했다 ...
다음은 Web.config의 섹션입니다. 수정하려고합니다.
<elmah>
<errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/ELMAH" />
<errorMail from="..." to="..."
subject="Application: EditStaff_MVC, Environment:Dev, ServerBoxName: AUST-DDEVMX90FF"
async="true" />
</elmah>
코드는 다음과 같습니다.
private void UpdateElmahErrorEmailSubject( string appPath )
{
string machineName = System.Environment.MachineName;
//System.Collections.IDictionary config = ( System.Collections.IDictionary ) ConfigurationManager.GetSection( "elmah" ); ;
//System.Configuration.Configuration config2 = ( System.Configuration.Configuration ) ConfigurationManager.GetSection( "elmah/errorMail" );
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration( appPath );
if ( config == null )
{
return;
}
ConfigurationSectionGroup sectionGroup = config.GetSectionGroup( "elmah" );
ConfigurationSection section = config.GetSection( "elmah/errorMail" );
// i was not able to get directly to the subject, so I had to write it as xml
string s = section.SectionInformation.GetRawXml();
string search = "ServerBoxName:";
//here is where i started to feel dirty, direct string parsing.
int startIndex = s.IndexOf( search );
int endIndex = s.IndexOf( "\"", startIndex );
string toReplace = s.Substring( startIndex, ( endIndex - startIndex ) );
s = s.Replace( toReplace, search + " " + machineName );
section.SectionInformation.SetRawXml( s );
config.Save();
}
누구든지 문자열 파싱을 돌아 다닐 수 있습니다. 나는 그것을 XML로 얻으려고 노력했지만 여전히 주제를 구문 분석하는 끈을 감았 다. 더 좋은 방법이 있습니까?
감사,
에릭의 뜻
해결책
공장 방법을 사용하여 런타임에 httphandler를 동적으로 만듭니다. 내가 마지막으로 사용했던 것에서 엘마로 필요한 httphandler의 사용자 정의 변형을 만듭니다.
이 예를보십시오 :
http://www.informit.com/articles/article.aspx?p=25339&seqnum=5
다른 팁
런타임에서 구성 XML을 수정하면 원하는대로 약간의 오버 킬처럼 들립니다. 대신 나는 이미 Elmah에 내장 된 후크를 사용합니다. 예를 들어, Elmah는 오류 메일을 보낼 때 이벤트를 시작합니다. 나는 그것을 읽는 것이 좋습니다 Elmah의 오류 이메일을 사용자 정의합니다 블로그 항목 스콧 미첼 일부 배경. 당신은 핸들러를 쓸 수 있습니다 Mailing
당신의 이벤트 Global.asax
메일이 준비되었을 때 제목 줄을 조작하기 위해 Elmah가 그것을 보내기 전에. 나 또한 반점 사용 대상의 관련 부분 Regex
다음 예제에서 알 수 있듯이 (문자열 검색, 인덱싱 및 일부를 직접 대체하는 것보다 더 강력합니다) :
void ErrorMail_Mailing(object sender, Elmah.ErrorMailEventArgs args)
{
args.Mail.Subject =
Regex.Replace(args.Mail.Subject,
@"(?<=\bServerBoxName *: *)([_a-zA-Z0-9-]+)",
Environment.MachineName);
}
XML로로드하고 피사체를 당기고 string.split을 두 번, 첫 번째로 ",", ":": ":"로 구문 분석하십시오. 다음과 같은 배열 목록을 얻을 수 있습니다.
첫 번째 분할 : 배열 0 응용 프로그램 : editstaff_mvc 1 환경 : Dev 2 ServerboxName : AUST-DDEVMX90FF
두 번째 (내부) 분할 : 배열 0 응용 프로그램 1 editstaff_mvc
두 번째 분할에서 첫 번째 값이 ServerBoxName이면 MachineName으로 두 번째 값을 다시 작성하십시오. 갈 때 문자열을 재건하십시오.