public static void ensureUniqueCodigo(PersistencyHelper.PreConcArguments args) { PersistencyHelper.EnsureUniqueCodigoNivelPreConcArguments pcArgs = null; pcArgs = (PersistencyHelper.EnsureUniqueCodigoNivelPreConcArguments)args; GISADataset.NivelRow nRow = (GISADataset.NivelRow)(GisaDataSetHelper.GetInstance().Nivel.Select("ID=" + pcArgs.nRowID.ToString())[0]); GISADataset.NivelDesignadoRow ndRow = (GISADataset.NivelDesignadoRow)(GisaDataSetHelper.GetInstance().NivelDesignado.Select("ID=" + pcArgs.ndRowID.ToString())[0]); GISADataset.RelacaoHierarquicaRow rhRow = null; if (GisaDataSetHelper.GetInstance().RelacaoHierarquica.Select(string.Format("ID={0} AND IDUpper={1}", pcArgs.rhRowID, pcArgs.rhRowIDUpper)).Length > 0) { rhRow = (GISADataset.RelacaoHierarquicaRow)(GisaDataSetHelper.GetInstance().RelacaoHierarquica.Select(string.Format("ID={0} AND IDUpper={1}", pcArgs.rhRowID, pcArgs.rhRowIDUpper))[0]); } // Se o nível em questão for uma entidade detentora if (rhRow == null && nRow.TipoNivelRow.ID == TipoNivel.LOGICO) { if (DBAbstractDataLayer.DataAccessRules.NivelRule.Current.isUniqueCodigo(nRow.Codigo, nRow.ID, pcArgs.tran, pcArgs.testOnlyWithinNivel)) { pcArgs.successful = true; } else { var cod = nRow.Codigo; System.Data.DataSet tempgisaBackup1 = pcArgs.gisaBackup; PersistencyHelper.BackupRow(ref tempgisaBackup1, ndRow); pcArgs.gisaBackup = tempgisaBackup1; System.Data.DataSet tempgisaBackup2 = pcArgs.gisaBackup; PersistencyHelper.BackupRow(ref tempgisaBackup2, nRow); pcArgs.gisaBackup = tempgisaBackup2; ndRow.RejectChanges(); PermissoesHelper.UndoAddNivelGrantPermissions(nRow); nRow.RejectChanges(); pcArgs.message = string.Format( "Não é possível completar a operação porque não é permitido " + Environment.NewLine + "que duas unidades de informação tenham o mesmo código " + Environment.NewLine + "parcial ({0}) no mesmo nivel de descrição.", cod); } } else { // antes de obter o código verificar se adição de um novo nível ainda é possível (por razões // de concorrência é necessário garantir que tanto o nível acima mantém-se na base de dados // até o save estar terminado) bool upperRelationExists; if (rhRow.IDUpper < 0) { upperRelationExists = true; } else { upperRelationExists = NivelRule.Current.isNivelDeleted(rhRow.IDUpper, args.tran); } if (!upperRelationExists) { var frdRow = GisaDataSetHelper.GetInstance().FRDBase.Cast <GISADataset.FRDBaseRow>().Single(r => r.ID == pcArgs.frdBaseID); Nivel.DeleteInDataSet(frdRow, false, pcArgs.gisaBackup); Nivel.DeleteInDataSet(nRow, false, pcArgs.gisaBackup); pcArgs.message = "Não foi possível criar/editar a unidade informacional uma" + Environment.NewLine + "vez que a unidade superior foi apagada por outro utilizador."; } else { if (DBAbstractDataLayer.DataAccessRules.NivelRule.Current.isUniqueCodigo(nRow.Codigo, nRow.ID, pcArgs.tran, pcArgs.testOnlyWithinNivel, rhRow.NivelRowByNivelRelacaoHierarquicaUpper.ID)) { pcArgs.successful = true; } else { var cod = nRow.Codigo; if (nRow.RowState == DataRowState.Modified) { nRow.RejectChanges(); GisaDataSetHelper.GetInstance().IndexFRDCA.Cast <GISADataset.IndexFRDCARow>() .Where(r => r.RowState != DataRowState.Unchanged).ToList().ForEach(r => r.RejectChanges()); } else if (nRow.RowState == DataRowState.Added) { var frdRow = GisaDataSetHelper.GetInstance().FRDBase.Cast <GISADataset.FRDBaseRow>().Single(r => r.ID == pcArgs.frdBaseID); Nivel.DeleteInDataSet(frdRow, false, pcArgs.gisaBackup); Nivel.DeleteInDataSet(nRow, false, pcArgs.gisaBackup); } pcArgs.message = string.Format( "Não é possível completar a operação porque não é permitido " + Environment.NewLine + "que duas unidades de informação tenham o mesmo código " + Environment.NewLine + "parcial ({0}) no mesmo nivel de descrição.", cod); } } } }
// Trata a criação de novos níveis e respectivas relações. Caso se trate // de um nível orgânico (estrutural e que esteja associado a uma EP) o // nível correspondente deverá já existir e não será por isso criado, // será criada apenas a relação. private bool handleNewNivel(Form frm, GISADataset.NivelRow parentNivelRow, GISADataset.TipoNivelRelacionadoRow tnrRow) { frm.Text = "Criar " + tnrRow.Designacao; bool successfulSave = true; switch (frm.ShowDialog()) { case DialogResult.OK: Trace.WriteLine("A criar nível..."); long click = DateTime.Now.Ticks; string designacaoUFAssociada = string.Empty; PostSaveAction postSaveAction = null; var nRow = GisaDataSetHelper.GetInstance().Nivel.AddNivelRow(tnrRow.TipoNivelRow, ((FormAddNivel)frm).txtCodigo.Text.Trim(), "NVL", new byte[] { }, 0); var ndRow = GisaDataSetHelper.GetInstance().NivelDesignado.AddNivelDesignadoRow(nRow, ((FormAddNivel)frm).txtDesignacao.Text.Trim(), new byte[] { }, 0); var frdRow = GisaDataSetHelper.GetInstance().FRDBase.AddFRDBaseRow(nRow, (GISADataset.TipoFRDBaseRow)(GisaDataSetHelper.GetInstance().TipoFRDBase.Select("ID=" + DomainValuesHelper.stringifyEnumValue(TipoFRDBase.FRDOIRecolha))[0]), "", "", new byte[] { }, 0); var rhRow = GisaDataSetHelper.GetInstance().RelacaoHierarquica.AddRelacaoHierarquicaRow(nRow, parentNivelRow, tnrRow, null, null, null, null, null, null, null, new byte[] { }, 0); //valores por omissão var globalConfig = GisaDataSetHelper.GetInstance().GlobalConfig.Cast <GISADataset.GlobalConfigRow>().Single(); if (globalConfig.ApplyDefaultValues) { var sfrdcaRow = GisaDataSetHelper.GetInstance().SFRDCondicaoDeAcesso .AddSFRDCondicaoDeAcessoRow(frdRow, "", globalConfig.IsCondicaoDeAcessoNull() ? "" : globalConfig.CondicaoDeAcesso, globalConfig.IsCondicaoDeReproducaoNull() ? "" : globalConfig.CondicaoDeReproducao, "", new byte[] {}, 0); foreach (GISADataset.ConfigLinguaRow r in globalConfig.GetConfigLinguaRows()) { GisaDataSetHelper.GetInstance().SFRDLingua.AddSFRDLinguaRow(sfrdcaRow, r.Iso639Row, new byte[] { }, 0); } foreach (GISADataset.ConfigAlfabetoRow r in globalConfig.GetConfigAlfabetoRows()) { GisaDataSetHelper.GetInstance().SFRDAlfabeto.AddSFRDAlfabetoRow(sfrdcaRow, r.Iso15924Row, new byte[] { }, 0); } } var selectedTipologia = ((FormNivelDocumentalFedora)frm).Tipologia; if (selectedTipologia != null) { GisaDataSetHelper.GetInstance().IndexFRDCA.AddIndexFRDCARow(frdRow, selectedTipologia.ControloAutRow, -1, new byte[] { }, 0); } // Só adicionar permissões ao grupo TODOS dos níveis lógicos e a níveis documentais imediatamente // abaixo de níveis orgânicos (Documentos soltos e séries); caso se se trate de um nível estrutural // controlado, as permissões já foram atribuidas aquando da criação do controlo de autoridade if (nRow.IDTipoNivel == TipoNivel.DOCUMENTAL && parentNivelRow.IDTipoNivel == TipoNivel.ESTRUTURAL) { var nUpperRow = rhRow == null ? default(GISADataset.NivelRow) : rhRow.NivelRowByNivelRelacaoHierarquicaUpper; PermissoesHelper.AddNewNivelGrantPermissions(nRow, nUpperRow); } postSaveAction = new PostSaveAction(); var args = new PersistencyHelper.GenericPostSaveArguments(); postSaveAction.args = args; postSaveAction.postSaveDelegate = delegate(PersistencyHelper.PostSaveArguments postSaveArgs) { if (!postSaveArgs.cancelAction && nRow != null && nRow.RowState != DataRowState.Detached && nRow.RowState != DataRowState.Deleted) { // registar a criação do nivel documental GISADataset.FRDBaseRow frdDocRow = null; GISADataset.FRDBaseRow[] frdDocRows = nRow.GetFRDBaseRows(); if (frdDocRows.Length > 0) { frdDocRow = frdDocRows[0]; } CurrentContext.RaiseRegisterModificationEvent(frdDocRow); PersistencyHelperRule.Current.saveRows(GisaDataSetHelper.GetInstance().FRDBaseDataDeDescricao, GisaDataSetHelper.GetInstance().FRDBaseDataDeDescricao.Cast <GISADataset.FRDBaseDataDeDescricaoRow>().Where(frd => frd.RowState == DataRowState.Added).ToArray(), postSaveArgs.tran); } }; // se se tratar de um (sub)documento é necessário garantir que se trata de um código // único dentro da sua série (se constituir série) ou nivel estrutural superior PersistencyHelper.ValidateNivelAddAndAssocNewUFPreConcArguments pcArgs = new PersistencyHelper.ValidateNivelAddAndAssocNewUFPreConcArguments(); PersistencyHelper.SetNewCodigosPreSaveArguments psArgs = new PersistencyHelper.SetNewCodigosPreSaveArguments(); PersistencyHelper.EnsureUniqueCodigoNivelPreConcArguments pcArgsNivel = new PersistencyHelper.EnsureUniqueCodigoNivelPreConcArguments(); pcArgs.argsNivel = pcArgsNivel; // dados que serão usados no delegate responsável pela criação do nível documental pcArgsNivel.nRowID = nRow.ID; pcArgsNivel.ndRowID = ndRow.ID; pcArgsNivel.rhRowID = rhRow.ID; pcArgsNivel.rhRowIDUpper = rhRow.IDUpper; pcArgsNivel.frdBaseID = frdRow.ID; pcArgsNivel.testOnlyWithinNivel = true; // permitir ao delegate selecionar o delegate correspondente ao tipo de nível que se está a criar pcArgs.IDTipoNivelRelacionado = tnrRow.ID; psArgs.createNewNivelCodigo = false; psArgs.createNewUFCodigo = false; psArgs.setNewCodigo = rhRow.IDTipoNivelRelacionado == TipoNivelRelacionado.SD; psArgs.argsNivelDocSimples = NiveisHelper.AddNivelDocumentoSimplesWithDelegateArgs(nRow.GetNivelDesignadoRows().Single(), rhRow.IDUpper, rhRow.IDTipoNivelRelacionado); PersistencyHelper.save(DelegatesHelper.ValidateNivelAddAndAssocNewUF, pcArgs, DelegatesHelper.SetNewCodigos, psArgs, postSaveAction); if (!pcArgsNivel.successful) { successfulSave = false; MessageBox.Show(pcArgsNivel.message, "Criação de unidade de descrição", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (parentNivelRow.GetRelacaoHierarquicaRowsByNivelRelacaoHierarquica()[0].TipoNivelRelacionadoRow.ID == TipoNivelRelacionado.SR) { GisaDataSetHelper.HoldOpen ho = new GisaDataSetHelper.HoldOpen(GisaDataSetHelper.GetConnection()); try { DBAbstractDataLayer.DataAccessRules.FRDRule.Current.LoadSFRDAvaliacaoData(GisaDataSetHelper.GetInstance(), parentNivelRow.ID, ho.Connection); } finally { ho.Dispose(); } } PersistencyHelper.cleanDeletedData(new List <TableDepthOrdered.TableCloudType>(new TableDepthOrdered.TableCloudType[] { PersistencyHelper.determinaNuvem("RelacaoHierarquica"), PersistencyHelper.determinaNuvem("FRDBase") })); if (!successfulSave) { return(successfulSave); } GISA.Search.Updater.updateNivelDocumentalComProdutores(nRow.ID); GISA.Search.Updater.updateNivelDocumental(nRow.ID); this.nivelNavigator1.AddNivel(nRow); Debug.WriteLine("<<A criar nível...>> " + new TimeSpan(DateTime.Now.Ticks - click).ToString()); break; case DialogResult.Cancel: successfulSave = false; break; } return(successfulSave); }
protected override void AcceptContents(object Value) { GISADataset.ControloAutRow ControloAutRow = (GISADataset.ControloAutRow)Value; if (FRDBase != null) { // Carregar nivel do CA largado IDbConnection conn = GisaDataSetHelper.GetConnection(); try { conn.Open(); DBAbstractDataLayer.DataAccessRules.NivelRule.Current.LoadNivelByControloAut(ControloAutRow.ID, GisaDataSetHelper.GetInstance(), conn); } finally { conn.Close(); } if (IsValidRelacaoHierarquica(ControloAutRow)) { // Apresentar form que permita escolher a data da relação FormRelacaoHierarquica frmRh = new FormRelacaoHierarquica(); // Pode-se obter a primeira relação encontrada para efeitos de determinação // do tipo de nível uma vez que o tipo de nível dos níveis documentais nunca se alterará frmRh.relacaoNvl.TipoNivelRelacionadoRow = TipoNivelRelacionado.GetPrimeiraRelacaoEncontrada(this.FRDBase.NivelRow).TipoNivelRelacionadoRow; frmRh.relacaoNvl.ContextNivelRow = ControloAutRow.GetNivelControloAutRows()[0].NivelRow; if (frmRh.ShowDialog() == DialogResult.Cancel) { return; } if (GisaDataSetHelper.GetInstance().RelacaoHierarquica.Select(string.Format("ID={0} AND IDUpper={1}", this.FRDBase.NivelRow.ID, ControloAutRow.GetNivelControloAutRows()[0].NivelRow.ID), "", DataViewRowState.Deleted).Length > 0) { GisaDataSetHelper.GetInstance().RelacaoHierarquica.Select(string.Format("ID={0} AND IDUpper={1}", this.FRDBase.NivelRow.ID, ControloAutRow.GetNivelControloAutRows()[0].NivelRow.ID), "", DataViewRowState.Deleted)[0].AcceptChanges(); } GISADataset.RelacaoHierarquicaRow rhRow = null; rhRow = GisaDataSetHelper.GetInstance().RelacaoHierarquica.NewRelacaoHierarquicaRow(); TempRelacaoHierarquica = rhRow; rhRow.ID = this.FRDBase.NivelRow.ID; rhRow.IDUpper = ControloAutRow.GetNivelControloAutRows()[0].NivelRow.ID; rhRow.IDTipoNivelRelacionado = TipoNivelRelacionado.GetTipoNivelRelacionadoDaPrimeiraRelacaoEncontrada(this.FRDBase.NivelRow).ID; rhRow.Descricao = frmRh.relacaoNvl.txtDescricao.Text; rhRow.InicioAno = frmRh.relacaoNvl.dtRelacaoInicio.ValueYear; rhRow.InicioMes = frmRh.relacaoNvl.dtRelacaoInicio.ValueMonth; rhRow.InicioDia = frmRh.relacaoNvl.dtRelacaoInicio.ValueDay; rhRow.FimAno = frmRh.relacaoNvl.dtRelacaoFim.ValueYear; rhRow.FimMes = frmRh.relacaoNvl.dtRelacaoFim.ValueMonth; rhRow.FimDia = frmRh.relacaoNvl.dtRelacaoFim.ValueDay; GisaDataSetHelper.GetInstance().RelacaoHierarquica.AddRelacaoHierarquicaRow(rhRow); // no caso de se tratar de uma entidade produtora é necessário validar o código de referência do nivel documental do contexto if (ControloAutRow.IDTipoNoticiaAut == (long)TipoNoticiaAut.EntidadeProdutora) { var argsPC = new PersistencyHelper.EnsureUniqueCodigoNivelPreConcArguments(); argsPC.rhRowID = rhRow.ID; argsPC.rhRowIDUpper = rhRow.IDUpper; var postSaveAction = new PostSaveAction(); PersistencyHelper.UpdatePermissionsPostSaveArguments args = new PersistencyHelper.UpdatePermissionsPostSaveArguments(); postSaveAction.args = args; postSaveAction.postSaveDelegate = delegate(PersistencyHelper.PostSaveArguments postSaveArgs) { if (argsPC.successful) { if (this.parent == null) Debug.Assert(false, "CONTEXTO PARENT DEVE ESTAR DEFINIDO."); if (this.parent.GetType() == typeof(MasterPanelSeries)) { ((MasterPanelSeries)this.parent).CurrentContext.RaiseRegisterModificationEvent(this.FRDBase); PersistencyHelperRule.Current.saveRows(GisaDataSetHelper.GetInstance().FRDBaseDataDeDescricao, GisaDataSetHelper.GetInstance().FRDBaseDataDeDescricao.Cast<GISADataset.FRDBaseDataDeDescricaoRow>().Where(r => r.RowState == DataRowState.Added).ToArray(), postSaveArgs.tran); } } }; var result = PersistencyHelper.save(DelegatesHelper.verificaCodigosRepetidos, argsPC, postSaveAction, true); if (result == PersistencyHelper.SaveResult.successful) { PersistencyHelper.cleanDeletedData(); GisaDataSetHelper.VisitControloAutDicionario(ControloAutRow, DisplayFormaAutorizada); GISA.Search.Updater.updateNivelDocumental(this.FRDBase.NivelRow.ID); } else { if (argsPC.message.Length > 0) MessageBox.Show(argsPC.message, "Adição", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } else { MessageBox.Show("Não é possível a existência de items repetidos.", "Adição", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else if (this.ControloAut != null) { Debug.Assert(false, "ORGANIC RELATIONS BETWEEN CAS NOT IMPLEMENTED. SHOULDN'T BE NEEDED"); } }
private void EditNivel() { var nRow = this.nivelNavigator1.SelectedNivel; var frdRow = nRow.GetFRDBaseRows().Single(); var rhRow = nRow.GetRelacaoHierarquicaRowsByNivelRelacaoHierarquica().First(); var tnrRow = TipoNivelRelacionado.GetTipoNivelRelacionadoFromRelacaoHierarquica(rhRow); var frm = new FormNivelDocumentalFedora(); frm.IDTipoNivelRelacionado = tnrRow.ID; string WindowTitle = string.Format("Editar {0}", tnrRow.Designacao); frm.Text = WindowTitle; frm.txtCodigo.Text = nRow.Codigo; frm.txtDesignacao.Text = Nivel.GetDesignacao(nRow); frm.FRDBaseRow = nRow.GetFRDBaseRows().Single(); frm.LoadData(); var idxFRDCARow = frdRow.GetIndexFRDCARows().SingleOrDefault(r => r["Selector"] != DBNull.Value && r.Selector == -1); // show form and receive user feedback if (frm.ShowDialog() == DialogResult.OK) { Trace.WriteLine("A editar nível..."); GISADataset.NivelDesignadoRow ndRow = null; nRow.Codigo = frm.txtCodigo.Text; // Um Nivel documental deve ter obrigatoriamente um NivelDesignado. Debug.Assert(nRow.GetNivelDesignadoRows().Length > 0); ndRow = nRow.GetNivelDesignadoRows()[0]; ndRow.Designacao = frm.txtDesignacao.Text; var tipologiaSelected = ((FormNivelDocumentalFedora)frm).Tipologia; if (tipologiaSelected == null && idxFRDCARow != null) { idxFRDCARow.Delete(); } else if (tipologiaSelected != null && idxFRDCARow == null) { idxFRDCARow = GisaDataSetHelper.GetInstance().IndexFRDCA.AddIndexFRDCARow(frdRow, ((FormNivelDocumentalFedora)frm).Tipologia.ControloAutRow, -1, new byte[] { }, 0); } else if (tipologiaSelected != null && idxFRDCARow != null && idxFRDCARow.IDControloAut != tipologiaSelected.IDControloAut) { idxFRDCARow.Delete(); idxFRDCARow = GisaDataSetHelper.GetInstance().IndexFRDCA.AddIndexFRDCARow(frdRow, ((FormNivelDocumentalFedora)frm).Tipologia.ControloAutRow, -1, new byte[] { }, 0); } string termoToCompare = frm.Tipologia == null ? null : ((FormNivelDocumentalFedora)frm).Tipologia.DicionarioRow.Termo; if (objetoDigital != null && objetoDigital.tipologia != termoToCompare) { objetoDigital.tipologia = tipologiaSelected != null ? tipologiaSelected.DicionarioRow.Termo : ""; objetoDigital.state = State.modified; } // registar a edição do item selecionado CurrentContext.RaiseRegisterModificationEvent(nRow.GetFRDBaseRows()[0]); PersistencyHelper.EnsureUniqueCodigoNivelPreConcArguments pcArgs = new PersistencyHelper.EnsureUniqueCodigoNivelPreConcArguments(); pcArgs.nRowID = nRow.ID; pcArgs.ndRowID = ndRow.ID; // Se se tratar de uma entidade detentora não passar os Ids de uma relação // hierárquica para um nível superior pois não existe nenhum. if (nRow.GetRelacaoHierarquicaRowsByNivelRelacaoHierarquica().Length > 0) { pcArgs.rhRowID = nRow.GetRelacaoHierarquicaRowsByNivelRelacaoHierarquica()[0].ID; pcArgs.rhRowIDUpper = nRow.GetRelacaoHierarquicaRowsByNivelRelacaoHierarquica()[0].IDUpper; } pcArgs.testOnlyWithinNivel = true; // actualizar objecto digital caso exista var preTransactionAction = new PreTransactionAction(); var args = new PersistencyHelper.FedoraIngestPreTransactionArguments(); preTransactionAction.args = args; preTransactionAction.preTransactionDelegate = delegate(PersistencyHelper.PreTransactionArguments preTransactionArgs) { string msg = null; if (objetoDigital != null) { preTransactionArgs.cancelAction = !SessionHelper.AppConfiguration.GetCurrentAppconfiguration().FedoraHelperSingleton.Ingest(objetoDigital, out msg); } preTransactionArgs.message = msg; }; PersistencyHelper.SaveResult successfulSave = PersistencyHelper.save(DelegatesHelper.ensureUniqueCodigo, pcArgs, preTransactionAction); if (!pcArgs.successful) { MessageBox.Show(pcArgs.message, "Edição da unidade de descrição", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (successfulSave == PersistencyHelper.SaveResult.successful) { GisaDataSetHelper.HoldOpen ho = new GisaDataSetHelper.HoldOpen(GisaDataSetHelper.GetConnection()); try { List <string> IDNiveis = new List <string>(); IDNiveis.Add(nRow.ID.ToString()); GISA.Search.Updater.updateNivelDocumental(IDNiveis); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); throw; } finally { ho.Dispose(); } } PersistencyHelper.cleanDeletedData(); // Actualizar a interface com os novos valores. Se editarmos a // raiz (estrutural) da vista documental é necessário actualizar // automaticamente também a vista estrutural. if (!(nRow.RowState == DataRowState.Detached)) { if (this.nivelNavigator1.PanelToggleState == NivelNavigator.ToggleState.Estrutural) { this.nivelNavigator1.UpdateSelectedNodeName(Nivel.GetDesignacao(nRow)); } else { this.nivelNavigator1.UpdateSelectedListItemName(Nivel.GetDesignacao(nRow)); } } // Forçar a gravação do documento CurrentContext.SetNivelEstrututalDocumental(null); CurrentContext.SetNivelEstrututalDocumental(nRow); } }