diff --git a/Button/ButtonLimp.cs b/Button/ButtonLimp.cs index 51565d6..c27e700 100644 --- a/Button/ButtonLimp.cs +++ b/Button/ButtonLimp.cs @@ -25,14 +25,26 @@ namespace OliviaAddInPro { protected override void OnClick() { + ///////////////////////////////////////////////////// + OliviaGlob.progrDialog= new ProgressDialog( "Procesando", "Canceled", 100, false); if (OliviaGlob.TipoEjec == TiposEjecucion.Ninguno) { - OliviaGlob.SetFlagTipEjec(TiposEjecucion.Limp); - OliviaGlob.Limp = new Limpieza(); - DockpaneLimpiezaViewModel.Reset(); - DockpaneLimpiezaViewModel.Show(); + ///Comprueba que existe la red navegable configurada + if (HelperGdb.GetGdb(OliviaGlob.Paths.PathGdbNw).Result == null) + { + HelperGlobal.ponMsg("No encuentra Gdb de red navegable, cambie Configuración: " + HelperGdb.OutStr, + System.Windows.MessageBoxImage.Warning); + } + else + { + OliviaGlob.SetFlagTipEjec(TiposEjecucion.Limp); + if(OliviaGlob.Limp==null) + OliviaGlob.Limp = new Limpieza(); + DockpaneLimpiezaViewModel.Reset(); + DockpaneLimpiezaViewModel.Show(); + } } else { diff --git a/Button/ButtonRec.cs b/Button/ButtonRec.cs index 5131d2a..def4442 100644 --- a/Button/ButtonRec.cs +++ b/Button/ButtonRec.cs @@ -29,10 +29,20 @@ namespace OliviaAddInPro "Procesando", "Canceled", 100, false); if (OliviaGlob.TipoEjec==TiposEjecucion.Ninguno) { - OliviaGlob.SetFlagTipEjec(TiposEjecucion.Reco); - OliviaGlob.Reco = new Recogida(); - DockpaneRecogidaViewModel.Reset(); - DockpaneRecogidaViewModel.Show(); + ///Comprueba que existe la red navegable configurada + if (HelperGdb.GetGdb(OliviaGlob.Paths.PathGdbNw).Result == null) + { + HelperGlobal.ponMsg("No encuentra Gdb de red navegable, cambie Configuración: " + HelperGdb.OutStr, + System.Windows.MessageBoxImage.Warning); + } + else + { + OliviaGlob.SetFlagTipEjec(TiposEjecucion.Reco); + if(OliviaGlob.Reco==null) + OliviaGlob.Reco = new Recogida(); + DockpaneRecogidaViewModel.Reset(); + DockpaneRecogidaViewModel.Show(); + } } else { diff --git a/Helper/HelperGdb.cs b/Helper/HelperGdb.cs index 4c5523e..166c273 100644 --- a/Helper/HelperGdb.cs +++ b/Helper/HelperGdb.cs @@ -26,6 +26,7 @@ namespace OliviaAddInPro.Helper { public static class HelperGdb { + private static string ObjectId = "OBJECTID"; private static string out_str = string.Empty; public static string OutStr { get @@ -312,7 +313,7 @@ namespace OliviaAddInPro.Helper } //Crea un filtro espacial a partir de una consulta y en todo caso, una geometría - public static ArcGIS.Core.Data.SpatialQueryFilter CreateFiler(string consulta, ArcGIS.Core.Geometry.Geometry geom, SpatialRelationship rel= SpatialRelationship.Intersects) + public static ArcGIS.Core.Data.SpatialQueryFilter CreateFiler(string consulta, ArcGIS.Core.Geometry.Geometry geom, SpatialRelationship rel= SpatialRelationship.Contains) { ArcGIS.Core.Data.SpatialQueryFilter filt =null; if (geom != null) @@ -548,35 +549,21 @@ namespace OliviaAddInPro.Helper * Forma la envolvente convexa, el mínimo polígono, * que contiene los ámbitos para exportar, a partir de ahí la red navegable ampliando a un buffer */ - public static Task GetGeomConvexHull(FeatureClass fclss, ArcGIS.Core.Data.QueryFilter filter, CancelableProgressorSource cps=null) + public static Task GetGeomConvexHull(FeatureClass fclss, ArcGIS.Core.Data.QueryFilter filter) { ArcGIS.Core.Geometry.Geometry geomIni = null; return ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run((Func)(() => { - geomIni = GetGeomUnique(fclss, filter, cps); - if (geomIni != null) - { - ArcGIS.Core.Geometry.Geometry geomSal = null; - try - { - geomSal = GeometryEngine.Instance.ConvexHull(geomIni); - return geomSal; - } - catch - { - return null; - } - } - else - return null; + geomIni = GetGeomUnique(fclss, filter); + return geomIni; })); } /* * A partir de una capa recorre todos los elementos que cumplen el filtro y los une en una única geometría */ - public static ArcGIS.Core.Geometry.Geometry GetGeomUnique(FeatureClass fclss, ArcGIS.Core.Data.QueryFilter filtro, CancelableProgressorSource cps) + public static ArcGIS.Core.Geometry.Geometry GetGeomUnique(FeatureClass fclss, ArcGIS.Core.Data.QueryFilter filtro) { ArcGIS.Core.Geometry.Geometry geomsal = null; ReiniciaOutStr(); @@ -584,7 +571,6 @@ namespace OliviaAddInPro.Helper try { var geom = new List(); - //geomSal = GeometryEngine.Instance.Union(f); using (RowCursor rowCursor = fclss.Search(filtro)) { @@ -593,9 +579,7 @@ namespace OliviaAddInPro.Helper using (Row row = rowCursor.Current) { if (row is Feature ft) - geom.Add(ft.GetShape()); - //geomsal = UneGeom(geomsal, ft.GetShape()); - + geom.Add(ft.GetShape()); } } geomsal= GeometryEngine.Instance.Union(geom); @@ -636,7 +620,7 @@ namespace OliviaAddInPro.Helper { where = $"{fieldName} = {Quote(f)}{selFieldVals[i]}{Quote(f)}"; filtro = new ArcGIS.Core.Data.QueryFilter { WhereClause = where }; - geomAux = GetGeomUnique(fclss, filtro, null); + geomAux = GetGeomUnique(fclss, filtro); if(geomAux == null) { ok = false; @@ -795,13 +779,109 @@ namespace OliviaAddInPro.Helper return res; } - public static bool ExportShp(string pathLayerIn, SpatialQueryFilter filter, string nameShp, string outpath, CancelableProgressorSource cps, out string msgOut, ProgressorSource progrDialog = null) + public static bool ExportShp2(string pathLayerIn, SpatialQueryFilter filter, string nameShp, string outpath, CancelableProgressorSource cps) + { + if (!System.IO.Directory.Exists(outpath)) + System.IO.Directory.CreateDirectory(outpath); + FeatureClass fc = null; + ///////////////////////////////////////////////////////// + //Prepara una where_clause con las entidades que cumplen el filtro + //Abre la featureclass + try + { + fc = GetFtClass(pathLayerIn); + if (fc == null) + { + OutStr = "Error al abrir Feature Class en exportación"; + return false; + } + List ids = new List(); + cps.Status = "Aplicando filtro espacial a exportación"; + //Añade a la lista los ids que cumplen el filtro espacial + using (RowCursor cursor = fc.Search(filter)) + { + while (cursor.MoveNext()) + { + using (Feature feature = (Feature)cursor.Current) + { + ids.Add(feature.GetObjectID()); + } + } + } + if (ids.Count <= 0) + { + OutStr = "Error al aplicar filtro espacial en exportación"; + return false; + } + //convierte la lista de ids a string para la clause de la forma + //(id1, id2, id3..) + string whereClause = GetWhereClauseFromIds(ids); + + /////////////////////////////////////////////////////////// + ///Exporta + cps.Status = "Exportando datos"; + string[] args = { pathLayerIn, outpath, nameShp, whereClause }; + // execute the tool + IGPResult gpResult = Geoprocessing.ExecuteToolAsync("FeatureClassToFeatureClass_conversion", args, + null, cps.CancellationTokenSource.Token, + + (event_name, o) => // implement delegate and handle events + { + switch (event_name) + { + case "OnValidate": // stop execute if any warnings + //if ((o as IGPMessage[]).Any(it => it.Type == GPMessageType.Warning)) + //_cts.Cancel(); + break; + + case "OnProgressMessage": + { + string msg = string.Format("{0}: {1}", new object[] { event_name, (string)o }); + Debug.WriteLine(msg); + ; + //System.Windows.MessageBox.Show(msg); + //_cts.Cancel(); + } + break; + + case "OnProgressPos": + { + string msg2 = string.Format("{0}: {1} %", new object[] { event_name, (int)o }); + Debug.WriteLine(msg2); + var av = (int)0; + if (av > 0) + { + cps.Value = (uint)(80 * av * 0.2); + } + // if ((int)o < 0) + //System.Windows.MessageBox.Show(msg2); + //_cts.Cancel(); + break; + } + } + }).Result; + cps.Status = "Finalizando exportacion"; + + return true; + } + catch (Exception ex) + { + OutStr = "Error: " + ex.Message; + return false; + } + finally + { + Free(fc); + } + + } + + public static bool ExportShp(string pathLayerIn, SpatialQueryFilter filter, string nameShp, string outpath, CancelableProgressorSource cps, out string msgOut, ProgressorSource progrDialog = null) { msgOut = ""; if (!System.IO.Directory.Exists(outpath)) System.IO.Directory.CreateDirectory(outpath); - //FeatureClass fc = HelperGdb.GetFtClass(pathLayerIn); //fc. /* @@ -950,23 +1030,64 @@ namespace OliviaAddInPro.Helper return resp; } } + /** + * Amplía la geometría para añadirele buffer + */ + public static Respuesta BufferGeom(ArcGIS.Core.Geometry.Geometry geom, double buffer) + { + Respuesta resp = new Respuesta(); + ArcGIS.Core.Geometry.Geometry geomBuff = null; + try + { + geomBuff = GeometryEngine.Instance.Buffer(geom, buffer); + } + catch + { + + } + resp.Value = geomBuff; + return resp; + } /**Amplía la geometría para que incluya el punto - */ + */ public static Respuesta AddPtoInGeom(Coordinate2D pto, ArcGIS.Core.Geometry.Geometry geom) { Respuesta resp = new Respuesta(); - double buffer = 100;//m de distancia desde la instalación + double buffer = 0;//m de distancia desde la instalación + bool repite = true; + ArcGIS.Core.Geometry.Geometry geom_pto, geom_sal; try { - ArcGIS.Core.Geometry.Geometry geom_pto = GeometryEngine.Instance.Buffer(pto.ToMapPoint(), buffer); - if(geom_pto==null || geom_pto.IsEmpty) + do { - resp.Value = null; - resp.Error.Add("Error al bufferear punto para incluirlo en polígono"); - return resp; + buffer += 100; + geom_pto = GeometryEngine.Instance.Buffer(pto.ToMapPoint(), buffer); + if(geom_pto==null || geom_pto.IsEmpty) + { + resp.Value = null; + resp.Error.Add("Error al bufferear punto para incluirlo en polígono"); + return resp; + } + //hace la convex hull, por si no fueran conexas las zonas + repite= GeometryEngine.Instance.Disjoint(geom_pto, geom); + /*if (geom_aux == null || geom_aux.IsEmpty) + { + ArcGIS.Core.Geometry.Envelope env1 = geom_sal.Extent; + ArcGIS.Core.Geometry.Envelope env2 = geom_pto.Extent; + ArcGIS.Core.Geometry.Envelope env3 = env1.Union(env2); + geom_sal = (ArcGIS.Core.Geometry.Geometry) env3; + //geom_sal = GeometryEngine.Instance.Envelope(geom_sal); + if (geom_sal == null || geom_sal.IsEmpty) + { + resp.Value = null; + resp.Error.Add("Error al hacer envolvente en unir punto al polígono"); + return resp; + } + }*/ } - ArcGIS.Core.Geometry.Geometry geom_sal = GeometryEngine.Instance.Union(geom_pto, geom); + while (repite); + geom_sal = GeometryEngine.Instance.Union(geom_pto, geom); if (geom_sal == null || geom_sal.IsEmpty) { resp.Value = null; @@ -985,10 +1106,30 @@ namespace OliviaAddInPro.Helper } /* * Dada una lista de ids de elemento, crea una consulta en la que se llama a todos esos elementos + * campo IN (id1, id2, id3..) */ public static string GetWhereClauseFromIds(List ids) { - string consulta, orstr; + if (ids.Count <= 0) + return string.Empty; + + string ids_str = "("; + bool first = true; + foreach (long i in ids) + { + if (first) + { + ids_str += i.ToString(); + first = false; + } + else + ids_str += "," + i.ToString(); + } + //el último + ids_str += ")"; + string whereClause = ObjectId + " IN " + ids_str; //Cambiar id a otro sitio + return whereClause; + /*string consulta, orstr; consulta = string.Empty; orstr = string.Empty; @@ -1003,15 +1144,68 @@ namespace OliviaAddInPro.Helper if (consulta == "()") consulta = string.Empty; - return consulta; + return consulta;*/ } /** * Elimina las filas indicadas del shp **/ - public static bool RemoveRowsFromShp(string shp_path, List quita) + public static bool RemoveRowsFromShp(FeatureClass fc, List quita) { - FeatureClass fc = HelperGdb.GetFtClassFromShp(shp_path).Result; + //Crea la consulta + var consulta = GetWhereClauseFromIds(quita); + + if (String.IsNullOrEmpty(consulta)) + return false; + + string message = String.Empty; + bool deletionResult = false; + + ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { + + EditOperation editOperation = new EditOperation(); + editOperation.Callback(context => + { + ArcGIS.Core.Data.QueryFilter openCutFilter = new ArcGIS.Core.Data.QueryFilter { WhereClause = consulta }; + + using (RowCursor rowCursor = fc.Search(openCutFilter, false)) + { + while (rowCursor.MoveNext()) + { + using (Row row = rowCursor.Current) + { + // In order to update the Map and/or the attribute table. Has to be called before the delete. + context.Invalidate(row); + + row.Delete(); + } + } + } + }, fc); + + try + { + deletionResult = editOperation.Execute(); + if (!deletionResult) + { + message = editOperation.ErrorMessage; + } + } + catch (GeodatabaseException exObj) + { + message = exObj.Message; + } + + }); + + if (!string.IsNullOrEmpty(message)) + { + OutStr = message; + return false; + } + else + return true; + /*FeatureClass fc = HelperGdb.GetFtClassFromShp(shp_path).Result; if (fc == null) return false; @@ -1025,7 +1219,8 @@ namespace OliviaAddInPro.Helper ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { string shpname = System.IO.Path.GetFileNameWithoutExtension(shp_path); - var shapeFileConnPath = new FileSystemConnectionPath(new Uri(shp_path), FileSystemDatastoreType.Shapefile); + var shapeFileConnPath = new FileSystemConnectionPath(new Uri(System.IO.Path.GetDirectoryName(shp_path)), + FileSystemDatastoreType.Shapefile); var shapefile = new FileSystemDatastore(shapeFileConnPath); using (Table table = shapefile.OpenDataset(shp_path)) { @@ -1071,6 +1266,7 @@ namespace OliviaAddInPro.Helper } else return true; + */ } /** @@ -1114,16 +1310,22 @@ namespace OliviaAddInPro.Helper Free(f); } Free(f); - Free(fc); - Free(cursor); - + Free(cursor); + + //comprueba que no se haya quedado sin ámbitos + if (quita.Count>=fc.GetCount()) + { + OutStr = "No quedan ámbitos que cumplan la geometría seleccionada."; + return false; + } + //Quita los ámbitos del shp if (quita.Count > 0) { //borra las líneas que se han indicado - if (!RemoveRowsFromShp(shp_path, quita)) + if (!RemoveRowsFromShp(fc, quita)) return false; } - + Free(fc); return true; } diff --git a/Model/ComunDef.cs b/Model/ComunDef.cs index e4d7475..8106d64 100644 --- a/Model/ComunDef.cs +++ b/Model/ComunDef.cs @@ -9,6 +9,7 @@ namespace OliviaAddInPro.Model { //************************************************************************************* //Enums y structs generales + public static int BuffExport = 1000; /** * Nombre de los campos de la cartografía de la red navegable que se consultan para la exportación */ diff --git a/Model/Limpieza.cs b/Model/Limpieza.cs index f8c5c07..f7333f1 100644 --- a/Model/Limpieza.cs +++ b/Model/Limpieza.cs @@ -58,12 +58,8 @@ namespace OliviaAddInPro.Model public TareaRes Ejecuta(ModosEjec modo, CancelableProgressorSource cps) { TareaRes res = null; - if (modo == ModosEjec.Sectoriza) - res = Serv.Sectoriza(cps); - else if (modo == ModosEjec.Planifica) - res = Serv.Planifica(cps); - //if(!res.Errores) - if (res.Errores) + res = Serv.Ejecuta(modo, cps); + if (res.Errores) { var res1=LanzaSrv.ejec(this, modo, TipoTtoStr); if (!res1.HasError) diff --git a/Model/OliviaConf.cs b/Model/OliviaConf.cs index a66008a..d979592 100644 --- a/Model/OliviaConf.cs +++ b/Model/OliviaConf.cs @@ -6,6 +6,8 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; +using Xceed.Wpf.Toolkit.PropertyGrid; +using Xceed.Wpf.Toolkit.PropertyGrid.Editors; namespace OliviaAddInPro.Model { @@ -190,6 +192,7 @@ namespace OliviaAddInPro.Model [Category("General")] [DisplayName("Red de carreteras")] [Description("Red de carreteras que se usara para la navegación")] + //[Editor(typeof(EditorFilePickerDefinition), typeof(EditorFilePickerDefinition))] public string red_carreteras { get; set; } [Category("General")] @@ -1301,5 +1304,5 @@ namespace OliviaAddInPro.Model #endregion - } + } } diff --git a/Model/OliviaGlob.cs b/Model/OliviaGlob.cs index f7a0f74..09c629e 100644 --- a/Model/OliviaGlob.cs +++ b/Model/OliviaGlob.cs @@ -209,8 +209,6 @@ namespace OliviaAddInPro.Model Conexion.Ip = c.Ip; Conexion.TiempoOutSocket = c.TiempoOutSocket; - //buff_export = c.buffer_export; - /////////////////////////////////////// //Capas, consultas y filtros GENERALES Capas.ftclass_ejes = c.eje_via; @@ -398,7 +396,7 @@ namespace OliviaAddInPro.Model RecogidaDef.tipos_lateralidad[(int)RecogidaDef.Lateralidad.Dcha] = c.derecha; RecogidaDef.tipos_lateralidad[(int)RecogidaDef.Lateralidad.Izqda] = c.izquierda; - + ComunDef.BuffExport = c.buffer_export; //Campos de la red navegable que se leen ComunDef.CamposNW.cons_onew = c.cons_onew; ComunDef.CamposNW.cons_kph = c.cons_kph; diff --git a/Model/Recogida.cs b/Model/Recogida.cs index f58386d..6c2cee2 100644 --- a/Model/Recogida.cs +++ b/Model/Recogida.cs @@ -82,12 +82,9 @@ namespace OliviaAddInPro.Model public TareaRes Ejecuta(ModosEjec modo, CancelableProgressorSource cps) { TareaRes res = null; - if (modo == ModosEjec.Sectoriza) - res = Serv.Sectoriza(cps); - else if (modo == ModosEjec.Planifica) - res = Serv.Planifica(cps); + res = Serv.Ejecuta(modo, cps); return res; - + } public async void EjecutaAsync(ModosEjec modo, CancelableProgressorSource cps, Action ffin) { diff --git a/Model/Respuesta.cs b/Model/Respuesta.cs index a1c2f91..246a759 100644 --- a/Model/Respuesta.cs +++ b/Model/Respuesta.cs @@ -10,13 +10,13 @@ namespace OliviaAddInPro.Model { public T Value { get; set; } - public List Error { get; set; } + public List Error { get; set; } = new List(); public bool HasError { get { - return Error.Any(); + return Error.Any(); } } public Respuesta() diff --git a/Services/EjecServ.cs b/Services/EjecServ.cs index 61e775f..a8628aa 100644 --- a/Services/EjecServ.cs +++ b/Services/EjecServ.cs @@ -40,9 +40,15 @@ namespace OliviaAddInPro.Services public bool LanzaEjec(ModosEjec modo, CancelableProgressorSource cps, out string ErrStr) { ErrStr = string.Empty; - FeatureClass fc = null; try - { + { + //Comprueba que tiene las columnas necesarias para planificar + if ((modo == ModosEjec.Planifica) && !CompruebaPlanif()) + { + ErrStr = "En la capa de ámbitos seleccionada no se encuentran columnas de SECTOR y/o SECUENCIA, necesarias para planificar"; + return false; + } + //Cuenta las filas que cumplen la consulta int nelems = HelperGdb.GetNumElems(com.CapaElems, com.ConsultaAmbs); if (nelems <= 0) @@ -55,7 +61,7 @@ namespace OliviaAddInPro.Services //Obtiene la geometría que envuelve a los ámbitos Geometry geom_export = null; - geom_export = GetGeomAmbitsExport(cps); + geom_export = GetGeomAmbitsExport(); if (geom_export == null || geom_export.IsEmpty) { ErrStr = "No se ha podido generar geometría de los ámbitos" + com.ConsultaAmbs + ErrStr; @@ -69,7 +75,6 @@ namespace OliviaAddInPro.Services { ErrStr = "Error al crear el filtro de exportacion de los ámbitos"; return false; - } //Termina de preparar nombre //Prepara nombre @@ -80,9 +85,10 @@ namespace OliviaAddInPro.Services com.NombreShpExport = prefNameExport + com.NombreShpExp_PrefTto +"_" + fechaHora + extShp; //exporta los datos de entrada - if (!HelperGdb.ExportShp(com.CapaElems, filtroEspacial, com.NombreShpExport, OliviaGlob.Paths.DirData, cps, out ErrStr)) + if (!HelperGdb.ExportShp2(com.CapaElems, filtroEspacial, com.NombreShpExport, OliviaGlob.Paths.DirData, cps)) + //if (!HelperGdb.ExportShp(com.CapaElems, filtroEspacial, com.NombreShpExport, OliviaGlob.Paths.DirData, cps, out ErrStr)) { - ErrStr = ErrStr+"Error al exportar los ámbitos"; + ErrStr = "Error al exportar los ámbitos: "+ HelperGdb.OutStr; return false; } //Guarda el nombre @@ -94,7 +100,8 @@ namespace OliviaAddInPro.Services } cps.Value = 80; //hace intersecciones espaciales en caso de ámbitos lineales para quitar los que tienen más parte fuera de la zona que dentro - if (((com.GeomNiv != null) || (com.GeomZon!=null)) && + //REVISAR + /*if (((com.GeomNiv != null) || (com.GeomZon != null)) && (OliviaGlob.IsReco() || (OliviaGlob.IsLimp() && (com.TipoTto < (int)LimpiezaDef.TiposTto.TtoPapeVaci)))) { if (!HelperGdb.RemoveRowsGeom(OliviaGlob.Paths.PathData, geom_export, 0.4)) @@ -102,44 +109,55 @@ namespace OliviaAddInPro.Services ErrStr = "Error al quitar los ámbitos que sobresalen: " + HelperGdb.OutStr; return false; } - } - //comprueba que no se haya quedado sin ámbitos - fc = HelperGdb.GetFtClassFromShp(OliviaGlob.Paths.PathData).Result; - if (fc==null) - { - ErrStr = HelperGdb.OutStr; - return false; - } - if(fc.GetCount() <= 0) - { - ErrStr = "No quedan ámbitos que cumplan la geometría seleccionada."; - return false; - } + }*/ /////////////////////////////////////////////////////////////////////////// - //amplia la geom para englobar las instalaciones - geom_export = HelperGdb.GetGeomConvexHull(fc, null, cps).Result; - if (!com.CoordsInstal.IsEmpty && (com.CoordsInstal.X!=0)) - { - //hay instalación - Respuesta resp; - //comprueba, si hay restricciones de circulación, que la instalación no está en ellas - if (com.GeomRestr != null) + //comprueba, si hay restricciones de circulación y hay instalación, que la instalación no está en ellas + if (!com.CoordsInstal.IsEmpty && (com.CoordsInstal.X!=0) && (com.GeomRestr != null)) + { + Respuesta resp = HelperGdb.IsPtoInGeom(com.CoordsInstal, com.GeomRestr); + if (!resp.Value && resp.HasError) { - resp = HelperGdb.IsPtoInGeom(com.CoordsInstal, com.GeomRestr); - if (!resp.Value) - { - if (resp.HasError) - ErrStr = "Error al comprobar si la instalación está contenida en el polígono de restricciones: " + resp.Error.ElementAt(0); - else - ErrStr = "Error, la instalación está en la zona restringida a la circulación "; - return false; - } + ErrStr = "Error al comprobar si la instalación está contenida en el polígono de restricciones: " + resp.Error.ElementAt(0); + return false; } - - //comprueba si la geometría de exportación contiene a la instalación - resp = HelperGdb.IsPtoInGeom(com.CoordsInstal, geom_export); - if (!resp.Value) + else if(resp.Value) //sí está contenido en las restricciones + { + ErrStr = "Error, la instalación está en la zona restringida a la circulación "; + return false; + } + + } + if (cps.CancellationTokenSource.IsCancellationRequested) + { + ErrStr = "Se ha cancelado la operación"; + return false; + } + /////////////////////////////////////////////////////////////////////////// + //exporta la red navegable (buffer, le quita las restr...) + //se obtiene la geometría a intersecar con la red, que será la que contiene + //a todos los ámbitos y la instalación, ampliada un buffer, mayor si hay + //restricciones de circulación + Geometry geom_aux = HelperGdb.BufferGeom(geom_export, com.BuffExport).Value; + if(geom_aux==null) + { + ErrStr = "Error al añadir buffer a la geometría"; + return false; + } + //quita las restricciones + geom_aux = HelperGdb.QuitaGeom(geom_aux, com.GeomRestr); + if (geom_aux == null) + { + ErrStr = "Error al intersecar con las restricciones."; + return false; + } + geom_export = geom_aux; + ////////////////////////////////////////////////////////////// + //comprueba si la geometría de exportación contiene a la instalación + if (!com.CoordsInstal.IsEmpty && (com.CoordsInstal.X != 0)) + { + Respuesta resp = HelperGdb.IsPtoInGeom(com.CoordsInstal, geom_export); + if (!resp.Value) //si no lo contiene { //ha ido mal if (resp.HasError) @@ -165,13 +183,7 @@ namespace OliviaAddInPro.Services } } } - if (cps.CancellationTokenSource.IsCancellationRequested) - { - ErrStr = "Se ha cancelado la operación"; - return false; - } - /////////////////////////////////////////////////////////////////////////// - //exporta la red navegable (buffer, le quita las restr...) + //Hace el filtro con la geometría final filtroEspacial = HelperGdb.CreateFiler(String.Empty, geom_export); if (filtroEspacial == null) { @@ -183,9 +195,10 @@ namespace OliviaAddInPro.Services com.NombreShpExportNw = prefNameExportNw + fechaHora + extShp; //exporta los datos de entrada string capaNw =System.IO.Path.Combine(OliviaGlob.Paths.PathGdbNw, OliviaGlob.Capas.ftclass_ejes); - if (!HelperGdb.ExportShp(capaNw, filtroEspacial, com.NombreShpExportNw, OliviaGlob.Paths.DirData, cps, out ErrStr)) + //if (!HelperGdb.ExportShp(capaNw, filtroEspacial, com.NombreShpExportNw, OliviaGlob.Paths.DirData, cps, out ErrStr)) + if (!HelperGdb.ExportShp2(capaNw, filtroEspacial, com.NombreShpExportNw, OliviaGlob.Paths.DirData, cps)) { - ErrStr = ErrStr + "Error al exportar la red navegable"; + ErrStr = "Error al exportar la red navegable: " + HelperGdb.OutStr; return false; } //guarda los nombres del shape @@ -202,17 +215,13 @@ namespace OliviaAddInPro.Services ErrStr = "Errores al comenzar la ejecución: " + ex.Message; return false; } - finally - { - HelperGdb.Free(fc); - } return true; } /** * Prepara la geometría para exportar los ámbitos */ - public Geometry GetGeomAmbitsExport(CancelableProgressorSource cps) + public Geometry GetGeomAmbitsExport() { Geometry geomAux = null; Geometry geomAmbits = null; @@ -247,20 +256,20 @@ namespace OliviaAddInPro.Services ErrStr = "Al emplear ejes de calle como ámbitos es necesario indicar polígono de exportación"; return null; } - cps.Value = 30; - - //prepara el filtro con consulta y espacial - SpatialQueryFilter filtro = HelperGdb.CreateFiler(com.ConsultaAmbs, geomAux); - //Ahora hace la geometría de los ámbitos que cumplen la consulta - geomAmbits = HelperGdb.GetGeomConvexHull(fc, filtro, cps).Result; - if (geomAmbits == null || geomAmbits.IsEmpty) + //prepara el filtro con consulta y espacial + SpatialQueryFilter filtro = HelperGdb.CreateFiler(com.ConsultaAmbs, geomAux); + if (geomAux == null) { - ErrStr = "No se ha podido generar geometría de los ámbitos" + com.ConsultaAmbs + HelperGdb.OutStr; - return null; + //Ahora hace la geometría de los ámbitos que cumplen la consulta, si no hay ya geometría + geomAmbits = HelperGdb.GetGeomConvexHull(fc, filtro).Result; + if (geomAmbits == null || geomAmbits.IsEmpty) + { + ErrStr = "No se ha podido generar geometría de los ámbitos" + com.ConsultaAmbs + HelperGdb.OutStr; + return null; + } + geomAux = geomAmbits; } - geomAux = geomAmbits; - cps.Value = 60; //le quita las restricciones if (com.GeomRestr != null) { @@ -271,7 +280,6 @@ namespace OliviaAddInPro.Services return null; } } - cps.Value = 75; HelperGdb.Free(fc); return geomAux; } @@ -330,5 +338,60 @@ namespace OliviaAddInPro.Services camps[1] = LimpiezaDef.Campos.consulta_secuen; return CompruebaCampos(pathCapa, camps) == 0; } + + /** + * Comprueba lo necesario para ver si hay campos para la planificación + */ + public bool CompruebaPlanif() + { + //si ha importado no hace falta que compruebe, seguro que las tiene + if (OliviaGlob.IsConfig2()) + return true; + //no ha importado, comprueba capa + if (ComprCamposPlanif(com.CapaElems)) + return true; + + return false; + } + + /** + * Borra los archivos exportados para el proceso + */ + public static void BorraFiles() + { + string[] list = null; + string capa_principal = System.IO.Path.GetFileNameWithoutExtension(OliviaGlob.Paths.PathData); + string capa_principal_nw = System.IO.Path.GetFileNameWithoutExtension(OliviaGlob.Paths.PathNW); + + try + { + if (capa_principal == null) + return; + list = System.IO.Directory.GetFiles(OliviaGlob.Paths.DirData, capa_principal + "*"); + if (list.Length > 0) + { + foreach (string f in list) + { + if (System.IO.Path.GetExtension(f) == ".lock") + continue; + System.IO.File.Delete(f); + } + } + if (capa_principal_nw == null) + return; + list = System.IO.Directory.GetFiles(OliviaGlob.Paths.DirData, capa_principal_nw + "*"); + if (list.Length > 0) + { + foreach (string f in list) + { + System.IO.File.Delete(f); + } + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message); + } + } } } diff --git a/Services/LimpiezaServ.cs b/Services/LimpiezaServ.cs index bf37014..25a4fc7 100644 --- a/Services/LimpiezaServ.cs +++ b/Services/LimpiezaServ.cs @@ -27,7 +27,7 @@ namespace OliviaAddInPro.Services * Modo 0, sectorizar * Modo 1, planificar */ - public TareaRes Sectoriza(CancelableProgressorSource cps) + public TareaRes Ejecuta(ModosEjec modo, CancelableProgressorSource cps) { var res = new TareaRes() { @@ -74,36 +74,7 @@ namespace OliviaAddInPro.Services return false; } return true; - } - - public TareaRes Planifica(CancelableProgressorSource cps) - { - TareaRes res = new TareaRes() - { - Errores = false, - msg = "", - data = null - }; - //se asegura que tiene todo para planif - //ErrStr = string.Empty; - if (!CompruebaPlanif()) - { - res.msg = "En la capa de ámbitos seleccionada no se encuentran columnas de SECTOR y/o SECUENCIA, necesarias para planificar"; - res.Errores = true; - return res; - } - //Prepara consulta - string nombFileAmbs = string.Empty; - //Prepara consulta - if (!PreparaConsulta(out nombFileAmbs)) - { - res.msg = "No se ha seleccionado una consulta válida" + limp.ConsultaAmbs; - res.Errores = true; - return res; - } - - return res; - } + } public string DameAmbsConsulta(out string ambs_file) { @@ -134,9 +105,9 @@ namespace OliviaAddInPro.Services /** * Comprueba lo necesario para ver si hay campos para la planificación */ - public bool CompruebaPlanif() + public bool CompruebaPlanif2() { - + //NO SE USA AQUÍ, ESTÁ EN EJECSERV //si ha importado no hace falta que compruebe, seguro que las tiene if (OliviaGlob.IsConfig2()) return true; diff --git a/Services/RecogidaServ.cs b/Services/RecogidaServ.cs index 11c0888..d790e79 100644 --- a/Services/RecogidaServ.cs +++ b/Services/RecogidaServ.cs @@ -60,7 +60,7 @@ namespace OliviaAddInPro.Services * Modo 0, sectorizar * Modo 1, planificar */ - public TareaRes Sectoriza(CancelableProgressorSource cps) + public TareaRes Ejecuta(ModosEjec modo, CancelableProgressorSource cps) { var res = new TareaRes() { @@ -85,7 +85,6 @@ namespace OliviaAddInPro.Services //Prepara nombre //Pone nombre al shape en función de los ámbitos, el tratamiento, y los polígonos + timestamp - //REVISAR PARA RECO reco.NombreShpExp_PrefTto = nombFileAmbs + DameStrPoligs(); string msg = ""; @@ -111,75 +110,43 @@ namespace OliviaAddInPro.Services } return true; } - - public TareaRes Planifica(CancelableProgressorSource cps) + + public string DameAmbsConsulta(out string cap_abrev) { - TareaRes res = new TareaRes() + string consulta, orstr, aux; + + consulta = null; + cap_abrev = ""; + aux = ""; + orstr = null; + + if (reco.TipoFrac != -1) { - Errores = false, - msg = "", - data = null - };/* - //se asegura que tiene todo para planif - //ErrStr = string.Empty; - if (!CompruebaPlanif()) - { - res.msg = "En la capa de ámbitos seleccionada no se encuentran columnas de SECTOR y/o SECUENCIA, necesarias para planificar"; - res.Errores = true; - return res; + consulta = consulta + orstr + "(" + RecogidaDef.filtro_str[reco.TipoFrac] + ")"; + cap_abrev = reco.TipoFrac.ToString("00"); + cap_abrev = "F" + cap_abrev + "_"; + if (consulta == "()") + consulta = ""; } - //Prepara consulta - string nombFileAmbs = string.Empty; - //Prepara consulta - if (!PreparaConsulta(out nombFileAmbs)) + if (orstr == null) + orstr = " AND "; + if (reco.TipoCarg != -1) { - res.msg = "No se ha seleccionado una consulta válida" + reco.ConsultaAmbs; - res.Errores = true; - return res; - }*/ - - return res; - } - public string DameAmbsConsulta(out string ambs_file) - { - string consulta, orstr; - - consulta = string.Empty; - ambs_file = ""; - /*orstr = null; - var n = reco.AmbitosSel.Length; - - for (int i = 0; i < n; i++) - { - if (limp.AmbitosSel[i]) - { - consulta = consulta + orstr + "(" + LimpiezaDef.filtro_str[i] + ")"; - ambs_file = ambs_file + i.ToString("00"); - if (orstr == null) - orstr = " OR "; - } + consulta = consulta + orstr + "(" + RecogidaDef.filtro_str[RecogidaDef.tipos_fracc_str.Length + reco.TipoCarg] + ")"; + aux = reco.TipoCarg.ToString("00"); + cap_abrev = cap_abrev + "C" + aux; + if (consulta == "()") + consulta = ""; + } + if (reco.TipoLate > 0) + { + consulta = consulta + orstr + "(" + RecogidaDef.campos_def.cons_lateral + " = '" + RecogidaDef.tipos_lateralidad[reco.TipoLate] + "'" + ")"; + if (consulta == "()") + consulta = ""; } - ambs_file = "_A" + ambs_file; - if (consulta == "()") - consulta = ""; - */ return consulta; } - /** - * Comprueba lo necesario para ver si hay campos para la planificación - */ - public bool CompruebaPlanif() - { - - //si ha importado no hace falta que compruebe, seguro que las tiene - if (OliviaGlob.IsConfig2()) - return true; - //no ha importado, comprueba capa - if (ComprCamposPlanif(reco.CapaElems)) - return true; - - return false; - } + /** * Rellena el array de filtros en base a la config */ diff --git a/View/Configuracion/PaneConfigView.xaml.cs b/View/Configuracion/PaneConfigView.xaml.cs index e391b6d..d4eaa88 100644 --- a/View/Configuracion/PaneConfigView.xaml.cs +++ b/View/Configuracion/PaneConfigView.xaml.cs @@ -13,6 +13,7 @@ using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; +using OliviaAddInPro.Model; namespace OliviaAddInPro { @@ -28,9 +29,12 @@ namespace OliviaAddInPro } private void OnGuardar(object sender, RoutedEventArgs e) { - - if (DataContext is PaneConfigViewModel mod) - mod.OnGuardar(); + + if (DataContext is PaneConfigViewModel mod) + { + mod.OnGuardar(); + OliviaGlob.IniDefault(); + } } private void OnRefres(object sender, RoutedEventArgs e) diff --git a/View/Limpieza/PaneLimpiezaSub2.xaml.cs b/View/Limpieza/PaneLimpiezaSub2.xaml.cs index 6021064..904929f 100644 --- a/View/Limpieza/PaneLimpiezaSub2.xaml.cs +++ b/View/Limpieza/PaneLimpiezaSub2.xaml.cs @@ -87,9 +87,16 @@ namespace OliviaAddInPro ArcGIS.Core.Geometry.Geometry geomsal = HelperGdb.OpenGeom(HelperGdb.TiposOpenFileDlg.OpenFtrClassPoint, out texto); - if ((DataContext is PaneLimpiezaSub2ViewModel mod) && geomsal != null && geomsal is MapPoint mp) + if ((DataContext is PaneLimpiezaSub2ViewModel mod) && (geomsal != null)) { - mod.CoordsInstal = mp.Coordinate2D; + if (geomsal is MapPoint map) + mod.CoordsInstal = map.Coordinate2D; + else if (geomsal is Multipoint multip) + { + if(multip.Copy2DCoordinatesToList().Count>0) + mod.CoordsInstal = multip.Copy2DCoordinatesToList().First(); + } + } if (geomsal != null) label_capainst.Content = texto; diff --git a/View/PaneEjecutar.xaml.cs b/View/PaneEjecutar.xaml.cs index cc1264c..5c4113c 100644 --- a/View/PaneEjecutar.xaml.cs +++ b/View/PaneEjecutar.xaml.cs @@ -28,17 +28,25 @@ namespace OliviaAddInPro private void button_secto_Click(object sender, RoutedEventArgs e) { - if (DataContext is PaneLimpiezaViewModel mod) + if (DataContext is PaneLimpiezaViewModel modlimp) { - mod.Ejecuta(OliviaAddInPro.Services.ModosEjec.Sectoriza); + modlimp.Ejecuta(OliviaAddInPro.Services.ModosEjec.Sectoriza); + } + else if(DataContext is PaneRecogidaViewModel modrec) + { + modrec.Ejecuta(OliviaAddInPro.Services.ModosEjec.Planifica); } } private void button_planif_Click(object sender, RoutedEventArgs e) { - if (DataContext is PaneLimpiezaViewModel mod) + if (DataContext is PaneLimpiezaViewModel modlimp) { - mod.Ejecuta(OliviaAddInPro.Services.ModosEjec.Planifica); + modlimp.Ejecuta(OliviaAddInPro.Services.ModosEjec.Planifica); + } + else if (DataContext is PaneRecogidaViewModel modrec) + { + modrec.Ejecuta(OliviaAddInPro.Services.ModosEjec.Planifica); } } diff --git a/View/Recogida/PaneRecogidaSub1.xaml.cs b/View/Recogida/PaneRecogidaSub1.xaml.cs index 6a5c216..195af6b 100644 --- a/View/Recogida/PaneRecogidaSub1.xaml.cs +++ b/View/Recogida/PaneRecogidaSub1.xaml.cs @@ -155,9 +155,15 @@ namespace OliviaAddInPro ArcGIS.Core.Geometry.Geometry geomsal = HelperGdb.OpenGeom(HelperGdb.TiposOpenFileDlg.OpenFtrClassPoint,out texto); - if ((DataContext is PaneRecogidaSub1ViewModel mod) && geomsal != null && geomsal is MapPoint mp) + if ((DataContext is PaneRecogidaSub1ViewModel mod) && geomsal != null) { - mod.CoordsPlanta = mp.Coordinate2D; + if (geomsal is MapPoint map) + mod.CoordsPlanta = map.Coordinate2D; + else if (geomsal is Multipoint multip) + { + if (multip.Copy2DCoordinatesToList().Count > 0) + mod.CoordsPlanta = multip.Copy2DCoordinatesToList().First(); + } } if (geomsal != null) label_capaplant.Content = texto; diff --git a/ViewModel/Limpieza/DockpaneLimpiezaViewModel.cs b/ViewModel/Limpieza/DockpaneLimpiezaViewModel.cs index a95768a..9ddcd53 100644 --- a/ViewModel/Limpieza/DockpaneLimpiezaViewModel.cs +++ b/ViewModel/Limpieza/DockpaneLimpiezaViewModel.cs @@ -57,6 +57,7 @@ namespace OliviaAddInPro internal static void Reset() { //HAY QUE HACER QUE SE LIMPIE TODO + } //The parameter passed to this method will be true if the Dockpane is being opened and it is false when you close the dockpane diff --git a/ViewModel/Limpieza/PaneLimpiezaSub2ViewModel.cs b/ViewModel/Limpieza/PaneLimpiezaSub2ViewModel.cs index c965537..a36335b 100644 --- a/ViewModel/Limpieza/PaneLimpiezaSub2ViewModel.cs +++ b/ViewModel/Limpieza/PaneLimpiezaSub2ViewModel.cs @@ -14,6 +14,7 @@ using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Framework.Dialogs; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Desktop.Mapping; +using OliviaAddInPro.Model; namespace OliviaAddInPro { @@ -22,7 +23,7 @@ namespace OliviaAddInPro public PaneLimpiezaSub2ViewModel() { lblCapaRestr= lblCapaNiv= lblCapaZon= lblCapaInst = Resource1.String_selec_capa; - txtBuffExport = 1000; + txtBuffExport = ComunDef.BuffExport; } diff --git a/ViewModel/Limpieza/PaneLimpiezaViewModel.cs b/ViewModel/Limpieza/PaneLimpiezaViewModel.cs index 18fa29a..711e513 100644 --- a/ViewModel/Limpieza/PaneLimpiezaViewModel.cs +++ b/ViewModel/Limpieza/PaneLimpiezaViewModel.cs @@ -176,7 +176,6 @@ namespace OliviaAddInPro OliviaGlob.progrDialog.Show(); var progSrc = new CancelableProgressorSource(OliviaGlob.progrDialog); - if (!Lee(out err)) { HelperGlobal.ponMsg(err); diff --git a/ViewModel/PanelViewModelBase.cs b/ViewModel/PanelViewModelBase.cs index 5588ef9..7f3d1e0 100644 --- a/ViewModel/PanelViewModelBase.cs +++ b/ViewModel/PanelViewModelBase.cs @@ -7,6 +7,7 @@ using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Runtime.InteropServices.WindowsRuntime; using OliviaAddInPro.Model; +using OliviaAddInPro.Helper; namespace OliviaAddInPro { @@ -122,6 +123,7 @@ namespace OliviaAddInPro return false; } return true; + } } diff --git a/ViewModel/Recogida/PaneRecogidaViewModel.cs b/ViewModel/Recogida/PaneRecogidaViewModel.cs index ccfad63..e716a50 100644 --- a/ViewModel/Recogida/PaneRecogidaViewModel.cs +++ b/ViewModel/Recogida/PaneRecogidaViewModel.cs @@ -101,9 +101,7 @@ namespace OliviaAddInPro err_str = "No se ha seleccionado ninguna Capa de Limpieza"; return false; } - reco.CapaElems = _subPanel1ViewModel.CapaElems; - reco.TipoTto = reco.TipoFrac; - reco.TipoTtoStr= RecogidaDef.tipos_fracc_str[reco.TipoFrac]; + reco.CapaElems = _subPanel1ViewModel.CapaElems; //lee la fracción reco.TipoFrac = _subPanel1ViewModel.TipoFrac; if (reco.TipoFrac == -1) @@ -112,6 +110,8 @@ namespace OliviaAddInPro return false; } reco.TipoFracStr = RecogidaDef.tipos_fracc_str[reco.TipoFrac]; + reco.TipoTto = reco.TipoFrac; + reco.TipoTtoStr = RecogidaDef.tipos_fracc_str[reco.TipoFrac]; //lee la densidad del contenedor //si se ha seleccionado que se recogen los contenedores llenos hay que comprobar que se ha rellenado la densidad de los contenedores @@ -213,6 +213,7 @@ namespace OliviaAddInPro } catch { + err_str = "Error al leer ventana de descarga: "+ err_str; return false; } }