1

我在很多层面上都犯了罪。我希望有人能告诉我一个更好的方法来重写这个 c#。

我的任务是在运行时修改 web.config 的一部分,以删除 elmah 错误电子邮件的一部分主题并插入框名称。

原因是我们不能相信我们的厘米人员能够始终如一地做到这些,因此我们浪费时间在错误的盒子上调试错误。

因此,面对眼前的丑陋,我开始写作……

这是我要修改的 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 获取,但仍然以字符串解析主题结束。有没有更好的办法?

谢谢,

埃里克-

4

3 回答 3

3

使用 Factory 方法在运行时动态创建 HttpHandler。根据我上次使用的一组 HTTP 处理程序,创建您需要作为 ELMAH 的 HTTPHandler 的自定义变体。

看这个例子:

http://www.informit.com/articles/article.aspx?p=25339&seqNum=5

于 2009-07-30T21:47:07.220 回答
3

在运行时修改配置 XML 听起来有点矫枉过正。相反,我会使用已经内置在 ELMAH 中的钩子。例如,ELMAH 在发送错误邮件时触发事件。我建议阅读Scott Mitchell撰写的自定义 ELMAH 的错误电子邮件博客文章了解一些背景知识。您可以为您的事件编写一个处理程序,以便在准备好邮件但在 ELMAH 发送之前操作主题行。我还将使用以下示例中所示的方法修补主题的相关部分(它比自己搜索字符串、索引和替换部分更健壮):MailingGlobal.asaxRegex

void ErrorMail_Mailing(object sender, Elmah.ErrorMailEventArgs args)
{
    args.Mail.Subject = 
        Regex.Replace(args.Mail.Subject, 
                      @"(?<=\bServerBoxName *: *)([_a-zA-Z0-9-]+)", 
                      Environment.MachineName);
}
于 2014-04-30T22:16:54.203 回答
1

将其加载为 XML 并拉取主题,然后使用 String.Split 解析主题两次,第一次使用“,”,然后每个结果字符串使用“:”。您将获得一个数组列表,例如:

第一次拆分:数组 0 应用程序:EditStaff_MVC 1 环境:Dev 2 ServerBoxName:AUST-DDEVMX90FF

第二个(内部)拆分:Array 0 Application 1 EditStaff_MVC

在第二次拆分中,如果第一个值是 ServerBoxName,则用您的 machineName 重写第二个值。随时重建字符串。

于 2009-07-30T22:12:00.273 回答