如何检查数据库是否有测验,并向系统管理员显示消息

本文关键字:系统管理员 消息 显示 何检查 检查 是否 数据库 | 更新日期: 2023-09-27 18:27:24

我正在开发一个intranet web应用程序,它是一个测验引擎。管理员可以通过点击名为SendingQuiz的页面链接,将测验发送给数据库中的所有用户。一切都很好,但我的问题是,即使数据库中没有测验,电子邮件也会发送给所有的usres那么我应该如何修改这个代码来避免这种情况的发生呢

供您参考,在数据库设计中,我有一个名为Quiz的表,它由以下部分组成:测验ID、标题、说明、IsSent

我现在想要的不是在数据库中没有任何可用测验的情况下发送电子邮件,这会让用户面对转储错误页面,我想让系统检查系统中是否有测验。如果没有,它不应该发送任何内容,并告诉管理员数据库中没有更多的测验那么怎么做呢

我的C#代码:

protected void SendEmail(string toAddresses, string fromAddress, string MailSubject, string MessageBody, bool isBodyHtml)
    {
        SmtpClient sc = new SmtpClient("Mail Server");
        try
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress("Test@CompanyDomain.com", "My Application");
            // In case the mail system doesn't like no to recipients. This could be removed
            //msg.To.Add("Test@CompanyDomain.com");
            msg.Bcc.Add(toAddresses);
            msg.Subject = MailSubject;
            msg.Body = MessageBody;
            msg.IsBodyHtml = isBodyHtml;
            //Response.Write(msg);
            sc.Send(msg);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void SendEmailTOAllUser()
    {
        string connString = "Data Source=localhost''sqlexpress;Initial Catalog=Test;Integrated Security=True";
        using (SqlConnection conn = new SqlConnection(connString))
        {
            var sbEmailAddresses = new System.Text.StringBuilder(2000);
            string quizid = "";
            // Open DB connection.
            conn.Open();
            string cmdText = "SELECT MIN (QuizID) As mQuizID FROM dbo.QUIZ WHERE IsSent <> 1";
            using (SqlCommand cmd = new SqlCommand(cmdText, conn))
            {
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        // There is only 1 column, so just retrieve it using the ordinal position
                        quizid = reader["mQuizID"].ToString();
                    }
                }
                reader.Close();
            }
            string cmdText2 = "SELECT Username FROM dbo.employee";
            using (SqlCommand cmd = new SqlCommand(cmdText2, conn))
            {
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        var sName = reader.GetString(0);
                        if (!string.IsNullOrEmpty(sName))
                        {
                            if (sbEmailAddresses.Length != 0)
                            {
                                sbEmailAddresses.Append(",");
                            }
                            // Just use the ordinal position for the user name since there is only 1 column
                            sbEmailAddresses.Append(sName).Append("@CompanyDomain.com");
                        }
                    }
                }
                reader.Close();
            }
            string cmdText3 = "UPDATE dbo.Quiz SET IsSent = 1 WHERE QuizId = @QuizID";
            using (SqlCommand cmd = new SqlCommand(cmdText3, conn))
            {
                // Add the parameter to the command
                var oParameter = cmd.Parameters.Add("@QuizID", SqlDbType.Int);
                var sEMailAddresses = sbEmailAddresses.ToString();
                string link = "<a href='http://Test/StartQuiz.aspx?testid=" + quizid + "'> Click here to participate </a>";
                string body = @"Good day, <br /><br />
                                <b> Please participate in the new short safety quiz </b>"
                                    + link +
                                    @"<br /><br />
                            ";
                int sendCount = 0;
                List<string> addressList = new List<string>(sEMailAddresses.Split(','));
                StringBuilder addressesToSend = new StringBuilder();
                for (int userIndex = 0; userIndex < addressList.Count; userIndex++)
                {
                    sendCount++;
                    if (addressesToSend.Length > 0)
                        addressesToSend.Append(",");
                    addressesToSend.Append(addressList[userIndex]);
                    if (sendCount == 10 || userIndex == addressList.Count - 1)
                    {
                        SendEmail(addressesToSend.ToString(), "", "Notification of New Weekly Safety Quiz", body, true);
                        addressesToSend.Clear();
                        sendCount = 0;
                    }
                }

                // Update the parameter for the current quiz
                oParameter.Value = quizid;
                // And execute the command
                cmd.ExecuteNonQuery();
            }
            conn.Close();
        }
    }

如何检查数据库是否有测验,并向系统管理员显示消息

你不需要为阅读器使用While,因为你只需要一个quizid,你可以在发送邮件之前使用if子句来检查是否有quizid

protected void SendEmail(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("pssp@aramco.com", "PMOD Safety Services Portal (PSSP)");
            // In case the mail system doesn't like no to recipients. This could be removed
            //msg.To.Add("pssp@aramco.com");
            msg.Bcc.Add(toAddresses);
            msg.Subject = MailSubject;
            msg.Body = MessageBody;
            msg.IsBodyHtml = isBodyHtml;
            //Response.Write(msg);
            sc.Send(msg);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void SendEmailTOAllUser()
    {
        string connString = "Data Source=localhost''sqlexpress;Initial Catalog=psspdbTest;Integrated Security=True";
        using (SqlConnection conn = new SqlConnection(connString))
        {
            var sbEmailAddresses = new System.Text.StringBuilder(2000);
            string quizid = "";
            // Open DB connection.
            conn.Open();
            string cmdText = "SELECT MIN (QuizID) As mQuizID FROM dbo.QUIZ WHERE IsSent <> 1";
            using (SqlCommand cmd = new SqlCommand(cmdText, conn))
            {
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    if(reader.Read())
                    {
                        // There is only 1 column, so just retrieve it using the ordinal position
                        quizid = reader["mQuizID"].ToString();
                    }
                }
                reader.Close();
            }
            string cmdText2 = "SELECT Username FROM dbo.employee";
            using (SqlCommand cmd = new SqlCommand(cmdText2, conn))
            {
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        var sName = reader.GetString(0);
                        if (!string.IsNullOrEmpty(sName))
                        {
                            if (sbEmailAddresses.Length != 0)
                            {
                                sbEmailAddresses.Append(",");
                            }
                            // Just use the ordinal position for the user name since there is only 1 column
                            sbEmailAddresses.Append(sName).Append("@aramco.com");
                        }
                    }
                }
                reader.Close();
            }
            string cmdText3 = "UPDATE dbo.Quiz SET IsSent = 1 WHERE QuizId = @QuizID";
            using (SqlCommand cmd = new SqlCommand(cmdText3, conn))
            {
                // Add the parameter to the command
                var oParameter = cmd.Parameters.Add("@QuizID", SqlDbType.Int);
                var sEMailAddresses = sbEmailAddresses.ToString();
                string link = "<a href='http://pmv/pssp/StartQuiz.aspx?testid=" + quizid + "'> Click here to participate </a>";
                string body = @"Good day, <br /><br />
                                <b> Please participate in the new short safety quiz </b>"
                                    + link +
                                    @"<br /><br />
                            Also, give yourself a chance to gain more safety culture by reading the PMOD Newsletter.
                            <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.
                            ";
                int sendCount = 0;
                List<string> addressList = new List<string>(sEMailAddresses.Split(','));
                StringBuilder addressesToSend = new StringBuilder();
if(!string.IsNullOrEmpty(quizid )){
                for (int userIndex = 0; userIndex < addressList.Count; userIndex++)
                {
                    sendCount++;
                    if (addressesToSend.Length > 0)
                        addressesToSend.Append(",");
                    addressesToSend.Append(addressList[userIndex]);
                    if (sendCount == 10 || userIndex == addressList.Count - 1)
                    {
                        SendEmail(addressesToSend.ToString(), "", "Notification of New Weekly Safety Quiz", body, true);
                        addressesToSend.Clear();
                        sendCount = 0;
                    }
                }
}
                // Update the parameter for the current quiz
                oParameter.Value = quizid;
                // And execute the command
                cmd.ExecuteNonQuery();
            }
            conn.Close();
        }
    }

最简单的解决方案是执行标量查询来确定行数:

SELECT COUNT(*) FROM Quiz

如果这大于零,表中还有测验!

您已经得到了quizid。如果为空,请发送电子邮件给管理员并返回,否则在…之前。。。?

在SendEmailTOAllUser中使用选择最小quizid的块后,您应该检查quizid是否为null,并将代码嵌入到conn.Close()中。