From a056f6d78ba088560b6c2e69688b34eb8cb9d19d Mon Sep 17 00:00:00 2001 From: Elena Date: Thu, 12 Jan 2023 01:05:54 +0100 Subject: [PATCH] =?UTF-8?q?Modificaciones=20varias=20=C3=BAltima=20versi?= =?UTF-8?q?=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Helper/HelperGdb.cs | 175 ++++++++++++------ Services/EjecServ.cs | 154 ++++++++++++--- Services/ProcesoEjecServ.cs | 9 +- .../Recogida/PaneRecogidaSub1ViewModel.cs | 1 + 4 files changed, 259 insertions(+), 80 deletions(-) diff --git a/Helper/HelperGdb.cs b/Helper/HelperGdb.cs index 00bf54f..65d5111 100644 --- a/Helper/HelperGdb.cs +++ b/Helper/HelperGdb.cs @@ -435,44 +435,124 @@ namespace OliviaAddInPro.Helper } - //Dado un path de una feature class devuelve la ftclass abierta directamente, - //o null si ha habido algún problema o no lo ha encontrado - public static FeatureClass GetFtClass(string pathFtClss) - { - FeatureClass ftclss = null; - if (string.IsNullOrEmpty(pathFtClss)) - return null; - Geodatabase gdb = GetGdb(pathFtClss).Result; - ReiniciaOutStr(); - if (gdb != null) - { - ftclss = GetFtClass(System.IO.Path.GetFileNameWithoutExtension(pathFtClss), gdb).Result; - } - else //mira a ver si es shapefile - { - ftclss = GetFtClassFromShp(pathFtClss).Result; - } - Free(gdb); - return ftclss; - } //Dado un path de una feature class devuelve la ftclass abierta directamente, //o null si ha habido algún problema o no lo ha encontrado public static FeatureClass GetFtClassSync(string pathFtClss) { FeatureClass ftclss = null; + FeatureDataset dtset = null; if (string.IsNullOrEmpty(pathFtClss)) return null; Geodatabase gdb = GetGdbSync(pathFtClss); ReiniciaOutStr(); if (gdb != null) { - ftclss = GetFtClassSync(System.IO.Path.GetFileNameWithoutExtension(pathFtClss), gdb); + string dtsetName = new DirectoryInfo(System.IO.Path.GetDirectoryName(pathFtClss)).Name; + try + { + dtset = gdb.OpenDataset(dtsetName); + } + catch (Exception ex) + { + HelperGdb.OutStr = "Error al abrir Dataset " + dtsetName + ": " + ex.Message; + dtset= null; + } + + string ftclassName = System.IO.Path.GetFileNameWithoutExtension(pathFtClss); + if (dtset != null) + { + try + { + ftclss = dtset.OpenDataset(ftclassName); + } + catch (Exception ex) + { + ftclss = null; + } + } + else + { + try + { + ftclss = gdb.OpenDataset(ftclassName); + } + catch (Exception ex) + { + ftclss = null; + } + } + if(ftclss==null) + HelperGdb.OutStr = "Error al abrir Feature Class " + ftclassName; } else //mira a ver si es shapefile { ftclss = GetFtClassFromShpSync(pathFtClss); } Free(gdb); + Free(dtset); + return ftclss; + } + //Dado un path de una feature class devuelve la ftclass abierta directamente, + //o null si ha habido algún problema o no lo ha encontrado + public static FeatureClass GetFtClass(string pathFtClss) + { + FeatureClass ftclss = null; + FeatureDataset dtset = null; + if (string.IsNullOrEmpty(pathFtClss)) + return null; + Geodatabase gdb = GetGdb(pathFtClss).Result; + ReiniciaOutStr(); + + if (gdb != null) + { + var task = ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run((Func)(() => + { + string dtsetName = new DirectoryInfo(System.IO.Path.GetDirectoryName(pathFtClss)).Name; + try + { + dtset = gdb.OpenDataset(dtsetName); + } + catch (Exception ex) + { + HelperGdb.OutStr = "Error al abrir Dataset " + dtsetName + ": " + ex.Message; + dtset = null; + } + + string ftclassName = System.IO.Path.GetFileNameWithoutExtension(pathFtClss); + if (dtset != null) + { + try + { + ftclss = dtset.OpenDataset(ftclassName); + } + catch (Exception ex) + { + ftclss = null; + } + } + else + { + try + { + ftclss = gdb.OpenDataset(ftclassName); + } + catch (Exception ex) + { + ftclss = null; + } + } + if (ftclss == null) + HelperGdb.OutStr = "Error al abrir Feature Class " + ftclassName; + return ftclss; + })); + task.Wait(); + } + else //mira a ver si es shapefile + { + ftclss = GetFtClassFromShp(pathFtClss).Result; + } + Free(gdb); + Free(dtset); return ftclss; } //Dado el path de una gdb y el nombre de una feature class, devuelve la @@ -487,7 +567,7 @@ namespace OliviaAddInPro.Helper { try { - ftclss = gdb.OpenDataset(nameFtclss); + ftclss = gdb.OpenDataset(nameFtclss); } catch (Exception ex) { @@ -1164,25 +1244,7 @@ namespace OliviaAddInPro.Helper return geomsal; })); } - /** - * Devuelve el número de entidades de una FeatureClass que cumplen la consulta, o todos si la consulta es empty - */ - public static int GetNumElems(string pathGdb, string ftclssName, string consulta = "") - { - Geodatabase gdb = GetGdb(pathGdb).Result; - FeatureClass fc = null; - int n = -1; - if (gdb != null) - { - fc = GetFtClass(ftclssName, gdb).Result; - if (fc != null) - n = GetNumElems(fc, consulta).Result; - } - Free(fc); - Free(gdb); - return n; - - } + /** * Devuelve los valores únicos de un campo dado */ @@ -2090,7 +2152,8 @@ namespace OliviaAddInPro.Helper try { FeatureDatasetDefinition featureDatasetDefinition = gdb.GetDefinition(datasetName); - if(featureDatasetDefinition.GetSpatialReference().Equals(spatref)) + ArcGIS.Core.Geometry.SpatialReference entr = featureDatasetDefinition.GetSpatialReference(); + if (entr.Wkid==spatref.Wkid) return 0; return 2; } @@ -2103,7 +2166,10 @@ namespace OliviaAddInPro.Helper /** * Crea un FeatureDataset con el nombre dado y la spatialrefernece dada en la gdb dada - * Devuelve 0 si no hay que crear nada o si lo ha creado bien, 2 si existe el dataset pero con otra referencia espacial, 1 si da error + * Devuelve 0 si no hay que crear nada, existe y coincide ref espac + * 2 si existe el dataset pero con otra referencia espacial, así que se crea otro + * 1 si da error + * 4 si no existe así que se crea */ public static Respuesta CreateDataset(string gdbPath, string datasetName, ArcGIS.Core.Geometry.SpatialReference spatref, out string datasetNameOut) { @@ -2125,6 +2191,7 @@ namespace OliviaAddInPro.Helper bool crea = false; int idat = 1; int r = 2; + bool refspatdif = false; while(r==2) { var task1 = CheckDataset(gdb, datasetName); @@ -2142,7 +2209,8 @@ namespace OliviaAddInPro.Helper { //existe ese nombre, pero con otra ref espacial //crea un nuevo dataset y avisa - datasetName = string.Format("{0}_{1}",datasetName,idat); + datasetName = string.Format("{0}_{1}",datasetName,idat); + refspatdif = true; idat++; } else//r==1 @@ -2188,10 +2256,11 @@ namespace OliviaAddInPro.Helper task.Wait(); if (task.Result.Value)//ha ido bien { - if (string.IsNullOrEmpty(datasetNameOut)) - res.Value = 0; + //avisa + if (refspatdif) + res.Value = 2; else - res.Value = 2;//avisa + res.Value = 4; //actualiza la gdb Refresh(gdbPath); } @@ -2319,18 +2388,18 @@ namespace OliviaAddInPro.Helper * Devuelve -1 si da error al abrir la gdb, -2 si da error al abrir el ftclass (igual porque no existe) * y 0 si da error el proceso de borrar, y 1 si va todo bien */ - public static Respuesta DeleteFeatureClassSync(string gdbPath, string featureClassName) + public static Respuesta DeleteFeatureClassSync(string gdbPathDataset, string featureClassName) { var res = new Respuesta { Value = 0 }; - Geodatabase gdb = GetGdbSync(gdbPath); + Geodatabase gdb = GetGdbSync(gdbPathDataset); if (gdb == null) { res.Value = -1; return res; } - FeatureClass ftclss = GetFtClassSync(featureClassName, gdb); + FeatureClass ftclss = GetFtClassSync(gdbPathDataset + " \\"+ featureClassName); if (ftclss == null) { res.Value = -2; @@ -2371,15 +2440,15 @@ namespace OliviaAddInPro.Helper /** * Borrar una feature class de un dataset */ - public static Respuesta DeleteFeatureClass(string gdbPath, string featureClassName) + public static Respuesta DeleteFeatureClass(string gdbPathDataset, string featureClassName) { var res = new Respuesta { Value = false }; - Geodatabase gdb = GetGdb(gdbPath).Result; + Geodatabase gdb = GetGdb(gdbPathDataset).Result; if (gdb == null) return res; - FeatureClass ftclss = GetFtClass(featureClassName,gdb).Result; + FeatureClass ftclss = GetFtClass(gdbPathDataset + " \\" + featureClassName); if (ftclss == null) return res; diff --git a/Services/EjecServ.cs b/Services/EjecServ.cs index 2efb5c6..f4e014c 100644 --- a/Services/EjecServ.cs +++ b/Services/EjecServ.cs @@ -175,6 +175,14 @@ namespace OliviaAddInPro.Services return false; } + ///////////////////////////////////////////////////////////////////// + ///Comprueba si está la columna de ObjectId y si no, la crea + if(!ComprCreaColOid(OliviaGlob.Paths.PathData, com.CapaElems, filtroEspacial)) + { + ErrStr = "Error al exportar columna " + ComunDef.CamposCom.camp_oid; + return false; + } + /////////////////////////////////////////////////////////////////////// //ahora si está en modo planificación, ya ha hecho una ejec antes y la capa no tiene esa columna pero la tiene guardada de la ejec anterior, exporta la sectorización if (modo==ModosEjec.Planifica && !string.IsNullOrEmpty(com.CapaPlanif) && OliviaGlob.IsConfig2()) @@ -240,22 +248,7 @@ namespace OliviaAddInPro.Services { ErrStr = "Error al añadir buffer a la geometría"; return false; - } - //quita las restricciones - if (com.GeomRestr != null) - { - geom_export = HelperGdb.QuitaGeom(geom_export, com.GeomRestr); - if (geom_export == null) - { - ErrStr = "Error al intersecar con las restricciones."; - return false; - } - } - if (com.ProgrSrc._ProgrSrc.Getcancelled()) - { - ErrStr = Resource1.String_cancel_progreso; - return false; - } + } ////////////////////////////////////////////////////////////// //comprueba si la geometría de exportación contiene a la instalación y a la planta de descarga for (int i = 0; i < coords.Length; i++) @@ -288,13 +281,28 @@ namespace OliviaAddInPro.Services else ErrStr = "Error al incluir punto de instalación en polígono de exportación."; return false; - } + } //actualiza la geometría geom_export = respGeom.Value; } } } } + //quita las restricciones de circ + if (com.GeomRestr != null) + { + geom_export = HelperGdb.QuitaGeom(geom_export, com.GeomRestr); + if (geom_export == null) + { + ErrStr = "Error al intersecar con las restricciones."; + return false; + } + } + if (com.ProgrSrc._ProgrSrc.Getcancelled()) + { + ErrStr = Resource1.String_cancel_progreso; + return false; + } //mira spatialreference del nw /*FeatureClass fc = HelperGdb.GetFtClass(OliviaGlob.Paths.PathGdbNw); @@ -496,8 +504,103 @@ namespace OliviaAddInPro.Services } /** - * Prepara la geometría para exportar los ámbitos + * Comrpueba si existe la columna de oid y si no, la crea y la rellena */ + public bool ComprCreaColOid(string pathCapa, string pathCapaOrig, SpatialQueryFilter filter) + { + //comprueba si está el campo + int NCAMPS = 1; + string[] camps; + camps = new string[NCAMPS]; + camps[0] = ComunDef.CamposCom.camp_oid; + int compCamp = HelperGdb.CheckFileds(pathCapa, camps); + ErrStr = HelperGdb.OutStr; + if (compCamp == 0) + return true; //tiene el campo + + //no lo tiene, lo crea + //Añade al shp exportado la columna de sector y secuencia + HelperGdb.FieldToAdd[] fields = new HelperGdb.FieldToAdd[1]; + //campo + fields[0].Name = ComunDef.CamposCom.camp_oid; + fields[0].Alias = ComunDef.CamposCom.camp_oid; + fields[0].Tipo = "LONG"; + fields[0].Length = 0; + + if (!HelperGdb.AddFieldsSync(pathCapa, fields)) + return false; + //vuelve a cerrar la capa + string capa_principal = System.IO.Path.GetFileNameWithoutExtension(pathCapa); + HelperGdb.CloseLayer(capa_principal); + + ///////////////////////////////////////////////////// + //Coge los ids de la capa de la que ha exportado + FeatureClass fc_orig = HelperGdb.GetFtClassSync(pathCapaOrig); + if (fc_orig == null) + return false; + List ids = new List(); + //Añade a la lista los ids que cumplen el filtro espacial + try + { + ids = fc_orig.Select(filter, SelectionType.ObjectID, SelectionOption.Normal).GetObjectIDs().ToList(); + } + catch + { + ids = new List(); + } + //Comprueba que hay tantos ids como elementos en el shp + FeatureClass fc_shp = HelperGdb.GetFtClassSync(pathCapa); + if (fc_shp == null) + return false; + int nelem_shp = HelperGdb.GetNumElemsSync(fc_shp); + if (nelem_shp != ids.Count) + return false; + + ///////////////////////////////////////////////////// + //ahora rellena las columnas + try + { + using (RowCursor rc_shp = fc_shp.Search()) + { + if (rc_shp == null) + return false; + + var modifyOp = new ArcGIS.Desktop.Editing.EditOperation(); + modifyOp.Name = "Actualiza OID"; + bool ex = false; + //modifyOp.Callback((context) => + //{ + int i = 0; + while (rc_shp.MoveNext() && i < ids.Count) + { + using (Row rowshp = rc_shp.Current) + { + //context.Invalidate(rowshp); + // modify and execute + modifyOp.Modify(rowshp, ComunDef.CamposCom.camp_oid, ids[i++]); + rowshp.Store(); + //context.Invalidate(rowshp); + } + } + //}, fc_shp); + ex = modifyOp.Execute(); + ArcGIS.Desktop.Core.Project.Current.SaveEditsAsync(); + if (ex && modifyOp.IsDone) + return true; + else + return false; + } + } + catch + { + return false; + } + return true; + } + + /** + * Prepara la geometría para exportar los ámbitos + */ public Geometry GetGeomAmbitsExport() { Geometry geomAux = null; @@ -539,7 +642,7 @@ namespace OliviaAddInPro.Services //if (geomAux == null) { //Ahora hace la geometría de los ámbitos que cumplen la consulta - geomAmbits = HelperGdb.GetGeomConvexHullSync(fc, filtro); + geomAmbits = HelperGdb.GetGeomUnique(fc, filtro); if (geomAmbits == null || geomAmbits.IsEmpty) { ErrStr = "No se ha podido generar geometría de los ámbitos" + com.ConsultaAmbs + HelperGdb.OutStr; @@ -550,7 +653,7 @@ namespace OliviaAddInPro.Services else { geomAux = HelperGdb.IntersectGeom(geomAux, geomAmbits); - geomAux = GeometryEngine.Instance.ConvexHull(geomAux); + //geomAux = GeometryEngine.Instance.ConvexHull(geomAux); } } //le quita las restricciones @@ -773,7 +876,7 @@ namespace OliviaAddInPro.Services //crea el dataset o comprueba si existe string datasetNameOut = string.Empty; var resp = HelperGdb.CreateDataset(GdbFileName, tratamiento, spatRefData, out datasetNameOut); - string err_spatref = "Atención, no coincide la proyección de las FeatureClass del Dataset ya creado con la del FeatureClass a importar"; + if(resp.Value==0) { //avisa @@ -786,10 +889,13 @@ namespace OliviaAddInPro.Services res.Error.Add("Error al crear el Dataset para importar " + tratamiento); return res; } - else if (resp.Value == 2) + else //2 o 4 if (resp.Value == 2) { //avisa - msg_avisa = err_spatref + ", se ha creado un nuevo dataset " + datasetNameOut; + string err_spatref = string.Empty; + if (resp.Value==2) + err_spatref = "Atención, no coincide la proyección de las FeatureClass del Dataset ya creado con la del FeatureClass a importar. "; + msg_avisa = err_spatref + "Se ha creado un nuevo dataset " + datasetNameOut; //HelperGlobal.ponMsg(err_spatref +", se ha creado un nuevo dataset "+ datasetNameOut ); tratamiento = datasetNameOut; } @@ -875,7 +981,7 @@ namespace OliviaAddInPro.Services //mira a ver si hay que borrar para reemplazar if (sobreescribe) { - resp = HelperGdb.DeleteFeatureClassSync(GdbFileName, noms_gdb[i]); + resp = HelperGdb.DeleteFeatureClassSync(GdbFileName + "\\" + dataset, noms_gdb[i]); if (resp.Value!=-2 && resp.Value!=1) //-2 porque puede ser que no pueda abrir la capa porque no existe { err_st = "Error al sobreescribir la capa " + noms_gdb[i]; diff --git a/Services/ProcesoEjecServ.cs b/Services/ProcesoEjecServ.cs index 7796bc0..0eafe72 100644 --- a/Services/ProcesoEjecServ.cs +++ b/Services/ProcesoEjecServ.cs @@ -124,6 +124,7 @@ namespace OliviaAddInPro.Services } } + int result = Environment.TickCount & Int32.MaxValue; //para que el tickcount no sea negativo if (cps.Getcancelled()) //mira a ver si ha cancelado el usuario { //se ha cancelado, lo envía al OliviaTask @@ -137,11 +138,11 @@ namespace OliviaAddInPro.Services if(!fin) //si no ha finalizado normal, el usuario lo ha cancelado res.Error.Add("Proceso Cancelado por el usuario"); } - else if (!first_send_cfg && ((Math.Abs(Environment.TickCount) - lastprog) >= m_tm_progr) && !fin) //en caso normal, todo va bien, pide el progreso y la tarea + else if (!first_send_cfg && ((result - lastprog) >= m_tm_progr) && !fin) //en caso normal, todo va bien, pide el progreso y la tarea { //solo pide la programación cada m_tm_progr milis var pp = pide_progr(); - if (pp .Value> TiposActu.ActuFinOk) + if (pp.Value> TiposActu.ActuFinOk) fin = true; if(pp.HasError) { @@ -153,8 +154,10 @@ namespace OliviaAddInPro.Services else nint++; } + if (pp.Value == TiposActu.ActuFinNOk) + res.Error.Add("Finalizado proceso con fallos"); actualiza(pp); - lastprog = Environment.TickCount; + lastprog = result; } } while (!sal); diff --git a/ViewModel/Recogida/PaneRecogidaSub1ViewModel.cs b/ViewModel/Recogida/PaneRecogidaSub1ViewModel.cs index 93bf1ca..df985ba 100644 --- a/ViewModel/Recogida/PaneRecogidaSub1ViewModel.cs +++ b/ViewModel/Recogida/PaneRecogidaSub1ViewModel.cs @@ -274,6 +274,7 @@ namespace OliviaAddInPro TiposVehic.Clear(); TiposCapac.Clear(); OliviaGlob.AddFlagTipEjec(TiposEjecucion.Config); //lo reinicia, por si estaba después de planificar + OliviaGlob.RemoveFlagTipEjec(TiposEjecucion.Config2); if (string.IsNullOrEmpty(capa)) return false;