웹 기반 ASP.NET 제안 상자 프로그램에서 관리자는 GridView 컨트롤에 나열된 모든 제안을 소유자의 사용자 이름으로 볼 수 있습니다. GridView의 마지막 열에 상태가 나열됩니다. 관리자가 이러한 제안 중 하나의 상태를 클릭하면 actioned, approved ... 등 가능한 모든 상태를 나열하는 새 팝업 창이 표시됩니다 (asp.net ajax ModalPopUpExtender). 그리고 Admin 이 상태 중 하나를 선택하면 제안 상태가 데이터베이스에서 업데이트됩니다. 모든 것이 잘 작동합니다. 지금 내가하고 싶은 일은 사용자가 추천 한 사람의 상태를 업데이트하고 제안 상태의 업데이트와 관련하여 소유자에게 이메일 알림을 보냅니다.C# Mail :이 함수가 전자 메일을 보낼 수없는 이유는 무엇입니까?
는 이미 메일 기능을 쓴하지만 어떤 이메일을 전송하지 않는 이유를 모르겠어요과 코드를 디버깅하는 동안이 오류가 점점 오전 : 할당되지 않은 지역 변수 '설명'의
사용
데이터베이스의 [설명] 열에 이미 값을 할당했지만 왜이 오류가 발생하는지 알 수 없습니다.
아무도 도와 줄 수 없습니까?
정말 그 업데이트 된 제안의 사용자 이름을 얻는 데 어려움을 겪고 있습니다.
Employee Table: Username, Name...
SafetySuggestionsLog: ID, Title, Description, Username, StatusID
SafetySuggestionsStatus: ID, Status
ASP.NET 코드 :이
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"
width="900px" CssClass="mGrid"
DataSourceID="SqlDataSource1"
OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" CssClass="alt" />
<HeaderStyle Font-Bold = "True" ForeColor="Black" Height="20px"/>
<Columns>
<asp:BoundField DataField="ID" HeaderText="No." InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="DivisionShortcut" HeaderText="Division"
SortExpression="DivisionShortcut" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<%-- This to make status be opened and edited through the Ajax ModalPopUp Window --%>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkSuggestionStatus" Text='<%#Eval("Status")%>'
OnClick="lnkSuggestionStatus_Click">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:HyperLinkField HeaderText="Status"
SortExpression="Status" />--%>
</Columns>
<RowStyle HorizontalAlign="Center" />
</asp:GridView>
<asp:Button runat="server" ID="btnModalPopUp" style="display:none" />
<AjaxToolkit:ModalPopUpExtender ID="modalPopUpExtender1"
runat="server"
TargetControlID="btnModalPopUp"
PopupControlID="pnlPopUp"
BackgroundCssClass="popUpStyle"
PopupDragHandleControlID="panelDragHandle"
OkControlID="OKButton">
</AjaxToolkit:ModalPopUpExtender>
<asp:HiddenField ID="HiddenField1" runat="server"/>
<asp:Panel runat="server" ID="pnlPopUp" CssClass="popUpStyle">
<asp:RadioButtonList ID="StatusList" runat="server" RepeatColumns="1" RepeatDirection="Vertical"
RepeatLayout="Table" TextAlign="Right" DataSourceID="SuggestionStatusDataSource"
DataTextField="Status" DataValueField="ID">
<asp:ListItem id="option1" runat="server" Value="ACTIONED" />
<asp:ListItem id="option2" runat="server" Value="APPROVED" />
<asp:ListItem id="option3" runat="server" Value="PENDING" />
<asp:ListItem id="option4" runat="server" Value="TRANSFERRED" />
</asp:RadioButtonList>
<asp:SqlDataSource ID="SuggestionStatusDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT * FROM [SafetySuggestionsStatus]"></asp:SqlDataSource>
<asp:Button ID="confirmButton" runat="server" Text="Confirm"
OnClientClick="javascript:return confirm('Are you sure you want to send an email notification about the safety suggestion to the owner?')"
OnClick="btnSendStatus_Click" />
<asp:Button ID="OKButton" runat="server" Text="Close" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
코드 숨김 :
protected void lnkSuggestionStatus_Click(object sender, EventArgs e)
{
LinkButton lnkSuggestionStatus = sender as LinkButton;
//var safetySuggestionsId =
//get reference to the row selected
GridViewRow gvrow = (GridViewRow)lnkSuggestionStatus.NamingContainer;
//set the selected index to the selected row so that the selected row will be highlighted
GridView1.SelectedIndex = gvrow.RowIndex;
//This HiddenField used to store the value of the ID
HiddenField1.Value = GridView1.DataKeys[gvrow.RowIndex].Value.ToString();
//ViewState["Username"] = gvrow.Cells[4].Text;
//show the modalPopUp
modalPopUpExtender1.Show();
}
public void btnSendStatus_Click(object sender, EventArgs e) {
//get the ID of the selected suggestion/row
var statusID = StatusList.SelectedValue;
var safetySuggestionsID = HiddenField1.Value;
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdbTest;Integrated Security=True";
//For updating the status of the safety suggestion
string updateCommand = "UPDATE SafetySuggestionsLog SET StatusID= @statusID where [email protected]";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(updateCommand, conn))
{
cmd.Parameters.AddWithValue("@statusID", Convert.ToInt32(statusID));
cmd.Parameters.AddWithValue("@SafetySuggestionsID", Convert.ToInt32(HiddenField1.Value));
cmd.ExecuteNonQuery();
}
//reset the value of hiddenfield
HiddenField1.Value = "-1";
}
GridView1.DataBind();
SendSuggestionStatusToUser(safetySuggestionsID);
}
protected void SendStatusByEmail(string toAddresses, string fromAddress, string MailSubject, string MessageBody, bool isBodyHtml)
{
SmtpClient sc = new SmtpClient("MAIL.Aramco.com");
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("[email protected]", "PMOD Safety Services Portal (PSSP)");
// In case the mail system doesn't like no to recipients. This could be removed
//msg.To.Add("[email protected]");
msg.Bcc.Add(toAddresses);
msg.Subject = MailSubject;
msg.Body = MessageBody;
msg.IsBodyHtml = isBodyHtml;
sc.Send(msg);
}
catch (Exception ex)
{
throw ex;
}
}
protected void SendSuggestionStatusToUser(string suggestionID)
{
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdbTest;Integrated Security=True";
string safetySuggestionID = suggestionID.ToString();
//string username = ViewState["Username"].ToString();
//The following connection is to get the username of the suggestion Owner
//and append (@aramco.com) to it.
using (SqlConnection conn = new SqlConnection(connString))
{
var sbEmailAddresses = new System.Text.StringBuilder(2000);
//initiate the varibles that will be retreived from the database
string username;
string description;
string status;
// Open DB connection.
conn.Open();
string cmdText2 = @"SELECT Username, Description, Status FROM dbo.SafetySuggestionsLog SSL INNER JOIN SafetySuggestionsStatus SSS
ON (SSL.StatusID = SSS.ID) WHERE (SSL.ID = @safetySuggestionID)";
using (SqlCommand cmd = new SqlCommand(cmdText2, conn))
{
cmd.Parameters.AddWithValue("@SafetySuggestionID", Convert.ToInt32(HiddenField1.Value));
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
if (reader.Read())
{
username = reader["Username"].ToString();
description = reader["Description"].ToString();
status = reader["Status"].ToString();
sbEmailAddresses.Append(username).Append("aramco.com");
}
}
var sEMailAddresses = sbEmailAddresses.ToString();
string body = @"Good day, <br /><br />
<b> We just would like to notify you that your following safety suggestion: </b>"
+ description +
@"<br /><br />
has been.
<br /> <br /><br /> <br />
This email was generated using the <a href='http://pmv/pssp/Default.aspx'>PMOD Safety Services Portal (PSSP) </a>.
Please do not reply to this email.
";
SendStatusByEmail(sbEmailAddresses.ToString(), "", "Notification of Your Safety Suggestion", body, true);
sbEmailAddresses.Clear();
reader.Close();
}
conn.Close();
}
}
참고 : 나는 것을 알고 참고로, 나는 다음과 같은 데이터베이스 설계를 나는 여기에 오랜 코드를 게시해서는 안되지만, 나는 당신에게 내 일을 설명하고 싶다. 당신의 도움을 얻을 수 있습니다.
UPDATE :
을 : 내 코드는 NULL로 변수를 할당에 관한 내가 코드를 디버깅 할 때, 나는 독자가 작동하지 않으며 다음을 읽어 보지 않았 발견 수정
if (reader != null)
{
if (reader.Read())
{
username = reader["Username"].ToString();
description = reader["Description"].ToString();
status = reader["Status"].ToString();
sbEmailAddresses.Append(username).Append("@aramco.com");
}
}
UPDATE 2 : SendSuggestionStatusToUser(string suggestionID)
방법에
, 나 브레이크를 추가 다음 줄에 점 :
string safetySuggestionID = suggestionID.ToString();
내가 다음 줄에 중단 점 추가 :
cmd.Parameters.AddWithValue("@safetySuggestionID", Convert.ToInt32(HiddenField1.Value));
을 내가 처음 들어 safetySuggestionID가 전달 된 값의 데이터를 가지고 있음을 발견했다. 그러나 두 번째 경우 (HiddenField1.Value)
의 값은 -1이며 이유는 알 수 없습니다.또한 다음 줄 각각에 중단 점을 추가했습니다.
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
if (reader.Read())
{
username = reader["Username"].ToString();
description = reader["Description"].ToString();
status = reader["Status"].ToString();
sbEmailAddresses.Append(username).Append("@aramco.com");
}
}
디버거가 디버깅하는 동안 디버거를 통과하지 못했습니다. 바로
var sEMailAddresses = sbEmailAddresses.ToString();
으로 이동합니다. 그 이유는 모르겠습니다. 어떤 생각? 저 좀 도와 주 시겠어요?
귀하의 의견에 따라 코드를 수정했지만 여전히 작동하지 않습니다. 내 업데이트 된 질문 좀 봐 주시겠습니까? –
@TechLover - 루핑이 끝나면'sbEmailAddresses.ToString()'은 무엇을 반환합니까? 유효한 이메일 주소 (또는 이메일 주소 집합)처럼 보이나요? – Oded
아무 것도 반환하지 않습니다. –