public ActionResult DeleteConfirmed(int id)
        {
            tp_procedimento tp_procedimento = db.TP_PROCEDIMENTO.Find(id);

            db.TP_PROCEDIMENTO.Remove(tp_procedimento);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public ActionResult Edit(tp_procedimento tp_procedimento)
 {
     if (ModelState.IsValid)
     {
         db.Entry(tp_procedimento).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(tp_procedimento));
 }
        public ActionResult Delete(int id = 0)
        {
            tp_procedimento tp_procedimento = db.TP_PROCEDIMENTO.Find(id);

            if (tp_procedimento == null)
            {
                return(HttpNotFound());
            }
            return(View(tp_procedimento));
        }
        public ActionResult Create(tp_procedimento tp_procedimento)
        {
            if (ModelState.IsValid)
            {
                Int32?intCD_TIPO = db.TP_PROCEDIMENTO.Max(s => (Int32?)s.CD_TIPO);

                if (intCD_TIPO != null)
                {
                    intCD_TIPO++;
                }
                else
                {
                    intCD_TIPO = 1;
                }

                tp_procedimento.CD_TIPO = (Int32)intCD_TIPO;


                try
                {
                    //db.TP_PROCEDIMENTO.Add(tp_procedimento);
                    //db.SaveChanges();
                    string sqlstatament;
                    sqlstatament = string.Format(" INSERT INTO TP_PROCEDIMENTO values({0},\'{1}\',\'{2}\',\'{3}\',\'{4}\', {5}) ",
                                                 tp_procedimento.CD_TIPO,
                                                 tp_procedimento.DES_TIPO,
                                                 tp_procedimento.SOL_NF_OBRIGATORIA,
                                                 tp_procedimento.SOL_NF_CLIENTE_OBRIGATORIA,
                                                 tp_procedimento.ATIVO,
                                                 tp_procedimento.TEMPO_PADRAO
                                                 );

                    db.Database.ExecuteSqlCommand(sqlstatament);
                }
                catch (Exception error)
                {
                    throw new Exception(error.ToString());
                }

                /*db.TP_PROCEDIMENTO.Add(tp_procedimento);
                 *              try
                 * {
                 *  db.SaveChanges(); << aqui da o erro
                 * }
                 * catch (Exception error)
                 * {
                 *  throw new Exception(error.ToString());
                 * }*/

                return(RedirectToAction("Index"));
            }

            return(View(tp_procedimento));
        }
        public ActionResult Save(IEnumerable <HttpPostedFileBase> attachments)
        {
            // The Name of the Upload component is "attachments"
            foreach (var file in attachments)
            {
                // Some browsers send file names with full path. This needs to be stripped.
                var    fileName     = Path.GetFileName(file.FileName);
                var    physicalPath = Path.Combine(Server.MapPath("~/App_Imports"), fileName);
                string exteension   = Path.GetExtension(fileName);
                // The files are not actually saved in this demo
                int counter  = 1;
                int verifica = 0;
                while (System.IO.File.Exists(physicalPath))
                {
                    counter++;
                    physicalPath = Path.Combine(HttpContext.Server.MapPath("~/App_Imports/"),
                                                Path.GetFileNameWithoutExtension(fileName) + counter.ToString() + Path.GetExtension(fileName));
                }
                file.SaveAs(physicalPath);


                DataSet dss = new DataSet();
                string  ConnectionString = "";
                if (exteension == ".xls")
                {
                    ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + physicalPath + ";Extended Properties=Excel 8.0;";
                    verifica         = 1;
                }

                if (exteension == ".xlsx")
                {
                    ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + physicalPath + ";Extended Properties=Excel 12.0;";
                    verifica         = 1;
                }

                if (verifica == 0)
                {
                    throw new Exception("Extensão não suportadaErro ao Salvar");
                }



                using (OleDbConnection conn = new System.Data.OleDb.OleDbConnection(ConnectionString))
                {
                    conn.Open();
                    using (DataTable dtExcelSchema = conn.GetSchema("Tables"))
                    {
                        string           sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                        string           query     = "SELECT * FROM [" + sheetName + "]";
                        OleDbDataAdapter adapter   = new OleDbDataAdapter(query, conn);

                        adapter.Fill(dss, "Items");

                        if (dss.Tables.Count > 0)
                        {
                            if (dss.Tables[0].Rows.Count > 0)
                            {
                                try
                                {
                                    for (int i = 0; i < dss.Tables[0].Rows.Count; i++)
                                    {
                                        tp_procedimento tp_procedimento = new tp_procedimento();
                                        int             id;

                                        // colocar as colunas aqui para importacao
                                        //tentar customizar no .tt
                                        // na index desta controller ao final do arquivo, gerou um codigo padrao para colocar aqui



                                        try
                                        {
                                            db.TP_PROCEDIMENTO.Add(tp_procedimento);
                                        }
                                        catch (Exception erro)
                                        {
                                            throw new Exception(erro.ToString());
                                            //return RedirectToAction("ErroAoSalvar");
                                        }


                                        tp_procedimento = null;
                                    }
                                }
                                catch (Exception erro)
                                {
                                    string err = "<b>Erro Gerado na importação do arquivo, consulte os detalhes para mais informações </b> ";
                                    err += "</br>";
                                    err += _Funcoes.TrataErro(erro);
                                    err += "</br>";
                                    throw new Exception(err.ToString());
                                }

                                try
                                {
                                    db.SaveChanges();
                                    return(RedirectToAction("Index"));
                                }
                                catch (Exception dbEx)
                                {
                                    if (dbEx is System.Data.Entity.Validation.DbEntityValidationException)
                                    {
                                        string errors = "O Arquivo não é válido, verifique as propriedades abaixo para mais detalhes </br> "; // dbEx.EntityValidationErrors.First(); //.ValidationErrors.First();
                                        errors += "<b> Nenhum registro foi gravado.</b> A importação só será possível com o arquivo 100% correto. </br> ";

                                        DbEntityValidationException ex = (DbEntityValidationException)dbEx;
                                        foreach (var validationErrors in ex.EntityValidationErrors)
                                        {
                                            foreach (var validationError in validationErrors.ValidationErrors)
                                            {
                                                errors += string.Format(" A propriedade : <b>{0}</b> não foi validado devido ao erro: <b> {1} </b>", validationError.PropertyName, validationError.ErrorMessage) + "</br>";
                                            }
                                        }
                                        throw new Exception(errors.ToString());
                                    }
                                    else if (dbEx is System.Data.Entity.Infrastructure.DbUpdateException)
                                    {
                                        string err = "<b>Erro Gerado, consulte os detalhes para mais informações </b> ";
                                        err += "</br>";
                                        err += _Funcoes.TrataErro(dbEx);
                                        err += "</br>";
                                        err += dbEx.InnerException.InnerException.ToString();
                                        throw new Exception(err.ToString());
                                    }
                                    else
                                    {
                                        string err = "<b>Erro Gerado, consulte os detalhes para mais informações </b> ";
                                        err += "</br>";
                                        err += _Funcoes.TrataErro(dbEx);
                                        err += "</br>";
                                        throw new Exception(err.ToString());
                                    }
                                }
                            }
                        }
                    }
                }

                // Return an empty string to signify success
            }
            return(Content(""));
        }