Example #1
0
    private void LoadFromEntity(Guid pes_id)
    {
        UCEnderecos1.Inicializar(true, false, "Endereco");

        //Carrega dados dos endereços da pessoa
        DataTable dtEndereco = PES_PessoaEnderecoBO.GetSelect(pes_id, false, 1, 1);

        UCEnderecos1.CarregarEnderecosBanco(dtEndereco);

        UCGridContato1._CarregarContato();
        UCGridDocumento1._CarregarDocumento(Guid.Empty);
        UCGridCertidaoCivil1._CarregarCertidaoCivil();
    }
Example #2
0
    /// <summary>
    /// Insere e altera uma pessoa
    /// </summary>
    private void _Associar()
    {
        try
        {
            string msgErro;
            bool   mensagemEmBranco = String.IsNullOrEmpty(_lblMessage.Text.Trim());
            if (mensagemEmBranco && !UCGridContato1.SalvaConteudoGrid(out msgErro))
            {
                UCGridContato1._MensagemErro.Visible = false;
                _lblMessage.Text     = msgErro;
                txtSelectedTab.Value = "2";
                return;
            }

            if (mensagemEmBranco && !UCGridCertidaoCivil1.AtualizaViewState(out msgErro))
            {
                _lblMessage.Text     = msgErro;
                txtSelectedTab.Value = "3";
                return;
            }

            if (!UCGridDocumento1.ValidaConteudoGrid(out msgErro))
            {
                UCGridDocumento1._MensagemErro.Visible = false;
                _lblMessage.Text     = UtilBO.GetErroMessage(msgErro, UtilBO.TipoMensagem.Alerta);
                txtSelectedTab.Value = "3";
                return;
            }

            //Adiciona valores na entidade de pessoa
            PES_Pessoa entityPessoa = new PES_Pessoa
            {
                pes_id = UCCadastroPessoa1._VS_pes_id
                ,
                pes_nome = UCCadastroPessoa1._txtNome.Text
                ,
                pes_nome_abreviado = UCCadastroPessoa1._txtNomeAbreviado.Text
                ,
                pai_idNacionalidade = new Guid(UCCadastroPessoa1._ComboNacionalidade.SelectedValue)
                ,
                pes_naturalizado = UCCadastroPessoa1._chkNaturalizado.Checked
                ,
                cid_idNaturalidade = UCCadastroPessoa1._VS_cid_id
                ,
                pes_dataNascimento = (String.IsNullOrEmpty(UCCadastroPessoa1._txtDataNasc.Text.Trim())? new DateTime() : Convert.ToDateTime(UCCadastroPessoa1._txtDataNasc.Text.Trim()))
                ,
                pes_racaCor = UCCadastroPessoa1._ComboRacaCor.SelectedValue == "-1" ? Convert.ToByte(null) : Convert.ToByte(UCCadastroPessoa1._ComboRacaCor.SelectedValue)
                ,
                pes_sexo = UCCadastroPessoa1._ComboSexo.SelectedValue == "-1" ? Convert.ToByte(null) : Convert.ToByte(UCCadastroPessoa1._ComboSexo.SelectedValue)
                ,
                pes_idFiliacaoPai = UCCadastroPessoa1._VS_pes_idFiliacaoPai
                ,
                pes_idFiliacaoMae = UCCadastroPessoa1._VS_pes_idFiliacaoMae
                ,
                tes_id = new Guid(UCCadastroPessoa1._ComboEscolaridade.SelectedValue)
                ,
                pes_estadoCivil = UCCadastroPessoa1._ComboEstadoCivil.SelectedValue == "-1" ? Convert.ToByte(null) : Convert.ToByte(UCCadastroPessoa1._ComboEstadoCivil.SelectedValue)
                ,
                pes_situacao = 1
                ,
                IsNew = (UCCadastroPessoa1._VS_pes_id != Guid.Empty) ? false : true
            };

            PES_PessoaDeficiencia entityPessoaDeficiencia = new PES_PessoaDeficiencia
            {
                pes_id = _VS_pes_id
                ,
                tde_id = new Guid(UCCadastroPessoa1._ComboTipoDeficiencia.SelectedValue)
                ,
                IsNew = true
            };

            CFG_Arquivo entArquivo = null;

            //armazema a imagem na entidade de pessoa
            if (!string.IsNullOrEmpty(UCCadastroPessoa1._iptFoto.PostedFile.FileName))
            {
                string tam = SYS_ParametroBO.ParametroValor(SYS_ParametroBO.eChave.TAMANHO_MAX_FOTO_PESSOA);

                if (!string.IsNullOrEmpty(tam))
                {
                    if (UCCadastroPessoa1._iptFoto.PostedFile.ContentLength > Convert.ToInt32(tam) * 1000)
                    {
                        throw new ArgumentException("Foto é maior que o tamanho máximo permitido.");
                    }

                    if (UCCadastroPessoa1._iptFoto.PostedFile.FileName.Substring(UCCadastroPessoa1._iptFoto.PostedFile.FileName.Length - 3, 3).ToUpper() != "JPG")
                    {
                        throw new ArgumentException("Foto tem que estar no formato \".jpg\".");
                    }
                }

                entArquivo = CFG_ArquivoBO.CriarEntidadeArquivo(UCCadastroPessoa1._iptFoto.PostedFile);

                if (_VS_arq_idAntigo > 0)
                {
                    // Se já existia foto e vai ser alterada, muda só o conteúdo.
                    entArquivo.arq_id = _VS_arq_idAntigo;
                    entArquivo.IsNew  = false;
                }
            }

            if (_VS_arq_idAntigo > 0)
            {
                entityPessoa.arq_idFoto = _VS_arq_idAntigo;
            }

            XmlDocument xDoc      = new XmlDocument();
            XmlNode     xElem     = xDoc.CreateNode(XmlNodeType.Element, "Coluna", string.Empty);
            XmlNode     xNodeCoor = xDoc.CreateNode(XmlNodeType.Element, "ColunaValorAntigo", string.Empty);
            XmlNode     xNode;

            for (int i = 0; i < _VS_AssociarPessoas.Rows.Count; i++)
            {
                if ((_VS_AssociarPessoas.Rows[i]["pes_id"].ToString()) != _VS_pes_id.ToString())
                {
                    xNodeCoor       = xDoc.CreateNode(XmlNodeType.Element, "ColunaValorAntigo", "");
                    xNode           = xDoc.CreateNode(XmlNodeType.Element, "valor", "");
                    xNode.InnerText = _VS_AssociarPessoas.Rows[i]["pes_id"].ToString();
                    xNodeCoor.AppendChild(xNode);
                    xElem.AppendChild(xNodeCoor);
                }
            }
            xDoc.AppendChild(xElem);

            if (PES_PessoaBO.AssociarPessoas(entityPessoa, entityPessoaDeficiencia, UCEnderecos1._VS_enderecos, UCGridContato1._VS_contatos, UCGridDocumento1.RetornaDocumentoSave(), UCGridCertidaoCivil1._VS_certidoes, _VS_pai_idAntigo, _VS_cid_idAntigo, _VS_pes_idPaiAntigo, _VS_pes_idMaeAntigo, _VS_tes_idAntigo, _VS_tde_idAntigo, xDoc))
            {
                ApplicationWEB._GravaLogSistema(LOG_SistemaTipo.Update, "pes_id: " + entityPessoa.pes_id);
                __SessionWEB.PostMessages = UtilBO.GetErroMessage(String.Format("Pessoas associadas com sucesso."), UtilBO.TipoMensagem.Sucesso);

                Response.Redirect(__SessionWEB._AreaAtual._Diretorio + "ManutencaoPessoa/Busca.aspx", false);
            }
            else
            {
                _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar associar as pessoas.", UtilBO.TipoMensagem.Erro);
            }
        }
        catch (CoreLibrary.Validation.Exceptions.ValidationException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (ArgumentException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (DuplicateNameException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (Exception ex)
        {
            ApplicationWEB._GravaErro(ex);
            _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar associar as pessoas.", UtilBO.TipoMensagem.Erro);
        }
        finally
        {
            _updGridPessoas.Update();
        }
    }
Example #3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager sm = ScriptManager.GetCurrent(this);

        if (sm != null)
        {
            sm.Scripts.Add(new ScriptReference(ArquivoJS.UiAriaTabs));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.Tabs));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.JQueryValidation));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.JqueryMask));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.MascarasCampos));
            sm.Scripts.Add(new ScriptReference("~/Includes/jsCadastroPessoa.js"));
            sm.Scripts.Add(new ScriptReference("~/Includes/jsUCCadastroEndereco.js"));
            sm.Scripts.Add(new ScriptReference("~/Includes/jsCadastroCertidaoCivil.js"));
            sm.Services.Add(new ServiceReference("~/WSServicos.asmx"));
        }

        if (!IsPostBack)
        {
            cvDataNascimento.ErrorMessage = GestaoEscolarUtilBO.RetornaMsgValidacaoData("Data de nascimento do aluno");
            CustomValidator1.ErrorMessage = GestaoEscolarUtilBO.RetornaMsgValidacaoData("Data de emissão da certidão de nascimento");

            string message = __SessionWEB.PostMessages;
            if (!String.IsNullOrEmpty(message))
            {
                lblMessage.Text = message;
            }

            lblMatriculaEstadual.Text         = GestaoEscolarUtilBO.nomePadraoMatriculaEstadual() + " *";
            rfvMatriculaEstadual.ErrorMessage = GestaoEscolarUtilBO.nomePadraoMatriculaEstadual() + " é obrigatório.";

            UCComboTipoDeficiencia1._MostrarMessageSelecione = true;
            UCComboTipoDeficiencia1._Load(Guid.Empty, 0);

            UCEnderecos1.Inicializar(false, true, string.Empty);

            UCFiltroEscolas1.SelecionaCombosAutomatico             = false;
            UCFiltroEscolas1.UnidadeAdministrativaCampoObrigatorio = true;
            UCFiltroEscolas1.EscolaCampoObrigatorio = true;
            UCFiltroEscolas1._LoadInicial();

            UCComboCursoCurriculo1.Obrigatorio = true;
            UCComboCursoCurriculo1.CarregarCursoCurriculo();
            UCComboCursoCurriculo1.PermiteEditar = false;

            UCComboCurriculoPeriodo1._Label.Text += " *";
            UCComboCurriculoPeriodo1._MostrarMessageSelecione = true;
            UCComboCurriculoPeriodo1._Load(-1, -1);
            UCComboCurriculoPeriodo1._Combo.Enabled      = false;
            UCComboCurriculoPeriodo1.ExibeFormatoPeriodo = true;
            cvCurriculoPeriodo.ErrorMessage = GestaoEscolarUtilBO.nomePadraoPeriodo() + " é obrigatório.";

            try
            {
                if (__SessionWEB._cid_id != Guid.Empty)
                {
                    END_Cidade cid = new END_Cidade {
                        cid_id = __SessionWEB._cid_id
                    };
                    END_CidadeBO.GetEntity(cid);

                    _txtCid_id.Value     = cid.cid_id.ToString();
                    txtNaturalidade.Text = cid.cid_nome;

                    _txtCid_idCertidao.Value = cid.cid_id.ToString();
                    txtCidadeCertidao.Text   = cid.cid_nome;
                }
            }
            catch (Exception ex)
            {
                ApplicationWEB._GravaErro(ex);
                lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar carregar o sistema.", UtilBO.TipoMensagem.Erro);
            }

            UCGridContato1._CarregarContato();

            UCComboTipoDeficiencia1._Label.Text = "Necessidade educacional especial";
            UCComboEstadoCivil1._Label.Text     = "Estado civil *";
            UCComboRacaCor1._Label.Text         = "Raça / cor *";
            UCComboSexo1._Label.Text            = "Sexo *";

            UCComboEstadoCivil1._Combo.SelectedValue = "1";
            _ddlSituacao.SelectedValue = "1";

            Page.Form.DefaultFocus  = txtMatriculaEstadual.ClientID;
            Page.Form.DefaultButton = btnSalvarNovo.UniqueID;
            btnSalvarNovo.Visible   = __SessionWEB.__UsuarioWEB.GrupoPermissao.grp_inserir;
        }

        UCFiltroEscolas1._Selecionar        += UCFiltroEscolas1__Selecionar;
        UCFiltroEscolas1._SelecionarEscola  += UCFiltroEscolas1__SelecionarEscola;
        UCComboCursoCurriculo1.IndexChanged += UCComboCursoCurriculo1_IndexChanged;
    }
