简体   繁体   中英

Error in the published site

I have this code to send email for event suppliers:

public ActionResult EnviarFornecedor(int id)
    {


        //  tenho duvida: onde criar variávelGlobal, public !void, void: para melhor visualizacao do fonte
        //  perguntar se devera criar classe  Recebendo parametros (sring strPEmail, ? qParametros): por enquanto aguardar
        //  css3 text-align shadown
        //  mauricio comentou: cores em hexa    senão erro em browsers

        try
        {
            WavebarEntities bd = new WavebarEntities();
            StringBuilder SB_Body = new StringBuilder();
            //SB_Body.Clear();
            Wavebar.Data.Pedidos1 pedidos1 = bd.Pedidos1.Find(id); // Localizar Pedidos com (ID)
            var varItemPedido1 = bd.ItemPedido1.Where(p => p.Pedido_Id == pedidos1.Id); //localizar Itens do Pedido
            var varPedidoFornecedor = new PedidoFornecedor();
            var itempedido = new ItemPedido1();
            int idFornecedorAnterior = 0;
            int i = 0;
            int j = 0;
            foreach (var k in varItemPedido1)
            {
                j++;
            }
            foreach (var varItem in varItemPedido1) // tem um erro dentro do foreach que explode no site publicado
            {
                //var varItensFornecedor1 = db.ItensFornecedor1.FirstOrDefault(i => i.Item_Id == varItem.Item_Id); // Localizar itensFornecedor first (i => i.Item_Id == item.Item_Id)    i   é um comando lambda
                //var varPedidoFornecedor = new PedidoFornecedor(); // cria esta variavel instanciada conforme: ClassPedidoFornecedor
                if (idFornecedorAnterior == 0 || idFornecedorAnterior == varItem.Fornecedor_Id)
                {
                    //cria o inicio do HTML
                    if (Convert.ToString(SB_Body) == "")
                    {
                        SB_Body.Append(motaBody(varItem.FORNECEDORES.FORN_IX_NOME));
                    }

                    varPedidoFornecedor.Descricao = varItem.Produtos1.Descricao;
                    varPedidoFornecedor.Quantidade = varItem.Quantidade.ToString();
                    varPedidoFornecedor.UnidadeMedida = varItem.UnidadesMedida1.Descricao;
                    varPedidoFornecedor.Email = varItem.FORNECEDORES.FORN_EMAIL;
                    itempedido.ValorTotal = varItem.ValorTotal;
                    itempedido.ValorUnitario = varItem.ValorUnitario;
                    //procurar/Relacionado: varItensFornecedor.FORNECEDORES.FORN_EMAIL 
                    //Popula as informações dos produtos do HtmL
                    if (i % 2 != 0)
                    {//Zebrado claro
                        if (i < j - 1)
                        {
                            SB_Body.Append("                <tr>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #c9c9c9;text-align: left; padding-left: 4px; ' >");
                            SB_Body.Append(varPedidoFornecedor.Descricao);     //Produto
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #c9c9c9;text-align: right;' >");
                            SB_Body.Append(varPedidoFornecedor.Quantidade);    //Quantidade
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #c9c9c9;text-align: right;' >");
                            SB_Body.Append(varPedidoFornecedor.UnidadeMedida); //UnidadeMedida
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #c9c9c9;text-align: right;' >");
                            SB_Body.Append(itempedido.ValorUnitario);          //ValorUnitario
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #c9c9c9;text-align: right;padding-right: 4px;' >");
                            SB_Body.Append(itempedido.ValorTotal);             //ValorTotal
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                </tr>");
                        }
                        else // Se final da tabela
                        {
                            SB_Body.Append("                <tr>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #c9c9c9; border-bottom-left-radius: 10px;padding-left: 4px;  ' >");
                            SB_Body.Append(varPedidoFornecedor.Descricao);     //Produto
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #c9c9c9;text-align: right;' >");
                            SB_Body.Append(varPedidoFornecedor.Quantidade);    //Quantidade
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #c9c9c9;text-align: right;' >");
                            SB_Body.Append(varPedidoFornecedor.UnidadeMedida); //UnidadeMedida
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #c9c9c9;text-align: right;' >");
                            SB_Body.Append(itempedido.ValorUnitario);          //ValorUnitario
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #c9c9c9; border-bottom-right-radius: 10px;padding-right: 4px;color: white; ' >");
                            SB_Body.Append(itempedido.ValorTotal);             //ValorTotal
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                </tr>");
                        }
                    }
                    else
                    {//Zebrado Escuro 
                        if (i < j - 1)
                        {
                            SB_Body.Append("                <tr>");
                            SB_Body.Append("                    <td style='height:15px;  background-color: #323232; color: white; padding-left: 4px; ' >");
                            SB_Body.Append(varPedidoFornecedor.Descricao);     //Produto
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #323232; color: white; text-align: right;' >");
                            SB_Body.Append(varPedidoFornecedor.Quantidade);    //Quantidade
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #323232; color: white; text-align: right;' >");
                            SB_Body.Append(varPedidoFornecedor.UnidadeMedida); //UnidadeMedida
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #323232; color: white; text-align: right;' >");
                            SB_Body.Append(itempedido.ValorUnitario);          //ValorUnitario
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px;background-color: #323232; color: white; text-align: right;padding-right: 4px;' >");
                            SB_Body.Append(itempedido.ValorTotal);             //ValorTotal
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                </tr>");
                        }
                        else // Se final da tabela
                        {
                            SB_Body.Append("                <tr>");
                            SB_Body.Append("                    <td style='height:15px;background-color: #323232;color: white; border-bottom-left-radius: 10px;padding-left: 4px;  ' >");
                            SB_Body.Append(varPedidoFornecedor.Descricao);     //Produto
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px;background-color: #323232; color: white; text-align: right;' >");
                            SB_Body.Append(varPedidoFornecedor.Quantidade);    //Quantidade
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #323232; color: white; text-align: right;' >");
                            SB_Body.Append(varPedidoFornecedor.UnidadeMedida); //UnidadeMedida
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px; background-color: #323232; color: white; text-align: right;' >");
                            SB_Body.Append(itempedido.ValorUnitario);          //ValorUnitario
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                    <td style='height:15px;background-color: #323232; color: white;border-bottom-right-radius: 10px; text-align: right;padding-right: 4px;' >");
                            SB_Body.Append(itempedido.ValorTotal);             //ValorTotal
                            SB_Body.Append("                    </td>");
                            SB_Body.Append("                </tr>");
                        }
                    }
                    i++;
                }
                else
                {
                    //Finalizar o HTML e enviar
                    if (Convert.ToString(SB_Body) != "")
                    {
                        string link = "http://localhost:15351/Pedidos/ConfirmarItem?id=0";
                        SB_Body.Append("                    </table>");
                        SB_Body.Append("                    <br><br>");
                        SB_Body.Append("                    <i>Att. Equipe WaveBar</i>");

                        // mark aqui mark: NAO ESTA CERTO LINK
                        SB_Body.Append("<h3> ");
                        SB_Body.Append("    <a href='" + link.Replace("0", Convert.ToString(id)) + "'> ");
                        SB_Body.Append("        Clique para confirmar aceita&ccedil;&atilde;o do pedido");
                        SB_Body.Append("    </a>");
                        SB_Body.Append("</h3>");


                        SB_Body.Append("                </DIV>");
                        SB_Body.Append("            </BODY>");
                        SB_Body.Append("        </HTML>");
                        System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("recursoshumanos@wavebar.com.br", varPedidoFornecedor.Email);
                        SmtpClient client = new SmtpClient();
                        client.EnableSsl = true;
                        client.Port = 587;
                        client.UseDefaultCredentials = true;
                        client.Host = "smtp.wavebar.com.br";
                        mail.Subject = "WebBar: Pedido/Solicitação de Produtos";
                        ContentType mimeType = new System.Net.Mime.ContentType("text/html"); // Add the alternate body to the message.
                        AlternateView alternate = AlternateView.CreateAlternateViewFromString(Convert.ToString(SB_Body), mimeType);
                        mail.AlternateViews.Add(alternate);
                        mail.Body = Convert.ToString(SB_Body);
                        mail.BodyEncoding = System.Text.Encoding.UTF8; // corrige problema acentuacao
                        mail.SubjectEncoding = System.Text.Encoding.UTF8; // corrige problema acentuacao
                        client.Credentials = new System.Net.NetworkCredential("recursoshumanos@wavebar.com.br", "123Mudar!@#");
                        ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
                        client.Send(mail);
                        SB_Body.Clear();
                        SB_Body.Append(motaBody(varItem.FORNECEDORES.FORN_IX_NOME));
                        varPedidoFornecedor.Descricao = varItem.Produtos1.Descricao;
                        varPedidoFornecedor.Quantidade = varItem.Quantidade.ToString();
                        varPedidoFornecedor.UnidadeMedida = varItem.UnidadesMedida1.Descricao;
                        varPedidoFornecedor.Email = varItem.FORNECEDORES.FORN_EMAIL; // procurar/Relacionado: varItensFornecedor.FORNECEDORES.FORN_EMAIL 
                        //Popular as informações dos produtos do HtmL
                        SB_Body.Append("                <tr>");
                        SB_Body.Append("                    <td style='height:15px;background-color: black; color: white; ' >");
                        SB_Body.Append(varPedidoFornecedor.Descricao); //Prod
                        SB_Body.Append("                    </td>");
                        SB_Body.Append("                    <td style='height:15px;background-color: LightBlue; color: black; text-align: right;' >");
                        SB_Body.Append(varPedidoFornecedor.Quantidade); //Qtd
                        SB_Body.Append("                    </td>");
                        SB_Body.Append("                    <td style='height:15px;background-color: LightBlue; color: black; text-align: right;' >");
                        SB_Body.Append(varPedidoFornecedor.UnidadeMedida); //UniMed
                        SB_Body.Append("                    </td>");
                        SB_Body.Append("                    <td style='height:15px;background-color: LightBlue; color: black; text-align: right;' >");
                        SB_Body.Append(itempedido.ValorUnitario);    //Valor Uni
                        SB_Body.Append("                    </td>");
                        SB_Body.Append("                    <td style='height:15px;background-color: LightBlue; color: black; text-align: right;' >");
                        SB_Body.Append(itempedido.ValorTotal);       //VT
                        SB_Body.Append("                    </td>");
                        SB_Body.Append("                </tr>");
                    }
                    else
                    {
                        //return Content("Não foi possível enviar email");
                        TempData["ErrorMsg"] = "Não foi possível enviar email";
                        return RedirectToAction("Index"); // ?funcionou: não testei
                    }
                }
                idFornecedorAnterior = varItem.Fornecedor_Id;

            }// foreach
            if (Convert.ToString(SB_Body) != "")
            {
                string link = "http://localhost:15351/Pedidos/ConfirmarItem?intpId=@p0";
                SB_Body.Append("                    </table>");
                SB_Body.Append("                    <br><br>");
                SB_Body.Append("                    <i>Att. ");
                SB_Body.Append("                    Equipe WaveBar</i>");

                // mark aqui mark: NAO ESTA CERTO LINK
                SB_Body.Append("<h3> ");
                SB_Body.Append("    <a href='" + link.Replace("@p0", Convert.ToString(id)) + "'> ");
                SB_Body.Append("        Clicar: Confirmar aceita&ccedil;&atilde;o do pedido");
                SB_Body.Append("    </a>");
                SB_Body.Append("</h3>");


                SB_Body.Append("                </DIV>");
                SB_Body.Append("            </BODY>");
                SB_Body.Append("        </HTML>");
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("recursoshumanos@wavebar.com.br", varPedidoFornecedor.Email);
                SmtpClient client = new SmtpClient();
                client.EnableSsl = true;
                client.Port = 587;
                client.UseDefaultCredentials = true;
                client.Host = "smtp.wavebar.com.br";
                mail.Subject = "WebBar: Pedido/Solicitação de Produtos";
                ContentType mimeType = new System.Net.Mime.ContentType("text/html"); // Add the alternate body to the message.
                AlternateView alternate = AlternateView.CreateAlternateViewFromString(Convert.ToString(SB_Body), mimeType);
                mail.AlternateViews.Add(alternate);
                mail.Body = Convert.ToString(SB_Body);
                mail.BodyEncoding = System.Text.Encoding.UTF8; // corrige problema acentuacao
                mail.SubjectEncoding = System.Text.Encoding.UTF8; // corrige problema acentuacao
                client.Credentials = new System.Net.NetworkCredential("recursoshumanos@wavebar.com.br", "123Mudar!@#");
                ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
                client.Send(mail);
            }

            //return Content("Email enviado com sucesso");
            TempData["SuccessMsg"] = "Email enviado com sucesso";
            bd.Dispose();
            return RedirectToAction("Index"); // funcionou

        }
        catch (SmtpException) //se não estiver conectado 
        {
            TempData["ErrorMsg"] = "Falha ao enviar email - Verificar conexão da rede";
            return RedirectToAction("Index"); // funcionou
        }
        catch (Exception Eerro)
        {
            //return Content(Convert.ToString("Fracasso ao enviar email - Erro: " + Eerro));
            TempData["ErrorMsg"] = "Falha ao enviar email - Erro: " + Eerro;
            return RedirectToAction("Index"); // funcionou
        }
    }

