예제 #1
0
        /*/// <summary>
         * /// Adiciona nova TbEmpresa
         * /// </summary>
         * /// <param name="param"></param>
         * /// <returns></returns>
         * public static string Add(string token, tbEmpresa param)
         * {
         *  try
         *  {
         *      _db.tbEmpresas.Add(param);
         *      _db.SaveChanges();
         *      return param.nrCNPJBase;
         *  }
         *  catch (Exception e)
         *  {
         *      if (e is DbEntityValidationException)
         *      {
         *          string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
         *          throw new Exception(erro.Equals("") ? "Falha ao salvar TbEmpresa" : erro);
         *      }
         *      throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
         *  }
         * }
         *
         *
         * /// <summary>
         * /// Apaga uma TbEmpresa
         * /// </summary>
         * /// <param name="param"></param>
         * /// <returns></returns>
         * public static void Delete(string token, string nrCNPJBase)
         * {
         *  try
         *  {
         *      _db.tbEmpresas.Remove(_db.tbEmpresas.Where(e => e.nrCNPJBase.Equals(nrCNPJBase)).First());
         *      _db.SaveChanges();
         *  }
         *  catch (Exception e)
         *  {
         *      if (e is DbEntityValidationException)
         *      {
         *          string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
         *          throw new Exception(erro.Equals("") ? "Falha ao apagar TbEmpresa" : erro);
         *      }
         *      throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
         *  }
         * }*/



        /*/// <summary>
         * /// Altera tbEmpresa
         * /// </summary>
         * /// <param name="param"></param>
         * /// <returns></returns>
         * public static Retorno Update(string token, tbEmpresa param)
         * {
         *  try
         *  {
         *      tbEmpresa value = _db.tbEmpresas
         *              .Where(e => e.nrCNPJBase.Equals(param.nrCNPJBase))
         *              .First<tbEmpresa>();
         *
         *      Retorno retorno = new Retorno();
         *
         *      HttpRequest httpRequest = HttpContext.Current.Request;
         *      if (httpRequest.Files.Count == 0) throw new Exception("Não foi identificado o certificado digital");
         *      // Obtém o arquivo
         *      HttpPostedFile postedFile = httpRequest.Files[0];
         *
         *      // Converte para um array de bytes
         *      MemoryStream memoryStream = postedFile.InputStream as MemoryStream;
         *      if (memoryStream == null)
         *      {
         *          memoryStream = new MemoryStream();
         *          postedFile.InputStream.CopyTo(memoryStream);
         *      }
         *      byte[] data = new byte[memoryStream.ToArray().Length];
         *      memoryStream.Read(data, 0, data.Length);
         *      memoryStream.Close();
         *
         *      // VERIFICAR SE EXISTE ALTERAÇÃO NOS PARAMETROS
         *      if (data != null && (value.dsCertificadoDigital == null || !data.SequenceEqual(value.dsCertificadoDigital)))
         *          value.dsCertificadoDigital = data;
         *      if (param.dsCertificadoDigitalSenha != null && (value.dsCertificadoDigitalSenha == null || !param.dsCertificadoDigitalSenha.Equals(value.dsCertificadoDigitalSenha)))
         *          value.dsCertificadoDigitalSenha = param.dsCertificadoDigitalSenha;
         *
         *      Mensagem mensagem = CertificadoDigital.ValidarCertificado(value.dsCertificadoDigital, value.dsCertificadoDigitalSenha);
         *      if (mensagem.cdMensagem == 200)
         *      {
         *          value.dtCadastro = DateTime.Now;
         *          value.dtValidade = CertificadoDigital.GetDataValidade(param.dsCertificadoDigital, param.dsCertificadoDigitalSenha);
         *          value.flSenhaValida = true;
         *
         *          _db.SaveChanges();
         *      }
         *
         *      retorno.Registros.Add(mensagem);
         *
         *      return retorno;
         *  }
         *  catch (Exception e)
         *  {
         *      if (e is DbEntityValidationException)
         *      {
         *          string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
         *          throw new Exception(erro.Equals("") ? "Falha ao alterar TbEmpresa" : erro);
         *      }
         *      throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
         *  }
         * }*/



        /// <summary>
        /// Altera certificado e senha
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static Mensagem Patch(string token, Dictionary <string, string> queryString, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }

            try
            {
                // TEM QUE TER ENVIADO VIA QUERYSTRING nrCNPJBase e dsCertificadoDigitalSenha
                string outValue = null;
                if (!queryString.TryGetValue("" + (int)GatewayTbEmpresa.CAMPOS.NRCNPJBASE, out outValue) ||
                    !queryString.TryGetValue("" + (int)GatewayTbEmpresa.CAMPOS.DSCERTIFICADODIGITALSENHA, out outValue))
                {
                    throw new Exception("CNPJ base e Senha são obrigatórios!");
                }

                string nrCNPJBase = queryString["" + (int)GatewayTbEmpresa.CAMPOS.NRCNPJBASE];
                string dsCertificadoDigitalSenha = queryString["" + (int)GatewayTbEmpresa.CAMPOS.DSCERTIFICADODIGITALSENHA];

                // Obtém o objet
                tbEmpresa value = _db.tbEmpresas.Where(e => e.nrCNPJBase.Equals(nrCNPJBase)).FirstOrDefault();

                if (value == null)
                {
                    throw new Exception("CNPJ Base inexistente!");
                }

                // TEM QUE TER ENVIADO O ARQUIVO
                HttpRequest httpRequest = HttpContext.Current.Request;
                if (httpRequest.Files.Count == 0)
                {
                    throw new Exception("Não foi identificado o certificado digital");
                }

                // Obtém o arquivo
                HttpPostedFile postedFile = httpRequest.Files[0];
                // Valida a extensão
                string extensao = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf("."));
                if (!extensao.ToLower().Equals(".pfx"))
                {
                    throw new Exception("Formato do arquivo deve ser PFX!");
                }

                // Converte para um array de bytes
                BinaryReader binaryReader = new BinaryReader(postedFile.InputStream);
                byte[]       data         = binaryReader.ReadBytes(postedFile.ContentLength);

                // VERIFICAR SE EXISTE ALTERAÇÃO NOS PARAMETROS
                if (value.dsCertificadoDigital == null || !data.SequenceEqual(value.dsCertificadoDigital))
                {
                    value.dsCertificadoDigital = data;
                }
                if (value.dsCertificadoDigitalSenha == null || !dsCertificadoDigitalSenha.Equals(value.dsCertificadoDigitalSenha))
                {
                    value.dsCertificadoDigitalSenha = dsCertificadoDigitalSenha;
                }

                // Decodifica a senha
                string senha = CertificadoDigital.DecodeFrom64(dsCertificadoDigitalSenha);

                Mensagem mensagem = CertificadoDigital.ValidarCertificado(data, senha);//value.dsCertificadoDigital, value.dsCertificadoDigitalSenha);
                if (mensagem.cdMensagem == 200)
                {
                    value.dtCadastro    = DateTime.Now;
                    value.dtValidade    = CertificadoDigital.GetDataValidade(data, senha);//value.dsCertificadoDigital, value.dsCertificadoDigitalSenha);
                    value.flSenhaValida = true;

                    _db.SaveChanges();
                }

                return(mensagem);
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao alterar TbEmpresa" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }