locked
Ajax loading with text showing counter/text RRS feed

  • Question

  • User539757411 posted

    Hi,

    I'm developing an application that sends bulk mails and i'm using AsyncCallback, so it sends one email every 2 seconds. 
    So what I need is a loading on top of the screen (modal maybe?), and a counter incrementing for every email it sends, something like a counter.

    Thanks in advance!

    Thursday, March 9, 2017 2:24 PM

All replies

  • User-707554951 posted

    Hi xandeq.

    I'm developing an application that sends bulk mails and i'm using AsyncCallback, so it sends one email every 2 seconds

    would you please provide more detailed description about the way you send the mail?

    you could post the code you use.

    and a counter incrementing for every email it sends, something like a counter.

    As general. the method we create a counter is set a  initial value. add 1 after a email sent successfully. then display the value in page.

    As I am not clear your code. so, i didn't  tell you the concrete way now.

    Best regards

    Cathy

    Friday, March 10, 2017 8:09 AM
  • User-1716253493 posted

    You can create app console that read data from database, send email then update send status every minute for example.

    Then in web page, periodicaly check the status from db.

    Friday, March 10, 2017 8:34 AM
  • User539757411 posted

    FRONT END:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="NovoEmailExterno.aspx.cs" Inherits="SistemaEnvioEmails.NovoEmailExterno" %>
    
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
        <h4 class="text-center">NOVA MENSAGEM</h4>
        <div class="row form-group">
            <div class="col-md-12">
                <h4>Escolha se quer enviar para um único destinatário ou um grupo selecionando uma das opções abaixo:</h4>
            </div>
        </div>
        <div class="row form-group">
            <asp:UpdatePanel ID="upEscolhaTipoEnvio" Mode="Conditional" runat="server">
                <ContentTemplate>
                    <div class="col-sm-6">
                        <asp:RadioButton ID="rbDestinatarioGrupo" runat="server" GroupName="rblDestinatario" CssClass="" OnCheckedChanged="rbDestinatarioGrupo_CheckedChanged" AutoPostBack="True"></asp:RadioButton>
                        <label for="to" class="col-sm-6 control-label">Para:</label>
                        <%--<asp:TextBox ID="txtNovoEmail" runat="server" CssClass="form-control select2-offscreen" />--%>
                        <asp:DropDownList ID="ddlCargo" runat="server" CssClass="form-control select2-offscreen" AutoPostBack="True" OnSelectedIndexChanged="ddlCargo_SelectedIndexChanged" Enabled="False">
                        </asp:DropDownList>
                        <p>
                            TOTAL:
                            <asp:Label ID="lblContadorEmailsExternos" runat="server" Font-Bold="True" ForeColor="#CC3300" />
                            e-mails
                        </p>
                    </div>
                    <div class="col-sm-6">
                        <asp:RadioButton ID="rbDestinatarioUnico" runat="server" GroupName="rblDestinatario" CssClass="" OnCheckedChanged="rbDestinatarioUnico_CheckedChanged" AutoPostBack="True"></asp:RadioButton>
                        <label for="to" class="col-sm-6 control-label">Para:</label>
                        <asp:TextBox ID="txtNovoEmail" runat="server" CssClass="form-control select2-offscreen" Enabled="False" />
                        <asp:RequiredFieldValidator ID="rfvEmail" runat="server"
                            ErrorMessage="*" ControlToValidate="txtNovoEmail"
                            ValidationGroup="vgSubmit" ForeColor="Red"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator2"
                            runat="server" ErrorMessage="Digite um e-mail válido"
                            ValidationGroup="vgSubmit" ControlToValidate="txtNovoEmail"
                            CssClass="requiredFieldValidateStyle"
                            ForeColor="Red"
                            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
                        </asp:RegularExpressionValidator>
                    </div>
                </ContentTemplate>
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="rbDestinatarioGrupo" EventName="CheckedChanged" />
                    <asp:AsyncPostBackTrigger ControlID="rbDestinatarioUnico" EventName="CheckedChanged" />
                    <asp:AsyncPostBackTrigger ControlID="ddlCargo" EventName="SelectedIndexChanged" />
                </Triggers>
            </asp:UpdatePanel>
        </div>
        <div class="row form-group">
            <label for="bcc" class="col-sm-1 control-label">Assunto:</label>
            <div class="col-sm-11">
                <asp:TextBox ID="txtNovoAssunto" runat="server" CssClass="form-control select2-offscreen" />
            </div>
        </div>
        <div class="row form-group">
            <label for="cc" class="col-sm-1 control-label">Texto:</label>
            <div class="col-sm-11">
                <asp:TextBox ID="txtNovoMensagem" runat="server" Width="100%" Height="500" />
                <ajaxToolkit:HtmlEditorExtender ID="txtNovoMensagem_HtmlEditorExtender" runat="server" Enabled="True" TargetControlID="txtNovoMensagem" DisplaySourceTab="True" EnableSanitization="False" OnImageUploadComplete="ajaxFileUpload_OnUploadComplete">
                    <Toolbar>
                        <ajaxToolkit:Undo />
                        <ajaxToolkit:Redo />
                        <ajaxToolkit:Bold />
                        <ajaxToolkit:Italic />
                        <ajaxToolkit:Underline />
                        <ajaxToolkit:StrikeThrough />
                        <ajaxToolkit:Subscript />
                        <ajaxToolkit:Superscript />
                        <ajaxToolkit:JustifyLeft />
                        <ajaxToolkit:JustifyCenter />
                        <ajaxToolkit:JustifyRight />
                        <ajaxToolkit:JustifyFull />
                        <ajaxToolkit:InsertOrderedList />
                        <ajaxToolkit:InsertUnorderedList />
                        <ajaxToolkit:CreateLink />
                        <ajaxToolkit:UnLink />
                        <ajaxToolkit:RemoveFormat />
                        <ajaxToolkit:SelectAll />
                        <ajaxToolkit:UnSelect />
                        <ajaxToolkit:Delete />
                        <ajaxToolkit:Cut />
                        <ajaxToolkit:Copy />
                        <ajaxToolkit:Paste />
                        <ajaxToolkit:BackgroundColorSelector />
                        <ajaxToolkit:ForeColorSelector />
                        <ajaxToolkit:FontNameSelector />
                        <ajaxToolkit:FontSizeSelector />
                        <ajaxToolkit:Indent />
                        <ajaxToolkit:Outdent />
                        <ajaxToolkit:InsertHorizontalRule />
                        <ajaxToolkit:HorizontalSeparator />
                        <ajaxToolkit:InsertImage />
                    </Toolbar>
                </ajaxToolkit:HtmlEditorExtender>
            </div>
        </div>
        <div class="row form-group pull-right col-md-6">
            <asp:Button ID="btnEnviar" Text="Enviar" runat="server" CssClass="btn btn-success" OnClick="btnEnviar_Click" />
            <asp:Button ID="btnCancelar" Text="Cancelar" runat="server" CssClass="btn btn-danger" OnClick="btnCancelar_Click" />
        </div>
    </asp:Content>
    

    BACK END:

    private void EnviarEmailExterno(string assunto, string corpo)
            {
                try
                {
                    using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbSCIConnectionString"].ConnectionString))
                    {
                        // Open your connection
                        sqlConnection.Open();
    
                        // Create a SQL Command to execute
                        string parametroCargo = string.Empty;
                        if(ddlCargo.SelectedIndex > 0)
                            parametroCargo = " and funcionario.cdcargo = " + ddlCargo.SelectedValue;
    
                        // top 3 for tests
                        string sqlQuery = @"select top 3 cdmatricula, max(cdmatricula) as matricula, max(sqcontrato) as contrato, max(nmpessoa) as nome, max(dscargo) as cargo, max(funcionario.cdcargo) as codcargo, max(email) as email, max(emailpessoal) as emailpessoal
                                                        from funcionario, pessoa , cargo 
                                                        where funcionario.cdpessoa = pessoa.cdpessoa and
                                                        funcionario.cdcargo = cargo.cdcargo 
                                                        and cddesligamento = 0 and (email <> '' or EmailPessoal  <> '')
                                                        and (email not like '%@vilavelha.es.gov%' or EmailPessoal not like '%@vilavelha.es.gov%')
                                                        " + parametroCargo +
                                                        @" group by cdmatricula
                                                        order by cdmatricula";
    
                        using (SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection))
                        {
                            // Execute your query into a datareader and read through your e-mail values
                            using (SqlDataReader sqlReader = sqlCommand.ExecuteReader())
                            {
                                string corpoEnviar = string.Empty;
                                string para = string.Empty;
    
                                using (StreamReader reader = new StreamReader(Server.MapPath("~/email.html")))
                                {
                                    corpoEnviar = reader.ReadToEnd();
                                }
    
                                corpoEnviar = corpoEnviar.Replace("{Corpo}", corpo);
                                corpoEnviar = corpoEnviar.Replace("{Data}", DateTime.Now.ToString("dd/MM/yyyy HH:mm"));
    
                                // While there are records, read
                                while (sqlReader.Read())
                                {
                                    corpoEnviar = corpoEnviar.Replace("{Nome}", sqlReader["nome"].ToString());
    
                                    if (!sqlReader["email"].ToString().Contains("@vilavelha.es.gov.br") && !string.IsNullOrWhiteSpace(sqlReader["email"].ToString()))
                                    {
                                        para = sqlReader["email"].ToString();
                                    }
                                    else if (!sqlReader["emailpessoal"].ToString().Contains("@vilavelha.es.gov.br") && !string.IsNullOrWhiteSpace(sqlReader["emailpessoal"].ToString()))
                                    {
                                        para = sqlReader["emailpessoal"].ToString();
                                    }
                                    else
                                    {
                                        throw new Exception("Funcionário não possui e-mail cadastrado. NOME: " + sqlReader["nome"].ToString() + " - MATRICULA: " + sqlReader["cdmatricula"].ToString());
                                    }
    
                                    corpoEnviar = corpoEnviar.Replace("{Nome}", sqlReader["nome"].ToString());
    
                                    MailMessage mensagem = new MailMessage("pshml@vilavelha.es.gov.br", para, assunto, corpoEnviar);
                                    mensagem.From = new MailAddress("pshml@vilavelha.es.gov.br", "Sistema de Envio de Emails da PMVV");
                                    mensagem.IsBodyHtml = true;
    
                                    AsyncMethodCaller caller = new AsyncMethodCaller(SendMailInSeperateThread);
                                    AsyncCallback callbackHandler = new AsyncCallback(AsyncCallback);
                                    caller.BeginInvoke(mensagem, callbackHandler, null);
    
                                }
                            }
                        }
    
                        sqlConnection.Close();
                    }
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "Erro", "alert('" + ex.Message + "');", true);
                }
            }
    
    protected void HtmlEditorExtender1_ImageUploadComplete(object sender, AjaxFileUploadEventArgs e)
            {
                try
                {
                    string fullpath = Server.MapPath("~/envios/") + e.FileName;
                    var ajaxFileUpload = (AjaxFileUpload)sender;
                    //HtmlEditorExtender1.AjaxFileUpload.SaveAs(fullpath);
                    ajaxFileUpload.SaveAs(fullpath);
                    e.PostedUrl = Page.ResolveUrl("~/envios/" + e.FileName);
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "Erro", "alert('" + ex.Message + "');", true);
                }
            }
    
            private delegate void AsyncMethodCaller(MailMessage message);
    
            private void SendMailInSeperateThread(MailMessage mensagem)
            {
                try
                {
                    string emailUsuario = WebConfigurationManager.AppSettings["emailUsuario"].ToString();
                    string emailSenha = WebConfigurationManager.AppSettings["emailSenha"].ToString();
                    string emailServidor = WebConfigurationManager.AppSettings["emailServidor"].ToString();
                    string emailPorta = WebConfigurationManager.AppSettings["emailPorta"].ToString();
    
                    NetworkCredential cred = new NetworkCredential(emailUsuario, emailSenha);
                    string emailServidorNome = (emailServidor + "," + emailPorta);
    
                    SmtpClient mailClient = new SmtpClient(emailServidorNome);
                    mailClient.EnableSsl = false;
                    mailClient.Timeout = 2000;
                    mailClient.Host = emailServidor;
                    mailClient.UseDefaultCredentials = false;
                    mailClient.Credentials = cred;
                    mailClient.Send(mensagem);
                    mensagem.Dispose();
    
                    // If you have a flag checking to see if an email was sent, set it here
                    // Pass more parameters in the delegate if you need to...
                }
                catch (Exception ex)
                {
                    // This is very necessary to catch errors since we are in
                    // a different context & thread
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "Erro", "alert('" + ex.Message + "');", true);
                }
            }
    
            private void AsyncCallback(IAsyncResult ar)
            {
                try
                {
                    AsyncResult result = (AsyncResult)ar;
                    AsyncMethodCaller caller = (AsyncMethodCaller)result.AsyncDelegate;
                    caller.EndInvoke(ar);
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "Erro", "alert('" + ex.Message + "');", true);
                }
            }
    

    If you can´t understand, please ask.

    Thanks!

    Monday, March 20, 2017 6:15 PM