Пример #1
0
        private void btnEdit_Click(object sender, EventArgs e)
        {
            DataRow relRow = null;

            relRow = (DataRow)(lstVwRelacoes.SelectedItems[0].Tag);

            // verificar se tanto a entidade produtora seleccionada como contexto como a relação seleccionada
            // para edição não foram apagadas concorrentemente por outro utilizador
            if (CurrentControloAut.RowState == DataRowState.Detached)
            {
                MessageBox.Show("Não é possível editar qualquer relação da entidade produtora " + System.Environment.NewLine + "selecionada uma vez que foi apagada por outro utilizador.", "Edição de Relações", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                lstVwRelacoes.SelectedItems.Clear();
                lstVwRelacoes.Items.Clear();
                return;
            }
            else if (relRow.RowState == DataRowState.Detached)
            {
                MessageBox.Show("Não é possível editar a relação selecionada uma " + System.Environment.NewLine + "vez que foi apagada por outro utilizador.", "Edição de Relações", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                ListViewItem lvItem = lstVwRelacoes.SelectedItems[0];
                lstVwRelacoes.SelectedItems.Clear();
                lstVwRelacoes.Items.Remove(lvItem);
                return;
            }

            GISADataset.ControloAutRow        caRow  = null;
            GISADataset.ControloAutRelRow     carRow = null;
            GISADataset.RelacaoHierarquicaRow rhRow  = null;

            FormControloAutRel frm = null;

            if (relRow is GISADataset.ControloAutRelRow)
            {
                frm = new FormControloAutRel(CurrentControloAut, ((frmMain)TopLevelControl).MasterPanel);

                carRow = (GISADataset.ControloAutRelRow)relRow;
                if (carRow.ControloAutRowByControloAutControloAutRel == CurrentControloAut)
                {
                    caRow = carRow.ControloAutRowByControloAutControloAutRelAlias;
                }
                else if (carRow.ControloAutRowByControloAutControloAutRelAlias == CurrentControloAut)
                {
                    caRow = carRow.ControloAutRowByControloAutControloAutRel;
                    // nas edições, ao visualizar uma relação pelo outro extremo é necessário alterar a designação da relação apresentada
                    frm.relacaoCA.cbTipoControloAutRel.DisplayMember = "Designacao";
                }
            }
            else if (relRow is GISADataset.RelacaoHierarquicaRow)
            {
                rhRow = (GISADataset.RelacaoHierarquicaRow)relRow;
                caRow = rhRow.NivelRowByNivelRelacaoHierarquica.GetNivelControloAutRows()[0].ControloAutRow;
                // Se estivermos a ver o extremo errado da relação hierarquica trocamos para o outro extremo
                if (CurrentControloAut == caRow)
                {
                    caRow = rhRow.NivelRowByNivelRelacaoHierarquicaUpper.GetNivelControloAutRows()[0].ControloAutRow;

                    frm = new FormControloAutRel(caRow, ((frmMain)TopLevelControl).MasterPanel);
                    // nas edições, ao visualizar uma relação pelo outro extremo é necessário alterar a designação da relação apresentada
                    frm.relacaoCA.cbTipoControloAutRel.DisplayMember = "Designacao";
                }
                else
                {
                    frm = new FormControloAutRel(CurrentControloAut, ((frmMain)TopLevelControl).MasterPanel);
                }
            }

            GISADataset.ControloAutDicionarioRow cadRow = null;
            string termo = null;

            cadRow = ControloAutHelper.getFormaAutorizada(caRow);
            termo  = cadRow.DicionarioRow.Termo;

            frm.ContextRel = relRow;
            frm.caList.AllowedNoticiaAut(TipoNoticiaAut.EntidadeProdutora);
            frm.caList.SelectedItems.Clear();
            frm.caList.txtFiltroDesignacao.Text = termo.Trim();
            frm.caList.ReloadList();
            frm.caList.SelectItem(cadRow);

            frm.caList.txtFiltroDesignacao.Clear();
            // popular datas
            frm.relacaoCA.dtRelacaoInicio.ValueYear  = GisaDataSetHelper.GetDBNullableText(relRow, "InicioAno");
            frm.relacaoCA.dtRelacaoInicio.ValueMonth = GisaDataSetHelper.GetDBNullableText(relRow, "InicioMes");
            frm.relacaoCA.dtRelacaoInicio.ValueDay   = GisaDataSetHelper.GetDBNullableText(relRow, "InicioDia");
            frm.relacaoCA.dtRelacaoFim.ValueYear     = GisaDataSetHelper.GetDBNullableText(relRow, "FimAno");
            frm.relacaoCA.dtRelacaoFim.ValueMonth    = GisaDataSetHelper.GetDBNullableText(relRow, "FimMes");
            frm.relacaoCA.dtRelacaoFim.ValueDay      = GisaDataSetHelper.GetDBNullableText(relRow, "FimDia");
            frm.relacaoCA.txtDescricao.Text          = GisaDataSetHelper.GetDBNullableText(relRow, "Descricao");

            // Encontrar e selecionar o TipoControloAutRel correcto
            if (relRow is GISADataset.ControloAutRelRow)
            {
                foreach (object drView in frm.relacaoCA.cbTipoControloAutRel.Items)
                {
                    if (((GISADataset.TipoControloAutRelRow)drView).ID == carRow.TipoControloAutRelRow.ID)
                    {
                        frm.relacaoCA.cbTipoControloAutRel.SelectedItem = drView;
                    }
                }
            }
            else if (relRow is GISADataset.RelacaoHierarquicaRow)
            {
                foreach (object drView in frm.relacaoCA.cbTipoControloAutRel.Items)
                {
                    if (((GISADataset.TipoControloAutRelRow)drView).ID == Convert.ToInt64(TipoControloAutRel.Hierarquica))
                    {
                        frm.relacaoCA.cbTipoControloAutRel.SelectedItem = drView;
                        break;
                    }
                }

                bool foundTipoNivel = false;
                foreach (TipoNivelRelacionado.PossibleSubNivel subNivel in frm.relacaoCA.cbTipoNivel.Items)
                {
                    if (subNivel.SubIDTipoNivelRelacionado == rhRow.IDTipoNivelRelacionado)
                    {
                        frm.relacaoCA.cbTipoNivel.SelectedItem = subNivel;
                        foundTipoNivel = true;
                        break;
                    }
                }

                // O tipo de nivel já definido pode nao ser encontrado entre os possiveis
                // se o tipo de nivel do pai tiver entretanto também ele mudado. Nesse caso
                // adicionamos mais esse tipo de nivel de forma a ser mantida a selecção
                // anteriormente existente.
                if (!foundTipoNivel)
                {
                    ArrayList data = null;
                    data = (ArrayList)frm.relacaoCA.cbTipoNivel.DataSource;
                    TipoNivelRelacionado.PossibleSubNivel subTipoNivel = null;
                    string inicioAno = string.Empty;
                    string inicioMes = string.Empty;
                    string inicioDia = string.Empty;
                    string fimAno    = string.Empty;
                    string fimMes    = string.Empty;
                    string fimDia    = string.Empty;

                    if (!rhRow.IsInicioAnoNull())
                    {
                        inicioAno = rhRow.InicioAno;
                    }
                    if (!rhRow.IsInicioMesNull())
                    {
                        inicioMes = rhRow.InicioMes;
                    }
                    if (!rhRow.IsInicioDiaNull())
                    {
                        inicioDia = rhRow.InicioDia;
                    }

                    if (!rhRow.IsFimAnoNull())
                    {
                        fimAno = rhRow.FimAno;
                    }
                    if (!rhRow.IsFimMesNull())
                    {
                        fimMes = rhRow.FimMes;
                    }
                    if (!rhRow.IsFimDiaNull())
                    {
                        fimDia = rhRow.FimDia;
                    }

                    subTipoNivel = new TipoNivelRelacionado.PossibleSubNivel(rhRow.IDTipoNivelRelacionado, rhRow.TipoNivelRelacionadoRow.Designacao, inicioAno, inicioMes, inicioDia, fimAno, fimMes, fimDia, true);
                    int idx = data.Add(subTipoNivel);

                    frm.relacaoCA.cbTipoNivel.ImageIndexes.Add(SharedResourcesOld.CurrentSharedResources.NivelImageBase(System.Convert.ToInt32(subTipoNivel.SubIDTipoNivelRelacionado)));
                    frm.relacaoCA.cbTipoNivel.DataSource    = null;
                    frm.relacaoCA.cbTipoNivel.DataSource    = data;
                    frm.relacaoCA.cbTipoNivel.DisplayMember = "DesignacaoComposta";
                    frm.relacaoCA.cbTipoNivel.SelectedItem  = subTipoNivel;
                }
            }
            RetrieveSelection(frm, relRow);
        }
Пример #2
0
//INSTANT C# NOTE: C# does not support optional parameters. Overloaded method(s) are created above.
//ORIGINAL LINE: Public Shared Sub DeleteControloAut(ByVal caList As ControloAutList, ByVal Caption As String, ByVal Interrogacao As String, ByVal MessageBoxText As String, Optional ByVal caller As Control = null)
		public static void DeleteControloAut(ControloAutList caList, string Caption, string Interrogacao, string MessageBoxText, Control caller)
		{

			bool HasDocumentData = false;
            List<string> nivelIDsAssoc = new List<string>();
			string Detalhes = null;
			
            if (caller != null) ((frmMain)caller.TopLevelControl).EnterWaitMode();
            Detalhes = ControloAutHelper.GetControloAutUsage(caList.SelectedItems.Cast<ListViewItem>().Select(i => i.Tag as GISADataset.ControloAutDicionarioRow).ToList(), ref HasDocumentData, ref nivelIDsAssoc);
            if (caller != null) ((frmMain)caller.TopLevelControl).LeaveWaitMode();

			if (Detalhes.Length > 0)
			{
                FormDeletionReport form = new FormDeletionReport();
                form.Text = Caption;
                form.Interrogacao = Interrogacao;
                form.Detalhes = Detalhes;
				if (HasDocumentData)
				{
                    form.SetBtnOKVisible(false);
                    form.Interrogacao = "Este elemento não pode ser removido enquanto lhe existirem associados níveis documentais.";
				}

                if (form.ShowDialog() == DialogResult.Cancel) return;
			}
			else
			{
				switch (MessageBox.Show(MessageBoxText, Caption, MessageBoxButtons.OKCancel))
				{
					case System.Windows.Forms.DialogResult.OK:
					break;
					case System.Windows.Forms.DialogResult.Cancel:
						return;
					default:
						Debug.Assert(false, "Unexpected DialogResult.");
						break;
				}
			}

			Trace.WriteLine("A apagar notícia de autoridade...");

			ListViewItem selectedItem = null;
			if (caList.SelectedItems.Count > 0)
			{
				Debug.Assert(caList.SelectedItems.Count == 1, "Só deveria existir 1 item selecionado.");
				selectedItem = caList.SelectedItems[0];

				GISADataset.ControloAutDicionarioRow cadRow = null;
				GISADataset.ControloAutRow caRow = null;
				cadRow = (GISADataset.ControloAutDicionarioRow)selectedItem.Tag;
				caRow = cadRow.ControloAutRow;

				// Remover a selecção do item vai provocar uma mudança de contexto que 
				// por sua vez vai provocar uma gravação dos dados
				caList.ClearItemSelection(selectedItem);

                var ho = default(GisaDataSetHelper.HoldOpen);
                if (caller != null && caller.GetType() == typeof(MasterPanelControloAut))
                {
                    ((MasterPanelControloAut)caller).CurrentContext.RaiseRegisterModificationEvent(caRow);

                    if (caRow.IDTipoNoticiaAut == (long)TipoNoticiaAut.EntidadeProdutora)
                    {
                        var frdRow = default(GISADataset.FRDBaseRow);
                        long IDTipoNivelRelacionado = -1;
                        ho = new GisaDataSetHelper.HoldOpen(GisaDataSetHelper.GetConnection());
                        try
                        {
                            DBAbstractDataLayer.DataAccessRules.FRDRule.Current.LoadFRD(GisaDataSetHelper.GetInstance(), caRow.GetNivelControloAutRows().Single().ID, ho.Connection);
                            frdRow = caRow.GetNivelControloAutRows().Single().NivelRow.GetFRDBaseRows().SingleOrDefault();
                            DBAbstractDataLayer.DataAccessRules.NivelRule.Current.LoadNivelParents(caRow.GetNivelControloAutRows().Single().ID, GisaDataSetHelper.GetInstance(), ho.Connection);
                            if (frdRow != null)
                                IDTipoNivelRelacionado = DBAbstractDataLayer.DataAccessRules.NivelRule.Current.GetNivelLastIDTipoNivelRelacionado(frdRow.ID, ho.Connection);
                        }
                        finally
                        {
                            ho.Dispose();
                        }

                        if (frdRow != null) // frd pode ainda não ter sido criado
                        {
                            var caRegRow = GisaDataSetHelper.GetInstance().ControloAutDataDeDescricao.Cast<GISADataset.ControloAutDataDeDescricaoRow>().Single(r => r.RowState == DataRowState.Added);
                            var nvlRegRow = RecordRegisterHelper
                                            .CreateFRDBaseDataDeDescricaoRow(frdRow,
                                                caRegRow.TrusteeUserRowByTrusteeUserControloAutDataDeDescricao,
                                                caRegRow.TrusteeUserRowByTrusteeUserControloAutDataDeDescricaoAuthority,
                                                caRegRow.DataAutoria,
                                                IDTipoNivelRelacionado);
                            nvlRegRow.DataEdicao = caRegRow.DataEdicao;

                            GisaDataSetHelper.GetInstance().FRDBaseDataDeDescricao.AddFRDBaseDataDeDescricaoRow(nvlRegRow);
                        }
                    }
                }

				selectedItem.Remove();

                ho = new GisaDataSetHelper.HoldOpen(GisaDataSetHelper.GetConnection());
                List<long> lowerIDsList = new List<long>();
                try {
                    lowerIDsList = DiplomaModeloRule.Current.GetIDLowers(caRow.ID, ho.Connection);
                } 
                finally {
                    ho.Dispose();
                }

				// Como os dados acabaram de ser gravados pode ter-se chegado à conclusão que o contexto existente já não existia, daí este teste
				if (caRow.RowState != DataRowState.Detached)
				{
					try
					{
                        var oldTermo = caRow.GetControloAutDicionarioRows().Single(cad => cad.IDTipoControloAutForma == (long)TipoControloAutForma.FormaAutorizada).DicionarioRow.Termo;
                        var IDTipoNoticiaAut = caRow.IDTipoNoticiaAut;
						PersistencyHelper.DeleteIDXPreSaveArguments preSaveArgs = new PersistencyHelper.DeleteIDXPreSaveArguments();
						GISADataset.NivelControloAutRow[] ncaRows = null;
						GISADataset.NivelRow nRow = null;
						ncaRows = caRow.GetNivelControloAutRows();
						if (ncaRows.Length > 0)
						{
							nRow = ((GISADataset.NivelControloAutRow)(ncaRows[0])).NivelRow;
							preSaveArgs.ID = nRow.ID;
						}
						PersistencyHelper.DeleteCAXPreConcArguments preConcArgs = DeleteCAX(caRow);
                        PersistencyHelper.SaveResult successfulSave = PersistencyHelper.save(deleteCAXTermos, preConcArgs, Nivel.DeleteNivelXInDataBase, preSaveArgs);
						PersistencyHelper.cleanDeletedData();

                        if (successfulSave == PersistencyHelper.SaveResult.successful) {
                            if (SessionHelper.AppConfiguration.GetCurrentAppconfiguration().IsFedoraEnable())
                                SessionHelper.AppConfiguration.GetCurrentAppconfiguration().FedoraHelperSingleton.ActualizaObjDigitaisPorNivel(nivelIDsAssoc, oldTermo, null, IDTipoNoticiaAut);
                            Search.Updater.updateNivelDocumental(nivelIDsAssoc);
                            Search.Updater.updateNivelDocumentalComProdutores(lowerIDsList.Select(t => t.ToString()).ToList<string>());
                        }
					}
					catch (Exception ex)
					{
						Trace.WriteLine(ex);
						throw;
					}
				}
                else
                    GisaDataSetHelper.GetInstance().ControloAutDataDeDescricao.Cast<GISADataset.ControloAutDataDeDescricaoRow>().Single(r => r.RowState == DataRowState.Added && r.IDControloAut == caRow.ID).RejectChanges();
			}
		}
Пример #3
0
        public override void ModelToView()
        {
            IsPopulated = false;
            lstVwRelacoes.Items.Clear();

            // Apresentar relações não hierarquicas
            string carId = CurrentControloAut.ID.ToString();

            QueryFilter = "IDControloAut=" + carId + " OR IDControloAutAlias=" + carId;
            foreach (GISADataset.ControloAutRelRow caRel in GisaDataSetHelper.GetInstance().ControloAutRel.Select(QueryFilter, "InicioAno, InicioMes, InicioDia, FimAno, FimMes, FimDia"))
            {
                if (caRel.TipoControloAutRelRow.ID != Convert.ToInt64(TipoControloAutRel.Instituicao))                 //System.Enum.Format(GetType(TipoControloAutRel), TipoControloAutRel.Instituicao, "D") Then
                {
                    GISADataset.ControloAutRow OtherControloAut = null;
                    if (caRel.ControloAutRowByControloAutControloAutRelAlias.ID != CurrentControloAut.ID)
                    {
                        OtherControloAut = caRel.ControloAutRowByControloAutControloAutRelAlias;
                    }
                    else
                    {
                        OtherControloAut = caRel.ControloAutRowByControloAutControloAutRel;
                    }
                    foreach (GISADataset.ControloAutDicionarioRow cad in OtherControloAut.GetControloAutDicionarioRows())
                    {
                        if (cad.IDTipoControloAutForma == Convert.ToInt64(TipoControloAutForma.FormaAutorizada))
                        {
                            ListViewItem tempWith1 = lstVwRelacoes.Items.Add(cad.DicionarioRow.Termo);
                            tempWith1.Tag = caRel;
                            if (cad.ControloAutRow.IsChaveColectividadeNull())
                            {
                                tempWith1.SubItems.Add(string.Empty);
                            }
                            else
                            {
                                tempWith1.SubItems.Add(cad.ControloAutRow.ChaveColectividade);
                            }
                            string rezDesTipoRel = null;
                            if (caRel.ControloAutRowByControloAutControloAutRelAlias.ID != CurrentControloAut.ID)
                            {
                                rezDesTipoRel = caRel.TipoControloAutRelRow.DesignacaoInversa;
                            }
                            else
                            {
                                rezDesTipoRel = caRel.TipoControloAutRelRow.Designacao;
                            }
                            tempWith1.SubItems.Add(rezDesTipoRel);
                            tempWith1.SubItems.Add(GUIHelper.GUIHelper.FormatStartDate(caRel));
                            tempWith1.SubItems.Add(GUIHelper.GUIHelper.FormatEndDate(caRel));
                            tempWith1.SubItems.Add(GUIHelper.GUIHelper.ClipText(caRel.Descricao));
                        }
                    }
                }
            }

            // Apresentar relações hierarquicas
            GISADataset.NivelRow nRow = null;
            GISADataset.NivelControloAutRow[] ncaRows = null;
            GISADataset.NivelControloAutRow   ncaRow  = null;
            ncaRows = CurrentControloAut.GetNivelControloAutRows();
            if (ncaRows.Length == 0)
            {
                MasterPanelControloAut.CreateAssociatedNivel(CurrentControloAut, ref nRow, ref ncaRow);
                try
                {
                    PersistencyHelper.save();
                    PersistencyHelper.cleanDeletedData();
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(ex);
                    throw;
                }
            }
            else
            {
                ncaRow = ncaRows[0];
                nRow   = ncaRow.NivelRow;
            }

            foreach (GISADataset.RelacaoHierarquicaRow rhRow in GisaDataSetHelper.GetInstance().RelacaoHierarquica.Select(string.Format("ID={0} OR IDUpper={0}", nRow.ID), "InicioAno, InicioMes, InicioDia, FimAno, FimMes, FimDia"))
            {
                // Só adicionar relações hierárquicas existentes entre níveis estruturais. Este teste não seria suficiente no caso de existirem níveis estruturais orgânicos relacionados com níveis estruturais temático-funcionais, mas tal não poderá acontecer em qualquer situação.
                if (rhRow.NivelRowByNivelRelacaoHierarquica.TipoNivelRow.ID == TipoNivel.ESTRUTURAL && rhRow.NivelRowByNivelRelacaoHierarquicaUpper.TipoNivelRow.ID == TipoNivel.ESTRUTURAL)
                {
                    GISADataset.ControloAutRow caRow = null;
                    caRow = rhRow.NivelRowByNivelRelacaoHierarquica.GetNivelControloAutRows()[0].ControloAutRow;
                    // Se estivermos a ver o extremo errado da relação hierarquica trocamos para o outro extremo
                    if (CurrentControloAut == caRow)
                    {
                        caRow = rhRow.NivelRowByNivelRelacaoHierarquicaUpper.GetNivelControloAutRows()[0].ControloAutRow;
                    }

                    GISADataset.ControloAutDicionarioRow cadRow = null;
                    cadRow = ControloAutHelper.getFormaAutorizada(caRow);

                    ListViewItem newItem = lstVwRelacoes.Items.Add(cadRow.DicionarioRow.Termo);
                    newItem.Tag = rhRow;
                    AddRelacaoHierarquicaToList(newItem);
                }
            }

            RefreshButtonState();
            PopulateDescricaoText();
            IsPopulated = true;
        }
Пример #4
0
		private void setNewTermo(PersistencyHelper.PreConcArguments args)
		{
			try
			{
				PersistencyHelper.ManageFormasAutorizadasPreConcArguments mfaPca = (PersistencyHelper.ManageFormasAutorizadasPreConcArguments)args;
				string termo = mfaPca.termo;
				GISADataset.ControloAutRow carow = (GISADataset.ControloAutRow)(GisaDataSetHelper.GetInstance().ControloAut.Select("ID=" + mfaPca.caRowID.ToString())[0]);
				GISADataset.TipoControloAutFormaRow tcafRowAutorizado = (GISADataset.TipoControloAutFormaRow)(GisaDataSetHelper.GetInstance().TipoControloAutForma.Select("ID=" + System.Enum.Format(typeof(TipoControloAutForma), TipoControloAutForma.FormaAutorizada, "D"))[0]);
				DataSet gisaBackup = mfaPca.gisaBackup;
				//Dim dataReader As IDataReader
				GISADataset.DicionarioRow dRowOrig = null;
				GISADataset.ControloAutDicionarioRow cadRowOrig = ControloAutHelper.getFormaAutorizada(carow);
				bool existsOrigCad = false;

				ArrayList termoUsed = DiplomaModeloRule.Current.GetDicionario(getCatCode(carow.TipoNoticiaAutRow), termo.Trim(), mfaPca.tran);

				// Distinguir entre criar e editar um Diploma/Modelo
				if (carow.ID < 0)
				{
					// Criar Diploma/Modelo:
					//  - verificar se o termo escolhido existe na base de dados e se nesse caso, verificar se
					//    está a ser utilizado noutro Diploma/Modelo
					if (((long)(termoUsed[0])) > 0 && (bool)(termoUsed[1]))
					{
						// A designação já existe na base de dados mas está marcada como apagada
						mfaPca.cadRow = manageDesignacaoDiplomaModelo(mfaPca.cadRow, mfaPca.termo, carow.TipoNoticiaAutRow, carow, tcafRowAutorizado);
					}
					else if (((long)(termoUsed[0])) > 0 && ! ((bool)(termoUsed[1])))
					{
						// A designação já existe na base de dados mas não está marcada como apagada; no entanto, 
						// é preciso saber se está a ser usada por outro Diploma/Modelo (tipicamente, nesta 
						// situação a designação está a ser utilizada por um Diploma/Modelo mas já aconteceu não 
						// estar a ser utilizada fruto de uma resolução de conflito de concorrência)
						if (DiplomaModeloRule.Current.ExistsControloAutDicionario((long)(termoUsed[0]), 1, carow.TipoNoticiaAutRow.ID, mfaPca.tran))
						{
							carow.RejectChanges();
							mfaPca.message = "A designação especificada já existe, deverá escolhê-la da lista caso a pretenda utilizar.";
						}
						else
						{
							mfaPca.cadRow = manageDesignacaoDiplomaModelo(mfaPca.cadRow, mfaPca.termo, carow.TipoNoticiaAutRow, carow, tcafRowAutorizado);
						}
					}
					else
					{
						// A designação não existe na base de dados
						mfaPca.cadRow = manageDesignacaoDiplomaModelo(mfaPca.cadRow, mfaPca.termo, carow.TipoNoticiaAutRow, carow, tcafRowAutorizado);
					}
				}
				else
				{
					// Editar Diploma/Modelo
					//  - verificar se entretanto outro utilizador já editou o Diploma/Modelo
					//  - verificar se o termo escolhido existe na base de dados e se nesse caso, verificar se
					//    está a ser utilizado noutro Diploma/Modelo
					existsOrigCad = DiplomaModeloRule.Current.ExistsControloAutDicionario(cadRowOrig.IDDicionario, cadRowOrig.IDTipoControloAutForma, carow.TipoNoticiaAutRow.ID, mfaPca.tran);

					dRowOrig = cadRowOrig.DicionarioRow;

					PersistencyHelper.BackupRow(ref gisaBackup, cadRowOrig);
					PersistencyHelper.BackupRow(ref gisaBackup, dRowOrig);

					cadRowOrig.Delete();
					// é permitido apagar o termo antigo uma vez que é único para diplomas/modelo
					dRowOrig.Delete();

					if (existsOrigCad)
					{
						// o Diploma/Modelo não foi editado por nenhum outro utilizador
						if (((long)(termoUsed[0])) > 0 && (bool)(termoUsed[1]))
						{
							// A designação já existe na base de dados mas está marcada como apagada
							mfaPca.cadRow = manageDesignacaoDiplomaModelo(mfaPca.cadRow, mfaPca.termo, carow.TipoNoticiaAutRow, carow, tcafRowAutorizado);
						}
						else if (((long)(termoUsed[0])) > 0 && ! ((bool)(termoUsed[1])))
						{
							// A designação já existe na base de dados mas não está marcada como apagada; no entanto, 
							// é preciso saber se está a ser usada por outro Diploma/Modelo (tipicamente, nesta 
							// situação a designação está a ser utilizada por um Diploma/Modelo mas já aconteceu não 
							// estar a ser utilizada fruto de uma resolução de conflito de concorrência)
							if (DiplomaModeloRule.Current.ExistsControloAutDicionario((long)(termoUsed[0]), 1, carow.TipoNoticiaAutRow.ID, mfaPca.tran))
							{
								dRowOrig.RejectChanges();
								cadRowOrig.RejectChanges();
								mfaPca.message = "A designação especificada já existe, deverá escolhê-la da lista caso a pretenda utilizar.";
							}
							else
							{
								mfaPca.cadRow = manageDesignacaoDiplomaModelo(mfaPca.cadRow, mfaPca.termo, carow.TipoNoticiaAutRow, carow, tcafRowAutorizado);
							}
						}
						else
						{
							// A designação não existe na base de dados
							mfaPca.cadRow = manageDesignacaoDiplomaModelo(mfaPca.cadRow, mfaPca.termo, carow.TipoNoticiaAutRow, carow, tcafRowAutorizado);
						}
					}
					else
					{
						// Outro utilizador já editou este Diploma/Modelo pelo que não é possível reeditá-lo
						dRowOrig.RejectChanges();
						cadRowOrig.RejectChanges();
						mfaPca.message = "Não foi possível executar a operação pretendida pois o controlo de autoridade foi alterado por outro utilizador.";
					}
				}
			}
			catch (Exception ex)
			{
				Trace.WriteLine(ex);
				throw;
			}
		}