Example #4
0
    private void _CarregarPessoa()
    {
        try
        {
            //Carrega entidade de pessoa
            PES_Pessoa pes = new PES_Pessoa
            {
                pes_id = _VS_pes_id
            };
            PES_PessoaBO.GetEntity(pes);

            _VS_arq_idAntigo = pes.arq_idFoto;

            //_VS_pes_foto = pes.pes_foto;
            UCCadastroPessoa1._imgFoto.ImageUrl = "~/Imagem.ashx?id=" + pes.arq_idFoto;

            CFG_Arquivo entArquivo = new CFG_Arquivo
            {
                arq_id = pes.arq_idFoto
            };
            CFG_ArquivoBO.GetEntity(entArquivo);

            //Exibe imagem caso exista
            if (!entArquivo.IsNew && entArquivo.arq_data.Length > 1)
            {
                System.Drawing.Image img;
                using (MemoryStream ms = new MemoryStream(entArquivo.arq_data, 0, entArquivo.arq_data.Length))
                {
                    ms.Write(entArquivo.arq_data, 0, entArquivo.arq_data.Length);
                    img = System.Drawing.Image.FromStream(ms, true);
                }

                int larguraMaxima = 200;
                int alturaMaxima  = 200;
                int alt;
                int lar;

                decimal proporcaoOriginal = (decimal)((img.Height * 100) / img.Width) / 100;

                if (proporcaoOriginal > 1)
                {
                    proporcaoOriginal = (decimal)((img.Width * 100) / img.Height) / 100;
                    alt = alturaMaxima;
                    lar = Convert.ToInt32(alturaMaxima * proporcaoOriginal);
                }
                else
                {
                    lar = larguraMaxima;
                    alt = Convert.ToInt32(larguraMaxima * proporcaoOriginal);
                }

                UCCadastroPessoa1._imgFoto.Height           = alt;
                UCCadastroPessoa1._imgFoto.Width            = lar;
                UCCadastroPessoa1._imgFoto.Visible          = true;
                UCCadastroPessoa1._chbExcluirImagem.Visible = true;
                UCCadastroPessoa1._chbExcluirImagem.Checked = false;
            }
            else
            {
                UCCadastroPessoa1._imgFoto.Visible          = false;
                UCCadastroPessoa1._chbExcluirImagem.Visible = false;
            }

            UCCadastroPessoa1._VS_pes_id             = pes.pes_id;
            UCCadastroPessoa1._txtNome.Text          = pes.pes_nome;
            UCCadastroPessoa1._txtNomeAbreviado.Text = (!string.IsNullOrEmpty(pes.pes_nome_abreviado) ? pes.pes_nome_abreviado : string.Empty);

            //Exibe cidade naturalidade da pessoa
            if (pes.cid_idNaturalidade != Guid.Empty)
            {
                END_Cidade cid = new END_Cidade
                {
                    cid_id = pes.cid_idNaturalidade
                };
                END_CidadeBO.GetEntity(cid);

                UCCadastroPessoa1._VS_cid_id            = pes.cid_idNaturalidade;
                UCCadastroPessoa1._txtNaturalidade.Text = cid.cid_nome;
            }

            //Exibe dados gerias da pessoa
            UCCadastroPessoa1._txtDataNasc.Text = (pes.pes_dataNascimento != new DateTime()) ? pes.pes_dataNascimento.ToString("dd/MM/yyyy") : string.Empty;
            UCCadastroPessoa1._ComboEstadoCivil.SelectedValue = (pes.pes_estadoCivil > 0 ? pes.pes_estadoCivil.ToString() : "-1");
            UCCadastroPessoa1._ComboSexo.SelectedValue        = (pes.pes_sexo > 0) ? pes.pes_sexo.ToString() : "-1";

            UCCadastroPessoa1._ComboNacionalidade.SelectedValue = (pes.pai_idNacionalidade != Guid.Empty ? pes.pai_idNacionalidade.ToString() : Guid.Empty.ToString());
            UCCadastroPessoa1._chkNaturalizado.Checked          = pes.pes_naturalizado;
            UCCadastroPessoa1._ComboRacaCor.SelectedValue       = (pes.pes_racaCor > 0 ? pes.pes_racaCor.ToString() : "-1");
            UCCadastroPessoa1._VS_pes_idFiliacaoPai             = pes.pes_idFiliacaoPai;
            UCCadastroPessoa1._VS_pes_idFiliacaoMae             = pes.pes_idFiliacaoMae;
            UCCadastroPessoa1._ComboEscolaridade.SelectedValue  = (pes.tes_id != Guid.Empty ? pes.tes_id.ToString() : Guid.Empty.ToString());

            //Carregar tipo de deficiência cadastrada para a pessoa
            DataTable dtPessoaDeficiencia = PES_PessoaDeficienciaBO.GetSelect(_VS_pes_id, false, 1, 1);
            UCCadastroPessoa1._ComboTipoDeficiencia.SelectedValue = dtPessoaDeficiencia.Rows.Count > 0 ? dtPessoaDeficiencia.Rows[0]["tde_id"].ToString() : Guid.Empty.ToString();

            //Armazena os os id's antigos em ViewState
            _VS_pai_idAntigo    = pes.pai_idNacionalidade;
            _VS_cid_idAntigo    = pes.cid_idNaturalidade;
            _VS_pes_idPaiAntigo = pes.pes_idFiliacaoPai;
            _VS_pes_idMaeAntigo = pes.pes_idFiliacaoMae;
            _VS_tes_idAntigo    = pes.tes_id;
            _VS_tde_idAntigo    = dtPessoaDeficiencia.Rows.Count > 0 ? new Guid(dtPessoaDeficiencia.Rows[0]["tde_id"].ToString()) : Guid.Empty;

            //Exibe dados do pai da pessoa
            PES_Pessoa pesFiliacaoPai = new PES_Pessoa {
                pes_id = pes.pes_idFiliacaoPai
            };
            PES_PessoaBO.GetEntity(pesFiliacaoPai);
            UCCadastroPessoa1._txtPai.Text = pesFiliacaoPai.pes_nome;

            //Exibe dados da mae da pessoa
            PES_Pessoa pesFiliacaoMae = new PES_Pessoa {
                pes_id = pes.pes_idFiliacaoMae
            };
            PES_PessoaBO.GetEntity(pesFiliacaoMae);
            UCCadastroPessoa1._txtMae.Text = pesFiliacaoMae.pes_nome;

            //Carrega dados dos endereços da pessoa
            DataTable dtEndereco = PES_PessoaEnderecoBO.GetSelect(pes.pes_id, false, 1, 1);

            if (dtEndereco.Rows.Count == 0)
            {
                dtEndereco = null;
            }

            UCEnderecos1.CarregarEnderecosBanco(dtEndereco);

            //Carrega dados dos contatos da pessoa
            DataTable dtContato = PES_PessoaContatoBO.GetSelect(pes.pes_id, false, 1, 1);

            if (dtContato.Rows.Count == 0)
            {
                dtContato = null;
            }

            UCGridContato1._VS_contatos = dtContato;
            UCGridContato1._CarregarContato();

            //Carrega dados dos documentos da pessoa
            UCGridDocumento1._CarregarDocumento(pes.pes_id);

            //Carrega dados da certidões da pessoa
            DataTable dtCertidao = PES_CertidaoCivilBO.GetSelect(pes.pes_id, false, 1, 1);

            if (dtCertidao.Rows.Count == 0)
            {
                dtCertidao = null;
            }

            UCGridCertidaoCivil1._VS_certidoes = dtCertidao;
            UCGridCertidaoCivil1._CarregarCertidaoCivil();

            UCCadastroPessoa1._updCadastroPessoas.Update();
            UCGridContato1._updGridContatos.Update();
            UCGridDocumento1._updGridDocumentos.Update();
            UCGridCertidaoCivil1._updGridCertidaoCivil.Update();

            _btnSalvar.Visible = true;
            _updBotoes.Update();
        }
        catch (Exception ex)
        {
            ApplicationWEB._GravaErro(ex);
            _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar carregar a pessoa.", UtilBO.TipoMensagem.Erro);
        }
    }
Example #5
0
    /// <summary>
    /// Insere e altera uma pessoa
    /// </summary>
    private void _Salvar()
    {
        try
        {
            string msgErro;
            bool   mensagemEmBranco = String.IsNullOrEmpty(_lblMessage.Text.Trim());
            if (mensagemEmBranco && !UCGridContato1.SalvaConteudoGrid(out msgErro))
            {
                UCGridContato1._MensagemErro.Visible = false;
                _lblMessage.Text     = msgErro;
                txtSelectedTab.Value = "2";
                return;
            }

            if (mensagemEmBranco && !UCGridCertidaoCivil1.AtualizaViewState(out msgErro))
            {
                _lblMessage.Text     = msgErro;
                txtSelectedTab.Value = "3";
                return;
            }

            if (!UCGridDocumento1.ValidaConteudoGrid(out msgErro))
            {
                UCGridDocumento1._MensagemErro.Visible = false;
                _lblMessage.Text     = UtilBO.GetErroMessage(msgErro, UtilBO.TipoMensagem.Alerta);
                txtSelectedTab.Value = "3";
                return;
            }

            //Adiciona valores na entidade de pessoa
            PES_Pessoa entityPessoa = new PES_Pessoa
            {
                pes_id = UCCadastroPessoa1._VS_pes_id
                ,
                pes_nome = UCCadastroPessoa1._txtNome.Text
                ,
                pes_nome_abreviado = UCCadastroPessoa1._txtNomeAbreviado.Text
                ,
                pes_nomeSocial = UCCadastroPessoa1._txtNomeSocial.Text
                ,
                pai_idNacionalidade = UCCadastroPessoa1._ComboNacionalidade.SelectedValue == "-1" ? Guid.Empty : new Guid(UCCadastroPessoa1._ComboNacionalidade.SelectedValue)
                ,
                pes_naturalizado = UCCadastroPessoa1._chkNaturalizado.Checked
                ,
                cid_idNaturalidade = UCCadastroPessoa1._VS_cid_id
                ,
                pes_dataNascimento = (String.IsNullOrEmpty(UCCadastroPessoa1._txtDataNasc.Text.Trim()) ? new DateTime() : Convert.ToDateTime(UCCadastroPessoa1._txtDataNasc.Text.Trim()))
                ,
                pes_racaCor = UCCadastroPessoa1._ComboRacaCor.SelectedValue == "-1" ? Convert.ToByte(null) : Convert.ToByte(UCCadastroPessoa1._ComboRacaCor.SelectedValue)
                ,
                pes_sexo = UCCadastroPessoa1._ComboSexo.SelectedValue == "-1" ? Convert.ToByte(null) : Convert.ToByte(UCCadastroPessoa1._ComboSexo.SelectedValue)
                ,
                pes_idFiliacaoPai = UCCadastroPessoa1._VS_pes_idFiliacaoPai
                ,
                pes_idFiliacaoMae = UCCadastroPessoa1._VS_pes_idFiliacaoMae
                ,
                tes_id = new Guid(UCCadastroPessoa1._ComboEscolaridade.SelectedValue)
                ,
                pes_estadoCivil = UCCadastroPessoa1._ComboEstadoCivil.SelectedValue == "-1" ? Convert.ToByte(null) : Convert.ToByte(UCCadastroPessoa1._ComboEstadoCivil.SelectedValue)
                ,
                pes_situacao = 1
                ,
                IsNew = (UCCadastroPessoa1._VS_pes_id != Guid.Empty) ? false : true
            };

            PES_PessoaDeficiencia entityPessoaDeficiencia = new PES_PessoaDeficiencia
            {
                pes_id = _VS_pes_id
                ,
                tde_id = new Guid(UCCadastroPessoa1._ComboTipoDeficiencia.SelectedValue)
                ,
                IsNew = true
            };

            CFG_Arquivo entArquivo = null;

            //armazema a imagem na entidade de pessoa
            if (!string.IsNullOrEmpty(UCCadastroPessoa1._iptFoto.PostedFile.FileName))
            {
                string tam = SYS_ParametroBO.ParametroValor(SYS_ParametroBO.eChave.TAMANHO_MAX_FOTO_PESSOA);

                if (!string.IsNullOrEmpty(tam))
                {
                    if (UCCadastroPessoa1._iptFoto.PostedFile.ContentLength > Convert.ToInt32(tam) * 1000)
                    {
                        throw new ArgumentException("Foto é maior que o tamanho máximo permitido.");
                    }
                }

                if (UCCadastroPessoa1._iptFoto.PostedFile.FileName.Substring(UCCadastroPessoa1._iptFoto.PostedFile.FileName.Length - 3, 3).ToUpper() != "JPG")
                {
                    throw new ArgumentException("Foto tem que estar no formato \".jpg\".");
                }

                entArquivo = CFG_ArquivoBO.CriarEntidadeArquivo(UCCadastroPessoa1._iptFoto.PostedFile);

                if (_VS_arq_idAntigo > 0)
                {
                    // Se já existia foto e vai ser alterada, muda só o conteúdo.
                    entArquivo.arq_id = _VS_arq_idAntigo;
                    entArquivo.IsNew  = false;
                }
            }

            if (_VS_arq_idAntigo > 0)
            {
                entityPessoa.arq_idFoto = _VS_arq_idAntigo;
            }

            //Chama método salvar da pessoa

            /* [OLD]  if (PES_PessoaBO.Save(entityPessoa
             *                  , entityPessoaDeficiencia
             *                  , UCEnderecos1._VS_enderecos
             *                  , UCGridContato1._VS_contatos
             *                  , UCGridDocumento1.RetornaDocumentoSave()
             *                  , UCGridCertidaoCivil1._VS_certidoes
             *                  , _VS_pai_idAntigo
             *                  , _VS_cid_idAntigo
             *                  , _VS_pes_idPaiAntigo
             *                  , _VS_pes_idMaeAntigo
             *                  , _VS_tes_idAntigo
             *                  , _VS_tde_idAntigo
             *                  , ApplicationWEB.TipoImagensPermitidas
             *                  , ApplicationWEB.TamanhoMaximoArquivo
             *                  , entArquivo
             *                  , UCCadastroPessoa1._chbExcluirImagem.Checked
             *                  )
             *     )*/
            END_Endereco entityEndereco = new END_Endereco();

            string    msg;
            DataTable dtEndereco;

            bool cadastraEndereco = UCEnderecos1.RetornaEnderecoCadastrado(out dtEndereco, out msg);

            if (PES_PessoaBO.Save(entityPessoa
                                  , entityPessoaDeficiencia
                                  , dtEndereco
                                  , UCGridContato1._VS_contatos
                                  , UCGridDocumento1.RetornaDocumentoSave()
                                  , UCGridCertidaoCivil1._VS_certidoes
                                  , _VS_pai_idAntigo
                                  , _VS_cid_idAntigo
                                  , _VS_pes_idPaiAntigo
                                  , _VS_pes_idMaeAntigo
                                  , _VS_tes_idAntigo
                                  , _VS_tde_idAntigo
                                  , ApplicationWEB.TipoImagensPermitidas
                                  , ApplicationWEB.TamanhoMaximoArquivo
                                  , entArquivo
                                  , UCCadastroPessoa1._chbExcluirImagem.Checked
                                  )
                )
            {
                if (_VS_pes_id == Guid.Empty)
                {
                    ApplicationWEB._GravaLogSistema(LOG_SistemaTipo.Insert, "pes_id: " + entityPessoa.pes_id);
                    __SessionWEB.PostMessages = UtilBO.GetErroMessage(String.Format("Pessoa incluída com sucesso."), UtilBO.TipoMensagem.Sucesso);
                }
                else
                {
                    ApplicationWEB._GravaLogSistema(LOG_SistemaTipo.Update, "pes_id: " + entityPessoa.pes_id);
                    __SessionWEB.PostMessages = UtilBO.GetErroMessage(String.Format("Pessoa alterada com sucesso."), UtilBO.TipoMensagem.Sucesso);
                }

                Response.Redirect(__SessionWEB._AreaAtual._Diretorio + "ManutencaoPessoa/Busca.aspx", false);
            }
            else
            {
                _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar salvar a pessoa.", UtilBO.TipoMensagem.Erro);
            }
        }
        catch (CoreLibrary.Validation.Exceptions.ValidationException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (ArgumentException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (DuplicateNameException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (Exception ex)
        {
            ApplicationWEB._GravaErro(ex);
            _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar salvar a pessoa.", UtilBO.TipoMensagem.Erro);
        }
    }
Example #6
0
    /// <summary>
    /// Salva dados do aluno
    /// </summary>
    private void Salvar(bool novo)
    {
        try
        {
            string msgErro;
            if (lblMessage.Text == string.Empty && !UCGridContato1.SalvaConteudoGrid(out msgErro))
            {
                UCGridContato1._MensagemErro.Visible = false;
                lblMessage.Text = msgErro;
                return;
            }

            PES_Pessoa entityPessoa = new PES_Pessoa
            {
                pes_nome = txtNome.Text
                ,
                cid_idNaturalidade = string.IsNullOrEmpty(_txtCid_id.Value) ? Guid.Empty : new Guid(_txtCid_id.Value)
                ,
                pes_dataNascimento = string.IsNullOrEmpty(txtDataNasc.Text) ? new DateTime() : Convert.ToDateTime(txtDataNasc.Text)
                ,
                pes_racaCor = UCComboRacaCor1._Combo.SelectedValue == "-1" ? Convert.ToByte(null) : Convert.ToByte(UCComboRacaCor1._Combo.SelectedValue)
                ,
                pes_sexo = UCComboSexo1._Combo.SelectedValue == "-1" ? Convert.ToByte(null) : Convert.ToByte(UCComboSexo1._Combo.SelectedValue)
                ,
                pes_estadoCivil = UCComboEstadoCivil1._Combo.SelectedValue == "-1" ? Convert.ToByte(null) : Convert.ToByte(UCComboEstadoCivil1._Combo.SelectedValue)
                ,
                pes_situacao = 1
                ,
                IsNew = true
            };

            PES_PessoaDeficiencia entityPessoaDeficiencia = new PES_PessoaDeficiencia
            {
                tde_id = new Guid(UCComboTipoDeficiencia1._Combo.SelectedValue)
            };

            END_Cidade cid = new END_Cidade
            {
                cid_id = new Guid(_txtCid_idCertidao.Value)
            };
            END_CidadeBO.GetEntity(cid);

            PES_CertidaoCivil entityCertidaoCivil = new PES_CertidaoCivil
            {
                ctc_tipo = 1
                ,
                cid_idCartorio = new Guid(_txtCid_idCertidao.Value)
                ,
                unf_idCartorio = cid.unf_id
                ,
                ctc_distritoCartorio = txtDistritoCertidao.Text
                ,
                ctc_dataEmissao = string.IsNullOrEmpty(txtDataEmissao.Text) ? new DateTime() : Convert.ToDateTime(txtDataEmissao.Text)
                ,
                ctc_folha = txtFolha.Text
                ,
                ctc_livro = txtLivro.Text
                ,
                ctc_numeroTermo = txtNumeroTermo.Text
            };

            END_Endereco entityEndereco;
            string       numero;
            string       complemento;
            string       msg;

            bool cadastraEndereco = UCEnderecos1.RetornaEnderecoCadastrado(out entityEndereco, out numero, out complemento, out msg);

            if (!cadastraEndereco)
            {
                throw new ValidationException(msg);
            }

            DataTable dtEndereco = string.IsNullOrEmpty(entityEndereco.end_cep) ? new DataTable() : UCEnderecos1._VS_enderecos;

            ACA_Aluno entityAluno = new ACA_Aluno
            {
                ent_id = __SessionWEB.__UsuarioWEB.Usuario.ent_id
                ,
                alu_situacao = _ddlSituacao.SelectedValue == "-1" ? Convert.ToByte(0) : Convert.ToByte(_ddlSituacao.SelectedValue)
                ,
                IsNew = true
            };

            ACA_AlunoCurriculo entityAlunoCurriculo = new ACA_AlunoCurriculo
            {
                esc_id = UCFiltroEscolas1._ComboUnidadeEscola.SelectedValue.Split(';')[0] == "-1" ? Convert.ToInt32(null) : Convert.ToInt32(UCFiltroEscolas1._ComboUnidadeEscola.SelectedValue.Split(';')[0])
                ,
                uni_id = UCFiltroEscolas1._ComboUnidadeEscola.SelectedValue.Split(';')[1] == "-1" ? Convert.ToInt32(null) : Convert.ToInt32(UCFiltroEscolas1._ComboUnidadeEscola.SelectedValue.Split(';')[1])
                ,
                cur_id = UCComboCurriculoPeriodo1._Combo.SelectedValue.Split(';')[0] == "-1" ? Convert.ToInt32(null) : Convert.ToInt32(UCComboCurriculoPeriodo1._Combo.SelectedValue.Split(';')[0])
                ,
                crr_id = UCComboCurriculoPeriodo1._Combo.SelectedValue.Split(';')[1] == "-1" ? Convert.ToInt32(null) : Convert.ToInt32(UCComboCurriculoPeriodo1._Combo.SelectedValue.Split(';')[1])
                ,
                crp_id = UCComboCurriculoPeriodo1._Combo.SelectedValue.Split(';')[2] == "-1" ? Convert.ToInt32(null) : Convert.ToInt32(UCComboCurriculoPeriodo1._Combo.SelectedValue.Split(';')[2])
                ,
                alc_matriculaEstadual = txtMatriculaEstadual.Text
                ,
                alc_situacao = _ddlSituacao.SelectedValue == "-1" ? Convert.ToByte(0) : Convert.ToByte(_ddlSituacao.SelectedValue)
            };

            if (ACA_AlunoBO.Save_CadastroRapido(entityPessoa
                                                , entityPessoaDeficiencia
                                                , dtEndereco
                                                , UCGridContato1._VS_contatos
                                                , entityCertidaoCivil
                                                , txtMae.Text
                                                , txtCPFMae.Text
                                                , txtPai.Text
                                                , txtCPFPai.Text
                                                , rfvMatriculaEstadual.Enabled
                                                , entityAluno
                                                , entityAlunoCurriculo
                                                , null
                                                , null))
            {
                ApplicationWEB._GravaLogSistema(LOG_SistemaTipo.Insert, "alu_id: " + entityAluno.alu_id);
                __SessionWEB.PostMessages = UtilBO.GetErroMessage(String.Format("Aluno incluído com sucesso."), UtilBO.TipoMensagem.Sucesso);

                Response.Redirect("CadastroRapido.aspx", false);
                HttpContext.Current.ApplicationInstance.CompleteRequest();

                string redirect = novo ?
                                  "~/Academico/Aluno/CadastroRapido.aspx" :
                                  "~/Academico/Aluno/Busca.aspx";

                Response.Redirect(redirect, false);
                Context.ApplicationInstance.CompleteRequest();
            }
            else
            {
                lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar salvar o aluno.", UtilBO.TipoMensagem.Erro);
            }
        }
        catch (ThreadAbortException)
        {
        }
        catch (ValidationException ex)
        {
            UCEnderecos1.AtualizaEnderecos();
            lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (ArgumentException ex)
        {
            UCEnderecos1.AtualizaEnderecos();
            lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (DuplicateNameException ex)
        {
            UCEnderecos1.AtualizaEnderecos();
            lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (Exception ex)
        {
            UCEnderecos1.AtualizaEnderecos();
            ApplicationWEB._GravaErro(ex);
            lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar salvar o aluno.", UtilBO.TipoMensagem.Erro);
        }
    }
    /// <summary>
    /// Carrega os dados da entidade nos controles caso seja alteração.
    /// </summary>
    private void _LoadFromEntity()
    {
        try
        {
            SYS_Entidade ent = new SYS_Entidade {
                ent_id = _VS_ent_id
            };
            SYS_EntidadeBO.GetEntity(ent);

            _VS_ent_id = ent.ent_id;
            _VS_ent_idSuperiorAntigo = ent.ent_idSuperior;
            UCComboTipoEntidade1._Combo.SelectedValue = ent.ten_id.ToString();
            _txtRazaoSocial.Text  = ent.ent_razaoSocial;
            _txtNomeFantasia.Text = (!string.IsNullOrEmpty(ent.ent_nomeFantasia) ? ent.ent_nomeFantasia : string.Empty);
            _txtSigla.Text        = (!string.IsNullOrEmpty(ent.ent_sigla) ? ent.ent_sigla : string.Empty);
            _txtCodigo.Text       = (!string.IsNullOrEmpty(ent.ent_codigo) ? ent.ent_codigo : string.Empty);
            _txtCNPJ.Text         = (!string.IsNullOrEmpty(ent.ent_cnpj) ? ent.ent_cnpj : string.Empty);
            _txtIE.Text           = (!string.IsNullOrEmpty(ent.ent_inscricaoEstadual) ? ent.ent_inscricaoEstadual : string.Empty);
            _txtIM.Text           = (!string.IsNullOrEmpty(ent.ent_inscricaoMunicipal) ? ent.ent_inscricaoMunicipal : string.Empty);
            UCComboEntidade1._Combo.SelectedValue = (ent.ent_idSuperior != Guid.Empty) ? Convert.ToString(ent.ent_idSuperior) : Guid.Empty.ToString();
            txtUrlAcesso.Text           = ent.ent_urlAcesso;
            chkExibeLogoCliente.Checked = ent.ent_exibeLogoCliente;

            if (ent.tep_id > 0)
            {
                UCComboTemaPadrao.Valor = ent.tep_id;
                UCComboTemaPadrao_IndexChanged();

                CFG_TemaPadrao entTema = new CFG_TemaPadrao {
                    tep_id = ent.tep_id
                };
                CFG_TemaPadraoBO.GetEntity(entTema);

                string caminho = "~/App_Themes/" + entTema.tep_nome + "/images/logos/";

                if (!string.IsNullOrEmpty(ent.ent_logoCliente) && UtilBO.ExisteArquivo(Server.MapPath(caminho + ent.ent_id + "_" + ent.ent_logoCliente)))
                {
                    imgLogoCliente.Visible  = true;
                    imgLogoCliente.ImageUrl = caminho + ent.ent_id + "_" + ent.ent_logoCliente;
                }

                UCComboTemaPaleta.Valor = ent.tpl_id > 0 ? new int[] { ent.tep_id, ent.tpl_id } : new int[] { -1, -1 };
            }
            else
            {
                UCComboTemaPadrao.Valor = -1;
            }

            _chkBloqueado.Checked = ent.ent_situacao == 2;

            DataTable dtEndereco = SYS_EntidadeEnderecoBO.CarregarEnderecosBy_Entidade(ent.ent_id);
            UCEnderecos1.CarregarEnderecosBanco(dtEndereco);

            DataTable dt = SYS_EntidadeContatoBO.GetSelect(_VS_ent_id, false, 1, 1);
            if (dt.Rows.Count == 0)
            {
                dt = null;
            }

            UCGridContato1._VS_contatos = dt;

            UCGridContato1._CarregarContato();

            UCComboTipoEntidade1._Combo.Enabled = false;
        }
        catch (Exception ex)
        {
            ApplicationWEB._GravaErro(ex);
            _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar carregar a entidade.", UtilBO.TipoMensagem.Erro);
        }
    }
Example #8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager sm = ScriptManager.GetCurrent(this);

        if (sm != null)
        {
            sm.Scripts.Add(new ScriptReference(ArquivoJS.UiAriaTabs));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.Tabs));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.PastaScriptRaiz + "Telas/jsCadastroPessoa.js"));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.PastaScriptRaiz + "Telas/jsUCCadastroContato.js"));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.PastaScriptRaiz + "Telas/jsUCCadastroEndereco.js"));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.PastaScriptRaiz + "Telas/jsCadastroCertidaoCivil.js"));
            sm.Services.Add(new ServiceReference("~/WSServicos.asmx"));
        }

        UCPessoas1.Paginacao     = ApplicationWEB._Paginacao;
        UCPessoas1.ContainerName = "divBuscaPessoa";
        UCPessoas1.ReturnValues += UCPessoas1BuscaPessoa;

        if (!IsPostBack)
        {
            // Inicializa componentes

            // Validação para utilização de múltiplos endereços para a manutenção de pessoas
            bool permitirMultiplosEnderecos = SYS_ParametroBO.ParametroValorBooleano(SYS_ParametroBO.eChave.PERMITIR_MULTIPLOS_ENDERECOS_PESSOA);
            UCEnderecos1.Inicializar(false, !permitirMultiplosEnderecos, "Pessoa");

            bool valor = SYS_ParametroBO.ParametroValorBooleano(SYS_ParametroBO.eChave.PERMITIR_TIPO_CONTATOS_DUPLICADOS);
            UCGridContato1.InicializarContato(valor);

            if ((PreviousPage != null) && (PreviousPage.IsCrossPagePostBack))
            {
                _VS_pes_id = PreviousPage.EditItem;
                _LoadFromEntity();
            }
            else
            {
                string pais_padrao = SYS_ParametroBO.ParametroValor(SYS_ParametroBO.eChave.PAIS_PADRAO_BRASIL);

                if (!string.IsNullOrEmpty(pais_padrao))
                {
                    UCCadastroPessoa1._ComboNacionalidade.SelectedValue = pais_padrao;
                }

                UCGridContato1._CarregarContato();
                UCGridDocumento1._CarregarDocumento(Guid.Empty);
                UCGridCertidaoCivil1._CarregarCertidaoCivil();

                _btnSalvar.Visible = __SessionWEB.__UsuarioWEB.GrupoPermissao.grp_inserir;
            }

            Page.Form.DefaultFocus  = UCCadastroPessoa1._txtNome.ClientID;
            Page.Form.DefaultButton = _btnSalvar.UniqueID;
        }

        #region INICIALIZACAO DOS DELEGATES

        UCCadastroPessoa1._Selecionar += UCCadastroPessoa1__Seleciona;

        #endregion INICIALIZACAO DOS DELEGATES
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager sm = ScriptManager.GetCurrent(this);

        if (sm != null)
        {
            sm.Scripts.Add(new ScriptReference(ArquivoJS.JQueryValidation));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.JqueryMask));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.MascarasCampos));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.PastaScriptRaiz + "Telas/jsUCCadastroContato.js"));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.PastaScriptRaiz + "Telas/jsUCCadastroEndereco.js"));
            sm.Services.Add(new ServiceReference("~/WSServicos.asmx"));
        }

        UCComboTemaPadrao.IndexChanged += UCComboTemaPadrao_IndexChanged;

        if (!IsPostBack)
        {
            try
            {
                // Validação para utilização de múltiplos endereços para a entidade
                bool permitirMultiplosEnderecos = SYS_ParametroBO.ParametroValorBooleano(SYS_ParametroBO.eChave.PERMITIR_MULTIPLOS_ENDERECOS_ENTIDADE);
                UCEnderecos1.Inicializar(false, !permitirMultiplosEnderecos, "Entidade");

                UCComboTipoEntidade1.Inicialize("Tipo de entidade *");
                UCComboTipoEntidade1._EnableValidator = true;
                UCComboTipoEntidade1._ValidationGroup = "Endereco";
                UCComboTipoEntidade1._Load(0);

                UCComboTemaPadrao.Carregar();
                UCComboTemaPadrao_IndexChanged();

                if ((PreviousPage != null) && (PreviousPage.IsCrossPagePostBack))
                {
                    _VS_ent_id = PreviousPage.EditItem;

                    _LoadFromEntity();

                    _chkBloqueado.Visible  = true;
                    Page.Form.DefaultFocus = _txtRazaoSocial.ClientID;
                }
                else
                {
                    UCGridContato1._CarregarContato();

                    _chkBloqueado.Visible = false;
                    _chkBloqueado.Checked = false;

                    _VS_IsNew_end_id = true;

                    Page.Form.DefaultFocus  = UCComboTipoEntidade1._Combo.ClientID;
                    this._btnSalvar.Visible = __SessionWEB.__UsuarioWEB.GrupoPermissao.grp_inserir;
                }

                UCComboEntidade1.Inicialize("Entidade superior");
                UCComboEntidade1._EnableValidator = false;
                UCComboEntidade1._Load(_VS_ent_id, 0);

                Page.Form.DefaultButton = _btnSalvar.UniqueID;
            }
            catch (Exception ex)
            {
                ApplicationWEB._GravaErro(ex);
                _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar carregar o sistema.", UtilBO.TipoMensagem.Erro);
            }
        }
    }
    /// <summary>
    /// Insere e altera uma entidade
    /// </summary>
    private void _Salvar()
    {
        try
        {
            string msgErro;
            if (String.IsNullOrEmpty(_lblMessage.Text.Trim()) && !UCGridContato1.SalvaConteudoGrid(out msgErro))
            {
                UCGridContato1._MensagemErro.Visible = false;
                _lblMessage.Text     = msgErro;
                txtSelectedTab.Value = "2";
                return;
            }

            string    msg;
            DataTable dtEndereco;
            bool      cadastraEndereco = UCEnderecos1.RetornaEnderecoCadastrado(out dtEndereco, out msg);

            if (!cadastraEndereco)
            {
                throw new ValidationException(msg);
            }

            SYS_Entidade entityEntidade = new SYS_Entidade
            {
                ent_id = _VS_ent_id
                ,
                ten_id = new Guid(UCComboTipoEntidade1._Combo.SelectedValue)
                ,
                ent_razaoSocial = _txtRazaoSocial.Text
                ,
                ent_nomeFantasia = _txtNomeFantasia.Text
                ,
                ent_sigla = _txtSigla.Text
                ,
                ent_codigo = _txtCodigo.Text
                ,
                ent_cnpj = _txtCNPJ.Text
                ,
                ent_inscricaoEstadual = _txtIE.Text
                ,
                ent_inscricaoMunicipal = _txtIM.Text
                ,
                ent_idSuperior = new Guid(UCComboEntidade1._Combo.SelectedValue)
                ,
                ent_situacao = (_chkBloqueado.Checked ? Convert.ToByte(2) : Convert.ToByte(1))
                ,
                ent_urlAcesso = txtUrlAcesso.Text
                ,
                ent_logoCliente = !string.IsNullOrEmpty(fupLogoCliente.FileName) ?
                                  fupLogoCliente.FileName :
                                  (!string.IsNullOrEmpty(imgLogoCliente.ImageUrl) ? Path.GetFileName(imgLogoCliente.ImageUrl) : string.Empty)
                ,
                ent_exibeLogoCliente = chkExibeLogoCliente.Checked
                ,
                tep_id = UCComboTemaPadrao.Valor
                ,
                tpl_id = UCComboTemaPaleta.tpl_id
                ,
                IsNew = (_VS_ent_id != Guid.Empty) ? false : true
            };

            if (!entityEntidade.IsNew && string.IsNullOrEmpty(fupLogoCliente.FileName) && !string.IsNullOrEmpty(imgLogoCliente.ImageUrl))
            {
                entityEntidade.ent_logoCliente = entityEntidade.ent_logoCliente.Remove(0, entityEntidade.ent_id.ToString().Length + 1);
            }

            string tema = NomeTemaAtual;

            if (UCComboTemaPadrao.Valor > 0)
            {
                CFG_TemaPadrao entTema = new CFG_TemaPadrao {
                    tep_id = UCComboTemaPadrao.Valor
                };
                CFG_TemaPadraoBO.GetEntity(entTema);

                tema = entTema.tep_nome;
            }

            string caminho = Server.MapPath("~/App_Themes/" + tema + "/images/logos/");

            if (SYS_EntidadeBO.Save(entityEntidade, dtEndereco, UCGridContato1._VS_contatos, _VS_ent_idSuperiorAntigo, _VS_end_idAntigo, caminho, fupLogoCliente.FileName, fupLogoCliente.PostedFile, null))
            {
                if (_VS_ent_id == Guid.Empty)
                {
                    ApplicationWEB._GravaLogSistema(LOG_SistemaTipo.Insert, "ent_id: " + entityEntidade.ent_id);
                    __SessionWEB.PostMessages = UtilBO.GetErroMessage(String.Format("Entidade incluída com sucesso."), UtilBO.TipoMensagem.Sucesso);
                }
                else
                {
                    ApplicationWEB._GravaLogSistema(LOG_SistemaTipo.Update, "ent_id: " + entityEntidade.ent_id);
                    __SessionWEB.PostMessages = UtilBO.GetErroMessage(String.Format("Entidade alterada com sucesso."), UtilBO.TipoMensagem.Sucesso);
                }

                Response.Redirect(__SessionWEB._AreaAtual._Diretorio + "Entidade/Busca.aspx", false);
            }
            else
            {
                _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar salvar a entidade.", UtilBO.TipoMensagem.Erro);
            }
        }
        catch (ValidationException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (ArgumentException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (DuplicateNameException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (Exception ex)
        {
            ApplicationWEB._GravaErro(ex);
            _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar salvar a entidade.", UtilBO.TipoMensagem.Erro);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager sm = ScriptManager.GetCurrent(this);

        if (sm != null)
        {
            sm.Scripts.Add(new ScriptReference(ArquivoJS.PastaScriptRaiz + "Telas/jsUCCadastroContato.js"));
            sm.Scripts.Add(new ScriptReference(ArquivoJS.PastaScriptRaiz + "Telas/jsUCCadastroEndereco.js"));
            sm.Services.Add(new ServiceReference("~/WSServicos.asmx"));
        }

        if (!IsPostBack)
        {
            string ent_padrao = __SessionWEB.__UsuarioWEB.Usuario.ent_id.ToString();
            SetFocus(UCComboTipoUnidadeAdministrativa1);
            try
            {
                // Validação para utilização de múltiplos endereços para a unidade administrativa
                bool permitirMultiplosEnderecos = SYS_ParametroBO.ParametroValorBooleano(SYS_ParametroBO.eChave.PERMITIR_MULTIPLOS_ENDERECOS_UA);
                UCEnderecos1.Inicializar(false, !permitirMultiplosEnderecos, string.Empty);

                if (!string.IsNullOrEmpty(ent_padrao))
                {
                    _VS_ent_id = new Guid(ent_padrao);
                }

                UCComboEntidade1._ShowSelectMessage = true;
                if (__SessionWEB.__UsuarioWEB.Grupo.vis_id == SysVisaoID.Administracao)
                {
                    UCComboEntidade1._Load(Guid.Empty, 0);
                }
                else
                {
                    UCComboEntidade1._LoadBy_UsuarioGrupoUA(Guid.Empty, __SessionWEB.__UsuarioWEB.Grupo.gru_id, __SessionWEB.__UsuarioWEB.Usuario.usu_id, 0);
                }

                UCComboEntidade1.Inicialize("Entidade *");

                UCComboEntidade1._Combo.SelectedValue = string.IsNullOrEmpty(ent_padrao) ? Guid.Empty.ToString() : ent_padrao;

                UCComboTipoUnidadeAdministrativa1._ShowSelectMessage = true;
                UCComboTipoUnidadeAdministrativa1._Load(Guid.Empty, 0);
                UCComboTipoUnidadeAdministrativa1.Inicialize("Tipo de unidade administrativa *");

                if ((PreviousPage != null) && PreviousPage.IsCrossPagePostBack)
                {
                    _VS_ent_id = PreviousPage.EditItem_ent_id;
                    _VS_uad_id = PreviousPage.EditItem_uad_id;

                    _LoadFromEntity();

                    _chkBloqueado.Visible = true;

                    Page.Form.DefaultFocus = _txtNome.ClientID;
                }
                else
                {
                    UCGridContato1._CarregarContato();

                    _chkBloqueado.Visible = false;
                    _chkBloqueado.Checked = false;

                    _VS_IsNew_end_id = true;

                    Page.Form.DefaultFocus = UCComboEntidade1._Combo.ClientID;

                    this._btnSalvar.Visible = __SessionWEB.__UsuarioWEB.GrupoPermissao.grp_inserir;
                }

                UCUASuperior.VsGruId = __SessionWEB.__UsuarioWEB.Grupo.gru_id;
                UCUASuperior.VsUsuId = __SessionWEB.__UsuarioWEB.Usuario.usu_id;
                UCUASuperior.VsVisId = __SessionWEB.__UsuarioWEB.Grupo.vis_id;

                Page.Form.DefaultButton = _btnSalvar.UniqueID;
            }
            catch (Exception ex)
            {
                ApplicationWEB._GravaErro(ex);
                _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar carregar o sistema.", UtilBO.TipoMensagem.Erro);
            }
        }

        if (__SessionWEB.__UsuarioWEB.Grupo.vis_id == SysVisaoID.UnidadeAdministrativa)
        {
            UCComboEntidade1._Combo.Enabled = false;
        }

        Delegates();

        UCComboEntidade1.OnSelectedIndexChange += UCComboEntidade1__IndexChanged;
    }
    /// <summary>
    /// Insere e altera uma entidade
    /// </summary>
    private void _Salvar()
    {
        try
        {
            List <END_Endereco> ltEntityEndereco = new List <END_Endereco>();
            List <SYS_UnidadeAdministrativaEndereco> ltEntityUAEndereco = new List <SYS_UnidadeAdministrativaEndereco>();

            string  numero;
            string  complemento;
            string  msg;
            decimal latitude;
            decimal longitude;

            DataTable dt;

            bool cadastraEndereco = UCEnderecos1.RetornaEnderecoCadastrado(out dt, out msg);

            if (ValidaCampos(dt))
            {
                string msgErro = string.Empty;
                if (String.IsNullOrEmpty(_lblMessage.Text.Trim()) && !UCGridContato1.SalvaConteudoGrid(out msgErro))
                {
                    UCGridContato1._MensagemErro.Visible = false;
                    _lblMessage.Text     = msgErro;
                    txtSelectedTab.Value = "2";
                    return;
                }

                //   Cadastra Unidade Administrativa
                SYS_UnidadeAdministrativa entityUnidadeAdministrativa = new SYS_UnidadeAdministrativa
                {
                    ent_id = _VS_ent_id
                    ,
                    uad_id = _VS_uad_id
                    ,
                    tua_id = new Guid(UCComboTipoUnidadeAdministrativa1._Combo.SelectedValue)
                    ,
                    uad_nome = _txtNome.Text
                    ,
                    uad_sigla = _txtSigla.Text
                    ,
                    uad_codigo = _txtCodigo.Text
                    ,
                    uad_codigoInep = _txtCodigoInep.Text
                    ,
                    uad_idSuperior = UCUASuperior.VsUadId
                    ,
                    uad_codigoIntegracao = _txtCodigoIntegracao.Text
                    ,
                    uad_situacao = _chkBloqueado.Checked ? Convert.ToByte(2) : Convert.ToByte(1)
                    ,
                    IsNew = (_VS_uad_id != Guid.Empty) ? false : true
                };


                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (!cadastraEndereco)
                    {
                        throw new ValidationException(msg);
                    }

                    DataRow dr     = dt.Rows[i];
                    string  end_id = dr["end_id"].ToString();
                    Guid    uae_id = string.IsNullOrEmpty(dr["endRel_id"].ToString()) ? Guid.NewGuid() : new Guid(dr["endRel_id"].ToString());

                    int zona = 0;
                    if (!string.IsNullOrEmpty(dr["end_zona"].ToString()))
                    {
                        zona = Convert.ToInt16(dr["end_zona"].ToString());
                    }

                    bool excluido = Convert.ToBoolean(dr["excluido"]);

                    if ((String.IsNullOrEmpty(end_id)) || (end_id.Equals(Guid.Empty.ToString())))
                    {
                        ltEntityEndereco.Add(new END_Endereco
                        {
                            end_id         = new Guid(dr["id"].ToString()),
                            IsNew          = true,
                            cid_nome       = dr["cid_nome"].ToString(),
                            end_logradouro = dr["end_logradouro"].ToString(),
                            end_distrito   = dr["end_distrito"].ToString(),
                            end_zona       = (zona != 0) ? Convert.ToByte(dr["end_zona"].ToString()) : Convert.ToByte(0),
                            end_bairro     = dr["end_bairro"].ToString(),
                            cid_id         = new Guid(dr["cid_id"].ToString()),
                            end_cep        = dr["end_cep"].ToString(),
                            end_situacao   = Convert.ToByte(1)
                        });
                    }
                    else
                    {
                        END_Endereco entityEndereco = new END_Endereco();
                        entityEndereco.end_id = new Guid(dr["end_id"].ToString());
                        entityEndereco.IsNew  = false;

                        END_EnderecoBO.GetEntity(entityEndereco);

                        entityEndereco.cid_id         = new Guid(dr["cid_id"].ToString());
                        entityEndereco.cid_nome       = dr["cid_nome"].ToString();
                        entityEndereco.end_logradouro = dr["end_logradouro"].ToString();
                        entityEndereco.end_distrito   = dr["end_distrito"].ToString();
                        entityEndereco.end_zona       = (zona != 0) ? Convert.ToByte(dr["end_zona"].ToString()) : Convert.ToByte(0);
                        entityEndereco.end_bairro     = dr["end_bairro"].ToString();
                        entityEndereco.end_cep        = dr["end_cep"].ToString();
                        entityEndereco.end_situacao   = (excluido) ? Convert.ToByte(3) : Convert.ToByte(1);
                        ltEntityEndereco.Add(entityEndereco);
                    }
                    numero      = dr["numero"].ToString();
                    complemento = dr["complemento"].ToString();
                    latitude    = string.IsNullOrEmpty(dr["latitude"].ToString()) ? 0 : decimal.Parse(dr["latitude"].ToString());
                    longitude   = string.IsNullOrEmpty(dr["longitude"].ToString()) ? 0 : decimal.Parse(dr["longitude"].ToString());

                    bool excluirEndereco = String.IsNullOrEmpty(dr["end_cep"].ToString()) && !_VS_IsNew_end_id;


                    if (!String.IsNullOrEmpty(ltEntityEndereco[i].end_cep))
                    {
                        ltEntityUAEndereco.Add(new SYS_UnidadeAdministrativaEndereco()
                        {
                            ent_id                = _VS_ent_id,
                            uad_id                = _VS_uad_id,
                            end_id                = ltEntityEndereco[i].end_id,
                            uae_numero            = numero,
                            uae_complemento       = complemento,
                            uae_situacao          = (excluido) ? Convert.ToByte(3) : Convert.ToByte(1),
                            IsNew                 = (string.IsNullOrEmpty(dr["novo"].ToString()) ? false : Convert.ToBoolean(dr["novo"].ToString())),
                            uae_latitude          = latitude,
                            uae_longitude         = longitude,
                            uae_id                = uae_id,
                            uae_enderecoPrincipal = (string.IsNullOrEmpty(dr["enderecoprincipal"].ToString()) ? false : Convert.ToBoolean(dr["enderecoprincipal"].ToString())),
                        });
                    }
                }

                if (SYS_UnidadeAdministrativaBO.Save(entityUnidadeAdministrativa, ltEntityEndereco, ltEntityUAEndereco, UCGridContato1._VS_contatos, _VS_uad_idSuperiorAntigo, _VS_end_idAntigo, null))
                {
                    if (_VS_uad_id == Guid.Empty)
                    {
                        ApplicationWEB._GravaLogSistema(LOG_SistemaTipo.Insert, "ent_id: " + entityUnidadeAdministrativa.ent_id + "; uad_id: " + entityUnidadeAdministrativa.uad_id);
                        __SessionWEB.PostMessages = UtilBO.GetErroMessage(String.Format("Unidade administrativa incluída com sucesso."), UtilBO.TipoMensagem.Sucesso);
                    }
                    else
                    {
                        ApplicationWEB._GravaLogSistema(LOG_SistemaTipo.Update, "ent_id: " + entityUnidadeAdministrativa.ent_id + "; uad_id: " + entityUnidadeAdministrativa.uad_id);
                        __SessionWEB.PostMessages = UtilBO.GetErroMessage(String.Format("Unidade administrativa alterada com sucesso."), UtilBO.TipoMensagem.Sucesso);
                    }

                    Response.Redirect(__SessionWEB._AreaAtual._Diretorio + "UA/Busca.aspx", false);
                }
                else
                {
                    _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar salvar a unidade administrativa.", UtilBO.TipoMensagem.Erro);
                }
            }
        }
        catch (ValidationException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
            SetFocus(ValidationSummary1);
        }
        catch (ArgumentException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
            SetFocus(ValidationSummary1);
        }
        catch (DuplicateNameException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
            SetFocus(ValidationSummary1);
        }
        catch (Exception ex)
        {
            ApplicationWEB._GravaErro(ex);
            _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar salvar a unidade administrativa.", UtilBO.TipoMensagem.Erro);
            SetFocus(ValidationSummary1);
        }
    }
    /// <summary>
    /// Carrega os dados da unidade administrativa nos controles caso seja alteração.
    /// </summary>
    private void _LoadFromEntity()
    {
        try
        {
            SYS_UnidadeAdministrativa uad = new SYS_UnidadeAdministrativa {
                ent_id = _VS_ent_id, uad_id = _VS_uad_id
            };
            SYS_UnidadeAdministrativaBO.GetEntity(uad);

            _VS_ent_id = uad.ent_id;
            _VS_uad_id = uad.uad_id;

            UCUASuperior.VsUadId = _VS_uad_idSuperiorAntigo = uad.uad_idSuperior;
            UCUASuperior._Limpar();

            UCComboEntidade1._Combo.SelectedValue = uad.ent_id.ToString();
            UCComboTipoUnidadeAdministrativa1._Combo.SelectedValue = uad.tua_id.ToString();
            _txtNome.Text             = uad.uad_nome;
            _txtSigla.Text            = !string.IsNullOrEmpty(uad.uad_sigla) ? uad.uad_sigla : string.Empty;
            _txtCodigo.Text           = !string.IsNullOrEmpty(uad.uad_codigo) ? uad.uad_codigo : string.Empty;
            _txtCodigoInep.Text       = !string.IsNullOrEmpty(uad.uad_codigoInep) ? uad.uad_codigoInep : string.Empty;
            _txtCodigoIntegracao.Text = uad.uad_codigoIntegracao;

            _chkBloqueado.Checked = uad.uad_situacao == 2;

            //List<SYS_UnidadeAdministrativaEnderecoBO.sUnidadeAdministrativaEndereco> ListEnderecoUA =
            //    SYS_UnidadeAdministrativaEnderecoBO.SelecionaEndereco(uad.ent_id, uad.uad_id);

            //[OLD] DataTable dtEnderecoUA = SYS_UnidadeAdministrativaEnderecoBO.SelecionaEndereco(uad.ent_id, uad.uad_id);
            DataTable dtEnderecoUA = SYS_UnidadeAdministrativaEnderecoBO.CarregaEnderecos(uad.ent_id, uad.uad_id);

            //foreach (SYS_UnidadeAdministrativaEnderecoBO.sUnidadeAdministrativaEndereco uaEndereco in ListEnderecoUA)
            //{
            //    if (uaEndereco.endereco.end_id != Guid.Empty)
            //    {
            //UCEnderecos1.CarregarEndereco(uaEndereco.endereco, uaEndereco.unidadeAdministrativaEndereco.uae_numero,
            //    uaEndereco.unidadeAdministrativaEndereco.uae_complemento
            //   , uaEndereco.unidadeAdministrativaEndereco.uae_latitude
            //   , uaEndereco.unidadeAdministrativaEndereco.uae_longitude
            //   , uaEndereco.unidadeAdministrativaEndereco.uae_enderecoPrincipal);

            UCEnderecos1.CarregarEnderecosBanco(dtEnderecoUA);

            _VS_IsNew_end_id = false;
            //_VS_end_idAntigo = uaEndereco.endereco.end_id;
            //    }
            //    else
            //    {
            //        _VS_IsNew_end_id = true;
            //    }
            //}

            DataTable dt = SYS_UnidadeAdministrativaContatoBO.GetSelect(_VS_ent_id, _VS_uad_id, false, 1, 1);
            if (dt.Rows.Count == 0)
            {
                dt = null;
            }

            UCGridContato1._VS_contatos = dt;
            UCGridContato1._CarregarContato();

            UCComboEntidade1._Combo.Enabled = false;
            UCComboTipoUnidadeAdministrativa1._Combo.Enabled = false;

            if (uad.uad_idSuperior != Guid.Empty)
            {
                UCUASuperior._PesquisarUASuperior(uad.ent_id, uad.uad_idSuperior);
                _txtUad_nome.Text = UCUASuperior.VsUadNome;
            }
        }
        catch (Exception ex)
        {
            ApplicationWEB._GravaErro(ex);
            _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar carregar a unidade administrativa.", UtilBO.TipoMensagem.Erro);
        }
    }