In the Localhost: ok, works.

But in the published site: i get the following Eerror:(its inside the foreach)

enter image description here

The only problem is that I can't debug, thanks!

var varItemPedido1 = bd.ItemPedido1.Where(p => p.Pedido_Id == pedidos1.Id).
....
foreach (var k in varItemPedido1)
....
foreach (var varItem in varItemPedido1)

These 3 lines of code are the problem. The first specifies the database command but the 2 others will each materialize the collections from the database (so 2 database results). Inside your second foreach you probably also do some database work somewhere otherwise you will not be getting this exception because the database has an active open connection which is being used in the foreach .

The fix is to materialize the list from the database once and because you reference it in 2 places you should do it immediately after the where clause like so.

var varItemPedido1 = bd.ItemPedido1.Where(p => p.Pedido_Id == pedidos1.Id).ToList(); // retrieve the object collection from the database once!

Now when you iterate you are doing it in memory and you can reuse your DbContext inside your loop to do other work.

Finally your first iteration you are doing nothing more than assigning a count. This can be removed and replaced by:

j = varItemPedido1.Count();

Side note

Ensure that all created DbContext instances are disposed of in a using block or in a finally block. This ensures that connections are not left open when failure occurs.

using(WavebarEntities bd = new WavebarEntities())
{
...
}

instead of

WavebarEntities bd = new WavebarEntities();
..
bd.Dispose();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM