// DELETE: api/NotasFiscais/id public HttpResponseMessage Delete(int id) { HttpResponseMessage response = null; SqlConnection sqlCon = null; try { sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["MarqDatabaseConnectionString"].ConnectionString); sqlCon.Open(); if (!NotasFiscais.nfValida(id, sqlCon)) { throw new Exception("Nota fiscal não encontrada!"); } //Exclui registros de Notas Fiscais Produtos associados a Nota Fiscal excluída string script = $"DELETE FROM dbo.NotasFicaisProdutos WHERE IdNota = {id}"; SqlCommand sqlCommand = new SqlCommand(script, sqlCon); int linhasAfetadas = 0; try { linhasAfetadas = sqlCommand.ExecuteNonQuery(); if (linhasAfetadas == 0) { throw new Exception("Nenhuma linha afetada!"); } } catch (Exception ex) { throw new Exception($"Falha de comunicação, não foi possível excluir os registros associados a Nota Fiscal: {ex.Message}"); } //Exclui nota fiscal script = $"DELETE FROM dbo.NotasFiscais WHERE Id = {id}"; sqlCommand = new SqlCommand(script, sqlCon); try { linhasAfetadas = sqlCommand.ExecuteNonQuery(); if (linhasAfetadas == 0) { throw new Exception("Nenhuma linha afetada!"); } } catch (Exception ex) { throw new Exception($"Falha de comunicação, não foi possível excluir a Nota Fiscal: {ex.Message}"); } response = Request.CreateResponse(HttpStatusCode.OK, "Nota Fiscal excluída com sucesso!"); } catch (Exception ex) { response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message); } finally { if (sqlCon != null) { sqlCon.Close(); } } return(response); }
// PUT: api/NotasFiscais public HttpResponseMessage Put([FromBody] NotasFiscais value) { HttpResponseMessage response = null; SqlConnection sqlCon = null; try { sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["MarqDatabaseConnectionString"].ConnectionString); sqlCon.Open(); //Checa existência da nota fiscal if (!NotasFiscais.nfValida(value.Id, sqlCon)) { throw new Exception("Nota fiscal não encontrada!"); } //Verifica se chave estrangeira é válida if (!checaExistencia(new string[] { $"{NotasFiscais.ALIAS}.Id = {value.Id}", $"{NotasFiscais.ALIAS}.IdEmpresa = {value.IdEmpresa}" }, $"dbo.NotasFiscais {NotasFiscais.ALIAS}", sqlCon)) { throw new Exception("Id Empresa não é válido!"); } //Checa se nota fiscal é a última enviada pela empresa SqlCommand sqlCommand = new SqlCommand($"SELECT TOP 1 {NotasFiscais.ALIAS}.Id FROM dbo.NotasFiscais {NotasFiscais.ALIAS} " + $"WHERE {NotasFiscais.ALIAS}.IdEmpresa = {value.IdEmpresa} ORDER BY {NotasFiscais.ALIAS}.DataHora DESC", sqlCon); int id = 0; using (SqlDataReader sqlR = sqlCommand.ExecuteReader()) { sqlR.Read(); id = Convert.ToInt32(sqlR[0]); } if (id != value.Id) { throw new Exception("Somente é permitido atualizar a nota fiscal caso esta seja a última nota enviada pela empresa!"); } //Pega objeto a ser atualizado sqlCommand = new SqlCommand($"SELECT {NotasFiscais.ALIAS}.* FROM dbo.NotasFiscais {NotasFiscais.ALIAS}" + $" WHERE {NotasFiscais.ALIAS}.Id = {value.Id}", sqlCon); IDataRecord nf = null; using (SqlDataReader sqlR = sqlCommand.ExecuteReader()) { nf = sqlR.Cast <IDataRecord>().FirstOrDefault(); } //Atualiza List <string> updates = new List <string>(); if (value.DataHora != new DateTime() && !value.DataHora.Equals(Convert.ToDateTime(nf["DataHora"]))) { updates.Add($"{NotasFiscais.ALIAS}.DataHora = '{value.DataHora.ToString("yyyy-dd-MM HH:mm:ss")}'"); } if (value.Total != Convert.ToDecimal(nf["Total"])) { updates.Add($"{NotasFiscais.ALIAS}.Total = {value.Total.ToString(CultureInfo.GetCultureInfo("en-GB"))}"); } sqlCommand = new SqlCommand($"UPDATE {NotasFiscais.ALIAS} SET {string.Join(", ", updates)} " + $"FROM dbo.NotasFiscais {NotasFiscais.ALIAS} WHERE {NotasFiscais.ALIAS}.Id = {value.Id}", sqlCon); int linhasAfetadas = 0; try { linhasAfetadas = sqlCommand.ExecuteNonQuery(); if (linhasAfetadas == 0) { throw new Exception("Nenhuma linha afetada!"); } } catch (Exception ex) { throw new Exception($"Não foi possível atualizar a nota fiscal: {ex.Message}"); } response = Request.CreateResponse(HttpStatusCode.OK, "Nota Fiscal atualizada com sucesso!"); } catch (Exception e) { response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message); } finally { if (sqlCon != null) { sqlCon.Close(); } } return(response); }