我犯了这么多级别的罪。我希望有人能告诉我一个更好的方法来重写这个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,但仍然解析了主题的字符串。 还有更好的方法吗?

谢谢,

埃里克 -

有帮助吗?

解决方案

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

看看这个例子:

http://www.informit.com/articles/article的.aspx p值= 25339&安培; 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两次解析主题,第一个用“,”解析,然后每个结果字符串用“:”解析。您将获得一个数组列表,如:

首先拆分: 排列 0应用程序:EditStaff_MVC 1环境:开发 2 ServerBoxName:AUST-DDEVMX90FF

第二次(内部)分裂: 排列 0申请 1 EditStaff_MVC

在第二次拆分时,如果第一个值是ServerBoxName,则使用machineName重写第二个值。你去的时候重建字符串。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top