【发布时间】:2011-08-24 09:45:31
【问题描述】:
我有以下代码应该执行以下操作:
如果有从 web 服务以 xml 格式返回的记录,则遍历每条记录,获取 ErrorCode、ErrorMessage 和 ID。通过电子邮件发送该信息。然后解析出每条记录并将子元素写入表。问题是它写入相同记录的次数与记录数一样多。我似乎无法弄清楚为什么。电子邮件部分按预期工作。
代码如下:
#region If There Are RecordsInError From Broker Acknowledgement
if (srca.NumberOfResponseRecordsInError != "0")
{
int TotalCount ;
int.TryParse(srca.NumberOfResponseRecordsInError,out TotalCount);
string[] ErrorCode = new string[TotalCount];
string[] ErrorMessage = new string[TotalCount];
string EmailBody = null;
string StateRequestRecordGUID = null;
for (int i = 0; i < TotalCount; i++)
{
//ZJR: Populate the string arrays with Error
ErrorCode[i] = srca.FailedSeparationResponse[i].ErrorOccurrence[0].ErrorCode;
ErrorMessage[i] = srca.FailedSeparationResponse[i].ErrorOccurrence[0].ErrorMessage;
StateRequestRecordGUID = srca.FailedSeparationResponse[i].StateRequestRecordGUID;
//ZJR: Database connection to insert Error Records
SqlConnection conn4 = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=test_BdbCSSQL01;Persist Security Info=False;Integrated Security=SSPI;");
conn4.Open();
string sql = "SELECT * FROM ERROROfSIDESStagingOUT";
SqlDataAdapter da = new SqlDataAdapter(sql, conn4);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr;
dr = dt.NewRow();
dt.Rows.Add(dr);
XDocument doc = XDocument.Load("XmlString.xml");
XNamespace ns = "https://uidataexchange.org/schemas";
var node = doc.Descendants(ns + "EmployerTPASeparationResponse");
using (da)
{
foreach (var param in node.Elements())
{
try
{
if (dr.Table.Columns.Contains(param.Name.LocalName))
{
dr[param.Name.LocalName] = param.Value;
}
//param.NextNode;
}
catch (Exception ee)
{
string asdf = ee.ToString();
}
}
SqlCommandBuilder sb = new SqlCommandBuilder(da);
da.Update(dt);
}
if (conn4 != null)
{
conn4.Close();
}
//ZJR: Build the Email Body
EmailBody = EmailBody + "StateRequestRecordGUID: " + StateRequestRecordGUID + Environment.NewLine + "ErrorCode: " + ErrorCode[i] + " : " + ErrorMessage[i] + Environment.NewLine + Environment.NewLine;
SendEmail mail = new SendEmail();
mail.Send(EmailBody, "Sides Error Event");
}
}
#endregion
【问题讨论】:
-
@Oscar:你真的编辑过什么吗?
-
似乎@Joce 比我早几秒钟重新编写了代码,所以它被
:)覆盖了。该代码在每个开头都有不必要的空格,这使得它的可读性降低。