private Conexao AddToContext(Conexao context, ConcurrentBag <ControleImpKitItemDto> lista, ControleImpressaoKitNova controleImpressaoKitNova)
        {
            SqlTransaction transaction = null;

            AddTransacao(transaction, context, lista, controleImpressaoKitNova);
            context.Dispose();
            context = new Conexao();
            context.Configuration.AutoDetectChangesEnabled = false;
            return(context);
        }
        public ConcurrentBag <Kitdigital> AddControleImpKitItem(List <int> lstKit, string usuario, ConcurrentBag <Kitdigital> lstKitDigital, RetornoLogProcessamento retornoLogProcessamento, string nomeArquivo)
        {
            Mapeamento.Instance();
            var lista   = new ConcurrentBag <Kitdigital>();
            var context = new Conexao();

            try
            {
                context.Configuration.AutoDetectChangesEnabled = false;

                try
                {
                    var listaDto = new ConcurrentBag <ControleImpKitItemDto>();
                    int cont     = 0;
                    foreach (var kit in lstKit)
                    {
                        var controleImpressaoKitNova = new ControleImpressaoKitNova(BuscarIdPadraoTipoKit(kit), DateTime.Now, usuario, nomeArquivo, lstKitDigital.Where(x => x.tipoKit == kit).Count());

                        using (TransactionScope scope2 = new TransactionScope())
                        {
                            context.Entry(controleImpressaoKitNova).State = EntityState.Added;
                            context.SaveChanges();
                            scope2.Complete();
                        }

                        try
                        {
                            foreach (var item in lstKitDigital.Where(x => x.tipoKit == kit))
                            {
                                TB_REGISTRO_PROCESSAMENTO tb_registro_processamento = new TB_REGISTRO_PROCESSAMENTO(retornoLogProcessamento.idLogProcessamento, "1", null);
                                using (TransactionScope scope5 = new TransactionScope())
                                {
                                    context.Entry(tb_registro_processamento).State = EntityState.Added;
                                    context.SaveChanges();
                                    scope5.Complete();
                                }
                                TB_DETALHE_REGISTRO tb_detalhe_registro = new TB_DETALHE_REGISTRO(tb_registro_processamento.cd_regpss, new Repository <TB_CAMPO>().Get(x => x.nm_cam == "cdc2v").FirstOrDefault().cd_cam, item.externalKey.ToString());
                                using (TransactionScope scope6 = new TransactionScope())
                                {
                                    context.Entry(tb_detalhe_registro).State = EntityState.Added;
                                    context.SaveChanges();
                                    scope6.Complete();
                                }
                                var    controle2Via      = context.Controle2Via.Find(item.externalKey);
                                string verificarErrosKit = verificarErros(item, controle2Via.cdconseg, kit);
                                if (verificarErrosKit.Equals("ok"))
                                {
                                    var dto = Mapper.Map <ControleImpKitItemDto>(controle2Via);
                                    dto.KitDigitalDto = Mapper.Map <KitDigitalDto>(item);
                                    dto.KitDigitalDto.idControleImpressaoKitNova = controleImpressaoKitNova.idControleImpressaoKitNova;
                                    listaDto.Add(dto);
                                    using (TransactionScope scope7 = new TransactionScope())
                                    {
                                        tb_registro_processamento.st_regpss            = "2";
                                        tb_registro_processamento.dt_sitreg            = DateTime.Now;
                                        context.Entry(tb_registro_processamento).State = EntityState.Modified;

                                        //var controle2Via = context.Controle2Via.Find(item.codigoControle);
                                        controle2Via.dtimpressao          = DateTime.Now;
                                        controle2Via.indimp               = "S";
                                        context.Entry(controle2Via).State = EntityState.Modified;
                                        context.SaveChanges();
                                        scope7.Complete();
                                    }
                                    lista.Add(item);
                                }
                                else
                                {
                                    using (TransactionScope scope8 = new TransactionScope())
                                    {
                                        tb_registro_processamento.st_regpss            = "3";
                                        tb_registro_processamento.dt_sitreg            = DateTime.Now;
                                        context.Entry(tb_registro_processamento).State = EntityState.Modified;
                                        context.SaveChanges();

                                        //Alteração na Controle2Via para esta solicitação ser cancelada por erro na geração.
                                        LogControle2Via logControle2Via = new LogControle2Via(controle2Via.cdc2v, controle2Via.cdusuari);
                                        context.Entry(logControle2Via).State = EntityState.Added;
                                        context.SaveChanges();

                                        controle2Via.dtimpressao          = DateTime.Now;
                                        controle2Via.indimp               = "C";
                                        controle2Via.cdusuari             = usuario;
                                        context.Entry(controle2Via).State = EntityState.Modified;
                                        context.SaveChanges();
                                        //Fim Alteração

                                        TB_ERRO_REGISTRO tb_erro_registro = new TB_ERRO_REGISTRO(tb_registro_processamento.cd_regpss, 9999, verificarErrosKit);
                                        context.Entry(tb_erro_registro).State = EntityState.Added;
                                        context.SaveChanges();
                                        scope8.Complete();
                                    }
                                }
                                ++cont;
                                if ((cont % 1000 == 0) || (cont == lstKitDigital.Count()))
                                {
                                    if (listaDto.Count() > 0)
                                    {
                                        context  = AddToContext(context, listaDto, controleImpressaoKitNova);
                                        listaDto = null;
                                        listaDto = new ConcurrentBag <ControleImpKitItemDto>();
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            throw e;
                        }
                        using (TransactionScope scope9 = new TransactionScope())
                        {
                            controleImpressaoKitNova.qtdereg = lista.Where(x => x.tipoKit == kit).Count();
                            context.Entry(controleImpressaoKitNova).State = EntityState.Modified;

                            var tbLogProcessamento = context.TB_LOG_PROCESSAMENTO.Find(retornoLogProcessamento.idLogProcessamento);
                            tbLogProcessamento.dt_fimpss            = DateTime.Now;
                            tbLogProcessamento.qt_totreg            = lstKitDigital.Count();
                            context.Entry(tbLogProcessamento).State = EntityState.Modified;
                            context.SaveChanges();
                            scope9.Complete();
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
                return(lista);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
 private void AddTransacao(SqlTransaction transaction, Conexao context, ConcurrentBag <ControleImpKitItemDto> lista, ControleImpressaoKitNova controleImpressaoKitNova)
 {
     using (context)
     {
         using (TransactionScope scope4 = new TransactionScope(TransactionScopeOption.Required))
         {
             using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["kitDigitalJson"].ConnectionString))
             {
                 connection.Open();
                 using (transaction = connection.BeginTransaction(System.Data.IsolationLevel.Serializable))
                 {
                     try
                     {
                         //foreach (var item in lista)
                         Parallel.ForEach(lista, item =>
                         {
                             SqlCommand cmd2  = new SqlCommand("PR_InserirControleImpKitItem", connection, transaction);
                             cmd2.CommandType = System.Data.CommandType.StoredProcedure;
                             cmd2.Parameters.AddWithValue("@cdconseg", item.cdconseg);
                             cmd2.Parameters.AddWithValue("@cdemi", item.cdemi);
                             cmd2.Parameters.AddWithValue("@cditeseg", item.cditeseg);
                             cmd2.Parameters.AddWithValue("@nrcer", item.nrcer);
                             cmd2.Parameters.AddWithValue("@cdc2v", item.cdc2v);
                             cmd2.Parameters.AddWithValue("@idControleImpressaoKitNova", item.KitDigitalDto.idControleImpressaoKitNova);
                             cmd2.Parameters.AddWithValue("@json", JsonConvert.SerializeObject(Mapper.Map <Kitdigital>(item.KitDigitalDto)));
                             cmd2.ExecuteNonQuery();
                             cmd2.Dispose();
                         });
                         transaction.Commit();
                     }
                     catch (Exception e)
                     {
                         transaction.Rollback();
                         throw new Exception(e.Message);
                     }
                 }
             }
             scope4.Complete();
         }
     }
     transaction.Dispose();
 }