SSIS执行链式存储过程

时间:2017-11-14 13:15:35

标签: c# sql-server asynchronous ssis async-await

我正在努力解决我想要执行的SSIS包。 这就是我正在执行存储过程,我从中获取所需的所有提醒并开始使用SqlDataReader循环它们,因为我正在循环提醒我正在发送电子邮件或短信取决于提醒的类型,如果发送电子邮件或短信的结果是成功的,我正在删除提醒。这里的问题是,当我执行包时,它只发送短信/电子邮件而不删除提醒。我正在使用那个让我感到困惑的代码

        public async void Main()
    {
        using (var conn = new SqlConnection("..."))
        {
            List<ReminderData> reminders = new List<ReminderData>();
            using (var command = new SqlCommand("GetRemindersToBeSend", conn)
            {
                CommandType = CommandType.StoredProcedure
            })
            {
                conn.Open();
                var reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (await reader.ReadAsync())
                    {
                        //loop throught the reminders and if the current reminder is send succesfuly delete it ( doesnt work. Why ? )
                        //--------The Part That Puzzles me----------

                        //foreach (var reminder in reminders)
                        //{
                        //    var isSuccessful = false;
                        //    if (((NotificationType)reader["NotificationType"]) == NotificationType.Email)
                        //    {
                        //        isSuccessful = await SendMailMessage(reader["Contact"].ToString(), reader["Title"].ToString(), "Няпомняме за събитие");
                        //    }
                        //    if (((NotificationType)reader["NotificationType"]) == NotificationType.SMS)
                        //    {
                        //        isSuccessful = await SendSmsMessage(reader["Contact"].ToString(), reader["Title"].ToString());
                        //    }
                        //    if (isSuccessful)
                        //    {
                        //        await DeleteReminderAsync((int)reader["ReminderID"], command);
                        //    }
                        //}
                        ReminderData reminder = new ReminderData()
                        {
                            Contact = reader["Contact"].ToString(),
                            NotificationType = (NotificationType)reader["NotificationType"],
                            ReminderID = (int)reader["ReminderID"],
                            Title = reader["Title"].ToString()
                        };
                        reminders.Add(reminder);
                    }
                }
                reader.Close();
                //
                StringBuilder whereClause = new StringBuilder();
                //
                foreach (var reminder in reminders)
                {

                    var isSuccessful = false;
                    if (reminder.NotificationType == NotificationType.Email)
                    {
                        isSuccessful = await SendMailMessage(reminder.Contact, reminder.Title, "Няпомняме за събитие");
                    }
                    if (reminder.NotificationType == NotificationType.SMS)
                    {
                        isSuccessful = await SendSmsMessage(reminder.Contact, reminder.Title);
                    }
                    if (isSuccessful)
                    {
                        //whereClause.Append("ReminderID = " + reminder.ReminderID + " & "); //Creating where clause to use for deletion on one hit -- Why not working ?
                        await DeleteReminderAsync(reminder.ReminderID, command);
                    }
                }
                //await DeleteRemindersAsync(whereClause.ToString(), command); // Query for delete many rows of table -- Why not working ?
            }
        }
        Dts.TaskResult = (int)ScriptResults.Success;
    }

    private async Task<bool> DeleteReminderAsync(int id, SqlCommand procedure)
    {
        try
        {
            procedure.CommandType = CommandType.StoredProcedure;
            procedure.CommandText = "RemoveReminder";
            procedure.Parameters.Add("@reminderID", SqlDbType.Int).Value = id;
            await procedure.ExecuteNonQueryAsync();
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    private async Task<bool> DeleteRemindersAsync(string whereClause, SqlCommand procedure)
    {
        try
        {
            procedure.CommandType = CommandType.Text;
            procedure.CommandText = "Delete from Reminders Where " + whereClause.TrimEnd('&',' ','\n','\r');
            await procedure.ExecuteNonQueryAsync();
            return true;
        }
        catch (Exception)
        {
            return false;
        }

    }

    private async Task<bool> SendMailMessage(string SendTo/*, string From*/, string Subject, string Body/*, string EmailHost, int EmailPort, string EmailUserName, string EmailPassword, bool isEmailSsl, bool UseDefaultCredentials = false*/)
    {
        var Creadentials = new NetworkCredential(Dts.Variables["$Package::EmailUserName"].Value.ToString(), Dts.Variables["$Package::EmailPassword"].Value.ToString());
        int smtpServerPort = int.Parse(Dts.Variables["$Package::EmailPort"].Value.ToString());
        String SmtpServer = Dts.Connections["GmailSMTP"].Properties["SmtpServer"].GetValue(Dts.Connections["GmailSMTP"]).ToString();
        try
        {
            using (SmtpClient mySmtpClient = new SmtpClient(SmtpServer, smtpServerPort)
            {
                Credentials = Creadentials,
                EnableSsl = true
            })
            {
                using (MailMessage htmlMessage = new MailMessage(Creadentials.UserName, SendTo, Subject, Body) { IsBodyHtml = true })
                {
                    await mySmtpClient.SendMailAsync(htmlMessage);
                }
            }
        }
        catch (Exception)
        {
            return false;
        }
        return true;
    }

    private async Task<bool> SendSmsMessage(string SendTo, string Subject, string Encoding = "utf-8")
    {
        string testSms = @"https://bsms.voicecom.bg/smsapi/bsms/sendsms/?sid=1772&id=" + Guid.NewGuid().ToString() + "&msisdn=" + SendTo + "&encoding=" + Encoding + "&text=" + Subject;

        WebRequest request = WebRequest.Create(testSms);
        WebResponse response = await request.GetResponseAsync();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string urlResultText = await reader.ReadToEndAsync();

        return urlResultText == "SEND_OK";
    }

    class ReminderData
    {
        public string Title { get; set; }
        public int ReminderID { get; set; }
        public NotificationType NotificationType { get; set; }
        public string Contact { get; set; }
    }

    enum NotificationType
    {
        SMS = 0,
        Email = 1
    }

另一方面,我决定生成一个where子句来删除所有成功发送的提醒,但这似乎也不起作用。 我做错了什么

0 个答案:

没有答案