私は罪を犯した..実行時にWeb.configを書き直す…
質問
私は多くのレベルで罪を犯しました。誰かがこのc#を書き直すためのより良い方法を教えてくれることを望んでいます。
elmahエラーメールの件名の一部を削除し、ボックス名を挿入するために、実行時にweb.configのセクションを変更するタスクが与えられました。
理由は、cmの人々がこれらを一貫して正しく取得することを信頼できないからです。 間違ったボックスでエラーをデバッグするのに時間を無駄にします。
だから私の前のlyいところから書き始めた...
これは、変更しようとしている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として取得しようとしましたが、それでも件名を解析する文字列を作成しました。 より良い方法はありますか?
ありがとう、
エリック-
解決
Factoryメソッドを使用して、実行時にHttpHandlerを動的に作成します。前回使用したHTTPハンドラのセットからELMAHとして必要なHTTPHandlerのカスタムバリアントを作成します。
この例を見てください:
http://www.informit.com/articles/article .aspx?p = 25339&amp; seqNum = 5
他のヒント
実行時に構成XMLを変更することは、希望するものを少しやり過ぎているように思えます。代わりに、ELMAHにすでに組み込まれているフックを使用します。たとえば、ELMAHはエラーメールを送信するとイベントを発生させます。 ELMAH&#8217のカスタマイズを読むことをお勧めします。 ; sエラーメールブログエントリ Scott Mitchell による背景 Global.asax
で Mailing
イベントのハンドラーを記述して、メールが準備された後、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でサブジェクトを2回解析します。最初は&quot;、&quot;で、次に結果の文字列は&quot;&quot;で解析します。次のような配列のリストが表示されます。
最初の分割: アレイ 0アプリケーション:EditStaff_MVC 1環境:開発 2 ServerBoxName:AUST-DDEVMX90FF
2番目の(内部)分割: アレイ 0アプリケーション 1 EditStaff_MVC
2番目の分割で、最初の値がServerBoxNameの場合、machineNameで2番目の値を書き換えます。移動しながら文字列を再構築します。