OliviaAddInPro/Services/EjecServ.cs

1170 lines
52 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OliviaAddInPro.Model;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using OliviaAddInPro.Helper;
using ArcGIS.Core.Internal.Data;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using System.Windows;
using System.IO;
namespace OliviaAddInPro.Services
{
public enum ModosEjec
{
Sectoriza,
Planifica,
SoloPlanifica
}
//Clase que realiza las funciones de la ejecución
public class EjecServ
{
//Cadenas de nombres internos para la exportación/importación de los archivos
public string PREF_NAME_EXPORT = "data_";
public string EXT_SHP = ".shp";
public string PREF_NAME_EXPORT_NW = "nw_";
public string PREF_NAME_EXPORT_NW_CONJ = "nw_c_";
public string NAME_CSV = "_L";
public string EXT_CSV = ".csv";
public string NAME_RUTA2 = "_R2";
public string NAME_RUTA2_OUT = "_Viajes";
public string NAME_AUX = "_aux";
public string NAME_SECT = "_Sector";
public string NAME_CONTROL_OUT = "_Control";
public string NAME_CONTROL = "_C";
public string NAME_RUTA_OUT = "_Ruta";
public string NAME_RUTA = "_R";
public string NAME_RUTA_AUX = "_Raux";
public string NAME_INSTAL = "_I";
public string NAME_INSTAL_OUT = "_Instalacion";
public int TipoMv { get; set; }
public string ErrStr = "";
SpatialQueryFilter filtroEspacial = null;
//SpatialReference spatRef = null;
SpatialReference spatRefData = null;
public TratamientoComun com;
/**
* Acciones para comenzar ejecución
* Modo 0, sectorizar
* Modo 1, planificar
*/
public bool ExportaEjec(ModosEjec modo, out string ErrStr)
{
ErrStr = string.Empty;
OliviaGlob.Paths.PathData = string.Empty;
OliviaGlob.Paths.PathNW = string.Empty;
OliviaGlob.Paths.PathNW_c= string.Empty;
if (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
return false;
}
try
{
com.ProgrSrc.Init("Exportando datos");
//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;
}
if (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
return false;
}
//////////////////////////////////////////////
///Se guarda el nombre de los campos originales
///
com.GuardaCamposOrig(com.CapaElems);
//Cuenta las filas que cumplen la consulta
var nelems = HelperGdb.GetNumElemsSync(com.CapaElems, com.ConsultaAmbs);
if (nelems <= 0)
{
ErrStr = "No existen ámbitos que cumplan las condiciones introducidas para la exportación " + com.ConsultaAmbs;
return false;
}
if (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
return false;
}
com.ProgrSrc.IncMessage(0, "Exportando geometria");
//////////////////////////////////////////////////////////////
Coordinate2D[] coords = { com.CoordsInstal, com.CoordsPlanta };
//Reproyecta las geometrías si es necesario
SpatialReference spatref = HelperGdb.GetSpatRefSync(com.CapaElems);
if (spatref != null)
{
if (com.GeomNiv != null)
com.GeomNiv = HelperGdb.ReproyectaGeom(com.GeomNiv, spatref);
if (com.GeomZon != null)
com.GeomZon = HelperGdb.ReproyectaGeom(com.GeomZon, spatref);
if (com.GeomRestr != null)
com.GeomRestr = HelperGdb.ReproyectaGeom(com.GeomRestr, spatref);
//ahora las coordenadas
for (int i = 0; i < coords.Length; i++)
{
if (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
return false;
}
if (!coords[i].IsEmpty && (coords[i].X != 0))
{
MapPoint mp = MapPointBuilderEx.CreateMapPoint(coords[i].X, coords[i].Y, spatref);
coords[i].X = mp.X;
coords[i].Y = mp.Y;
}
}
}
//////////////////////////////////////////////////////////////
//Obtiene la geometría que envuelve a los ámbitos
Geometry geom_export = null;
geom_export = GetGeomAmbitsExport();
if (geom_export == null || geom_export.IsEmpty)
{
ErrStr = "No se ha podido generar geometría de los ámbitos" + com.ConsultaAmbs + ErrStr;
return false;
}
if (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
return false;
}
//mira spatialreference de los datos de entrada
spatRefData = geom_export.SpatialReference;
//crea el filtro de exportación
filtroEspacial = HelperGdb.CreateFiler(com.ConsultaAmbs, geom_export);
if (filtroEspacial == null)
{
ErrStr = "Error al crear el filtro de exportacion de los ámbitos";
return false;
}
if (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
return false;
}
//Termina de preparar nombre
//Prepara nombre
string fechaHora = string.Empty;
//se consigue el tiempo en este instante para añadirlo a los nombres de los archivos de salida (shapefiles)
fechaHora = DateTime.Now.ToString("yyyyMMdd_Hmmss");
//Pone nombre al shape en función de los ámbitos, el tratamiento, y los polígonos + timestamp
com.NombreShpExport = PREF_NAME_EXPORT + com.NombreShpExp_PrefTto + "_" + fechaHora + EXT_SHP;
com.ProgrSrc.IncMessage(10, "Exportando ámbitos de trabajo");//10%
//Guarda el nombre
OliviaGlob.Paths.PathData = OliviaGlob.Paths.DirData + com.NombreShpExport;
//exporta los datos de entrada
if (!HelperGdb.ExportShp2(com.CapaElems, filtroEspacial, com.NombreShpExport, OliviaGlob.Paths.DirData, com.ProgrSrc._ProgrSrc, null, 50))
{
ErrStr = "Error al exportar los ámbitos: " + HelperGdb.OutStr;
return false;
}
if (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
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())
{
string capa_principal = System.IO.Path.GetFileNameWithoutExtension(OliviaGlob.Paths.PathData);
HelperGdb.CloseLayer(capa_principal);
if (!ActualizaSecto(OliviaGlob.Paths.PathData, com.CapaPlanif))
{
ErrStr = "Error al exportar campos de SECTOR y/o SECUENCIA de la capa " + com.CapaPlanif;
return false;
}
}
if (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
return false;
}
///////////////////////////////////////////////////////////////////////
///
com.ProgrSrc.IncMessage(40, "Preparando exportación de red navegable");//50%
//hace intersecciones espaciales en caso de ámbitos lineales para quitar los que tienen más parte fuera de la zona que dentro
//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))
{
ErrStr = "Error al quitar los ámbitos que sobresalen: " + HelperGdb.OutStr;
return false;
}
}*/
///////////////////////////////////////////////////////////////////////////
//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<bool> resp = HelperGdb.IsPtoInGeom(com.CoordsInstal, com.GeomRestr);
if (!resp.Value && resp.HasError)
{
ErrStr = "Error al comprobar si la instalación está contenida en el polígono de restricciones: " + resp.Error.ElementAt(0);
return false;
}
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 (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
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
geom_export = HelperGdb.BufferGeom(geom_export, com.BuffExport).Value;
if (geom_export == null)
{
ErrStr = "Error al añadir buffer a la geometría";
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++)
{
if (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
return false;
}
if (!coords[i].IsEmpty && (coords[i].X != 0))
{
Respuesta<bool> resp = HelperGdb.IsPtoInGeom(coords[i], geom_export);
if (!resp.Value) //si no lo contiene
{
//ha ido mal
if (resp.HasError)
{
ErrStr = "Error al comprobar si la instalación está contenida en el polígono de exportación: " + resp.Error.ElementAt(0);
return false;
}
else
{
//amplía la geom
Respuesta<ArcGIS.Core.Geometry.Geometry> respGeom = HelperGdb.AddPtoInGeom(coords[i], geom_export, com.BuffExport);
if (respGeom.Value == null)
{
//ha ido mal
if (resp.HasError)
ErrStr = resp.Error.ElementAt(0);
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);
if (fc != null)
{
spatRef = fc.GetDefinition().GetSpatialReference();
//AQUÍ COMPARAR SI ES IGUAL QUE SPATREFDEF Y SI NO, REPROYECTAR
if (spatRef.Wkid != spatRefData.Wkid)
{
var sp_ref = SpatialReferenceBuilder.CreateSpatialReference(102629); // NAD83 SP AL E FIPS 0101 Feet
var envi = Geoprocessing.MakeEnvironmentArray(outputCoordinateSystem: sp_ref);
//https://pro.arcgis.com/es/pro-app/2.8/tool-reference/environment-settings/output-coordinate-system.htm
//ProjectionTransformation transf_forTarget = ProjectionTransformation.Create(spatRef, spatRefData);
//geom_export=GeometryEngine.Instance.ProjectEx(geom_export, transf_forTarget);
//transf_forTarget.Transformation
/*
* FALTA HACER
* /
}
}*/
//////////////////////////////////////
//guarda la mima de la geometría de la red navegable a exportar
com.MimaNw = geom_export.Extent;
//////////////////////////////////////
///
//Hace el filtro con la geometría final
filtroEspacial = HelperGdb.CreateFiler(String.Empty, geom_export);
if (filtroEspacial == null)
{
ErrStr = "Error al crear el filtro de exportacion de la red navegable";
return false;
}
if (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
return false;
}
com.ProgrSrc.IncMessage(10, "Exportando red navegable");//60%
//Prepara nombre de exportación
com.NombreShpExportNw = PREF_NAME_EXPORT_NW + fechaHora + EXT_SHP;
//guarda los nombres del shape
OliviaGlob.Paths.PathNW = OliviaGlob.Paths.DirData + com.NombreShpExportNw;
//exporta los datos de entrada
if (!HelperGdb.ExportShp2(OliviaGlob.Paths.PathGdbNw, filtroEspacial, com.NombreShpExportNw, OliviaGlob.Paths.DirData, com.ProgrSrc._ProgrSrc, spatRefData,100))
{
ErrStr = "Error al exportar la red navegable: " + HelperGdb.OutStr;
return false;
}
if (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
return false;
}
com.NombreShpExportNw_C = PREF_NAME_EXPORT_NW_CONJ + fechaHora + EXT_SHP;
OliviaGlob.Paths.PathNW_c = OliviaGlob.Paths.DirData + com.NombreShpExportNw_C;
if (ComunDef.CamposNW.config.revisa_conjunciones)
{
if (!HelperGdb.ExportShp2(OliviaGlob.Paths.PathGdbNw_conj, filtroEspacial, com.NombreShpExportNw_C, OliviaGlob.Paths.DirData, com.ProgrSrc._ProgrSrc, spatRefData, 100))
{
ErrStr = "Error al exportar la red navegable: " + HelperGdb.OutStr;
return false;
}
if (com.ProgrSrc._ProgrSrc.Getcancelled())
{
ErrStr = Resource1.String_cancel_progreso;
return false;
}
}
//prepara campos estandar
if(!EstandarizaCamposNW(OliviaGlob.Paths.DirData+com.NombreShpExportNw))
{
ErrStr = "Error al estandarizar campos red navegable: " + HelperGdb.OutStr;
return false;
}
com.ProgrSrc.IncMessage(40, "Finalizada Exportación. Conectando con Olivia Tasks.");//100%
}
catch (Exception ex)
{
ErrStr = "Errores al exportar para comenzar la ejecución: " + ex.Message;
return false;
}
return true;
}
bool EstandarizaCamposNW(string pathNW)
{
HelperGdb.FieldToAdd[] fields = new HelperGdb.FieldToAdd[8];
//campo SECTOR
int i = 0;
fields[i].Name = ComunDef.CamposNW.cons_kph;
fields[i].Alias = ComunDef.CamposNW.cons_kph;
fields[i].Tipo = "FLOAT";
fields[i].Length = 0;
i++;
fields[i].Name = ComunDef.CamposNW.cons_ele_f;
fields[i].Alias = ComunDef.CamposNW.cons_ele_f;
fields[i].Tipo = "FLOAT";
fields[i].Length = 0;
i++;
fields[i].Name = ComunDef.CamposNW.cons_ele_t;
fields[i].Alias = ComunDef.CamposNW.cons_ele_t;
fields[i].Tipo = "FLOAT";
fields[i].Length = 0;
i++;
fields[i].Name = ComunDef.CamposNW.cons_fow;
fields[i].Alias = ComunDef.CamposNW.cons_fow;
fields[i].Tipo = "LONG";
fields[i].Length = 0;
i++;
fields[i].Name = ComunDef.CamposNW.cons_onewFT;
fields[i].Alias = ComunDef.CamposNW.cons_onewFT;
fields[i].Tipo = "LONG";
fields[i].Length = 0;
i++;
fields[i].Name = ComunDef.CamposNW.cons_onewTF;
fields[i].Alias = ComunDef.CamposNW.cons_onewTF;
fields[i].Tipo = "LONG";
fields[i].Length = 0;
i++;
fields[i].Name = ComunDef.CamposNW.cons_evit;
fields[i].Alias = ComunDef.CamposNW.cons_evit;
fields[i].Tipo = "LONG";
fields[i].Length = 0;
i++;
fields[i].Name = ComunDef.CamposNW.cons_name;
fields[i].Alias = ComunDef.CamposNW.cons_name;
fields[i].Tipo = "TEXT";
fields[i].Length = 128;
if (!HelperGdb.AddFieldsSync(pathNW, fields))
return false;
if (!HelperGdb.CalculateFieldsSync(pathNW, ComunDef.CamposNW.cons_kph, ComunDef.CamposNW.config.campo_velocidad))
return false;
if (!HelperGdb.CalculateFieldsSync(pathNW, ComunDef.CamposNW.cons_name, ComunDef.CamposNW.config.campo_nombre))
return false;
if (!HelperGdb.CalculateFieldsSync(pathNW, ComunDef.CamposNW.cons_fow, ComunDef.CamposNW.config.campo_peatonal))
return false;
if (!HelperGdb.CalculateFieldsSync(pathNW, ComunDef.CamposNW.cons_onewTF, ComunDef.CamposNW.config.campo_sentidoTf))
return false;
if (!HelperGdb.CalculateFieldsSync(pathNW, ComunDef.CamposNW.cons_onewFT, ComunDef.CamposNW.config.campo_sentidoFT))
return false;
if (!HelperGdb.CalculateFieldsSync(pathNW, ComunDef.CamposNW.cons_ele_t, ComunDef.CamposNW.config.campo_elevacion_to))
return false;
if (!HelperGdb.CalculateFieldsSync(pathNW, ComunDef.CamposNW.cons_ele_f, ComunDef.CamposNW.config.campo_elevacion_from))
return false;
if (!HelperGdb.CalculateFieldsSync(pathNW, ComunDef.CamposNW.cons_evit, "0"))
return false;
return true;
}
/**
* Actualiza la capa dada añadiendo una columna de sector y una de secuencia
*/
public bool ActualizaSecto(string path_shp, string path_secto)
{
//Añade al shp exportado la columna de sector y secuencia
HelperGdb.FieldToAdd[] fields = new HelperGdb.FieldToAdd[2];
//campo SECTOR
fields[0].Name = ComunDef.CamposCom.consulta_sector;
fields[0].Alias = ComunDef.CamposCom.consulta_sector;
fields[0].Tipo = "LONG";
fields[0].Length = 0;
//campo SECUENCIA
fields[1].Name = ComunDef.CamposCom.consulta_secuen;
fields[1].Alias = ComunDef.CamposCom.consulta_secuen;
fields[1].Tipo = "LONG";
fields[1].Length = 0;
if (!HelperGdb.AddFieldsSync(path_shp, fields))
return false;
//vuelve a cerrar la capa
string capa_principal = System.IO.Path.GetFileNameWithoutExtension(path_shp);
HelperGdb.CloseLayer(capa_principal);
/////////////////////////////////////////////////////
//ahora rellena las columnas
using (FeatureClass fc_secto = HelperGdb.GetFtClassSync(path_secto))
{
using (FeatureClass fc_shp = HelperGdb.GetFtClassSync(path_shp))
{
if (fc_secto == null || fc_shp == null)
return false;
try
{
using (RowCursor rc_shp = fc_shp.Search())
{
using (RowCursor rc_secto = fc_secto.Search())
{
if (rc_shp == null || rc_secto == null)
return false;
var modifyOp = new ArcGIS.Desktop.Editing.EditOperation();
modifyOp.Name = "Actualiza SECTOR y SECUENCIA";
bool ex = false;
//modifyOp.Callback((context) =>
//{
while (rc_shp.MoveNext() && rc_secto.MoveNext())
{
using (Row rowsecto = rc_secto.Current)
{
using (Row rowshp = rc_shp.Current)
{
//context.Invalidate(rowshp);
// modify and execute
modifyOp.Modify(rowshp, ComunDef.CamposCom.consulta_sector, rowsecto[ComunDef.CamposCom.consulta_sector]);
modifyOp.Modify(rowshp, ComunDef.CamposCom.consulta_secuen, rowsecto[ComunDef.CamposCom.consulta_secuen]);
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;
}
}
}
/*
var modifyOp = new ArcGIS.Desktop.Editing.EditOperation();
modifyOp.Name = "Actualiza SECTOR y SECUENCIA";
bool ex=false;
modifyOp.Callback((context) =>
{
using (RowCursor rc_shp = fc_shp.Search())
{
using (RowCursor rc_secto = fc_secto.Search())
{
if (rc_shp != null && rc_secto != null)
{
while (rc_shp.MoveNext() && rc_secto.MoveNext())
{
using (Row rowsecto = rc_secto.Current)
{
using (Row rowshp = rc_shp.Current)
{
context.Invalidate(rowshp);
// modify and execute
modifyOp.Modify(rowshp, LimpiezaDef.Campos.consulta_sector, rowsecto[LimpiezaDef.Campos.consulta_sector]);
modifyOp.Modify(rowshp, LimpiezaDef.Campos.consulta_secuen, rowsecto[LimpiezaDef.Campos.consulta_secuen]);
rowshp.Store();
context.Invalidate(rowshp);
}
}
}
bien = true;
rc_secto.Dispose();
rc_shp.Dispose();
}
}
}
}, fc_shp);
ex = modifyOp.Execute();
if (bien && ex && modifyOp.IsDone)
return true;
else
return false;
}
catch
{
}
finally
{
fc_secto.Dispose();
fc_shp.Dispose();
HelperGdb.Free(fc_secto);
HelperGdb.Free(fc_shp);
}
return false;*/
}
/**
* 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
bool compCamp = HelperGdb.CheckField(pathCapa, ComunDef.CamposCom.camp_oid);
ErrStr = HelperGdb.OutStr;
if (compCamp)
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
using (FeatureClass fc_orig = HelperGdb.GetFtClassSync(pathCapaOrig))
{
if (fc_orig == null)
return false;
List<long> ids = new List<long>();
//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<long>();
}
//Comprueba que hay tantos ids como elementos en el shp
using (FeatureClass fc_shp = HelperGdb.GetFtClassSync(pathCapa))
{
if (fc_shp == null)
return false;
long 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;
Geometry geomAmbits = null;
ErrStr = string.Empty;
FeatureClass fc = HelperGdb.GetFtClassSync(com.CapaElems);
if (fc == null)
{
ErrStr = "No se ha podido abrir la clase " + com.CapaElems;
return null;
}
//Hace la intersección de zonas y niveles
geomAux = null;
if (com.GeomNiv != null || com.GeomZon != null)
{
geomAux = HelperGdb.IntersectGeom(com.GeomNiv, com.GeomZon);
if (geomAux == null)
{
ErrStr = "Error al intersecar zonas y/o niveles.";
HelperGdb.Free(fc);
return null;
}
if (geomAux.IsEmpty)
{
ErrStr = "No existen ámbitos en la intersección entre zonas y/o niveles.";
HelperGdb.Free(fc);
return null;
}
}
//comprueba que, en el caso de ejes de vía, hayan metido polígono de exportación
if ((geomAux == null) && (com.CapaElems == OliviaGlob.Paths.PathGdbNw))
{
ErrStr = "Al emplear ejes de calle como ámbitos es necesario indicar polígono de exportación";
HelperGdb.Free(fc);
return null;
}
//prepara el filtro con consulta y espacial
SpatialQueryFilter filtro = HelperGdb.CreateFiler(com.ConsultaAmbs, geomAux);
//if (geomAux == null)
{
//Ahora hace la geometría de los ámbitos que cumplen la consulta
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;
HelperGdb.Free(fc);
return null;
}
if (geomAux == null)
geomAux = geomAmbits;
else
{
geomAux = HelperGdb.IntersectGeom(geomAux, geomAmbits);
//geomAux = GeometryEngine.Instance.ConvexHull(geomAux);
}
}
//le quita las restricciones
if (com.GeomRestr != null)
{
geomAux = HelperGdb.QuitaGeom(geomAux, com.GeomRestr);
if (geomAux == null)
{
ErrStr = "Error al intersecar con las restricciones.";
HelperGdb.Free(fc);
return null;
}
}
HelperGdb.Free(fc);
return geomAux;
}
/**
* Devuelve el string a concatenar en el nombre del path dependiendo de los polígonos seleccionados (zonas, turnos... etc)
*/
public string DameStrPoligs()
{
string str = "";
if (com.TextGeomNiv != "" && com.GeomNiv != null)
str += "_N" + com.TextGeomNiv;
if (com.TextGeomZon != "" && com.GeomZon != null)
str += "_Z" + com.TextGeomZon;
if (com.TextGeomRestr != "" && com.GeomRestr != null)
str += "_R" + com.TextGeomRestr;
return str;
}
public bool ComprCamposPlanif(string pathCapa)
{
int NCAMPS = 2;
string[] camps;
camps = new string[NCAMPS];
camps[0] = ComunDef.CamposCom.consulta_sector;
camps[1] = ComunDef.CamposCom.consulta_secuen;
return HelperGdb.CheckFiledsSync(pathCapa, camps) == 0;
}
/**
* Comprueba lo necesario para ver si hay campos para la planificación
*/
public bool CompruebaPlanif()
{
//si ha importado seguro que las tiene
if (OliviaGlob.IsConfig2() && !string.IsNullOrEmpty(com.CapaPlanif))
return true;
//comprueba capa
if (ComprCamposPlanif(com.CapaElems))
{
com.CapaPlanif = string.Empty;//reinicia para que coja la secto de la capa original
return true;
}
return false;
}
/**
* Realiza las funciones de importación de la sectorización
*/
public Respuesta<string> ImportSecto(string GdbFileName, string FtClssName)
{
com.ProgrSrc.IncMessage(10,"Importando capas");
var res = Import(GdbFileName, 0, FtClssName);
if (res.HasError || string.IsNullOrEmpty(res.Value))
{
return res;
}
//////////////////////////////////////////////////
com.ProgrSrc.IncMessage(50, "Pintando capas con valores únicos");
//abre las capas, pintando los sectores
bool mal = false;
string path_import = res.Value;
//abre con valor único
string path_lyr = path_import;
var resb = HelperGdb.OpenLayerUniqueValue(path_lyr, ComunDef.CamposCom.consulta_sector);
if (!resb.Value)
{
res.Error.Add("Error al abrir capa "+ path_lyr + " con Valor único. " + resb.Error.FirstOrDefault());
res.Value = string.Empty;
mal = true;
}
if(!mal)
res.Value = path_import;
return res;
}
/**
* Realiza las funciones de importación de la planificación
*/
public Respuesta<string> ImportPlanif(string GdbFileName, string FtClssName)
{
com.ProgrSrc.IncMessage(10, "Importando capas");
var res = Import(GdbFileName, 1, FtClssName);
if (res.HasError || string.IsNullOrEmpty(res.Value))
{
res.Value = string.Empty;
return res;
}
//////////////////////////////////////////////////
com.ProgrSrc.IncMessage(30, "Pintando capas con valores únicos");
//abre las capas, pintando los sectores
string path_import = res.Value;
int NOPEN = 6;
int nopen_ = 4;
string[] path_lyr_arr = new string[NOPEN];
//se añade la capa de ambitos original con la secto, y se pinta por sectores - shape
path_lyr_arr[0] = path_import;
//la primera capa que se añade es la de ruta, se le quita la visualización porque lo que interesa
//de esa capa es poder acceder si fuera necesario a la tabla de atributos. shape + name_ruta_out
path_lyr_arr[1]= path_import + NAME_RUTA_OUT;
//se añade la capa de ruta_aux y se pinta por sectores - shape + name_ruta_out + name_aux
path_lyr_arr[2] = path_import + NAME_RUTA_OUT + NAME_AUX;
//se abre la capa de puntos de control y se pintan por el sector al que pertenecen - shape + name_control_out
path_lyr_arr[3] = path_import + NAME_CONTROL_OUT;
//la siguiente es la de ruta2, se le quita la visualización porque lo que interesa
//de esa capa es poder acceder si fuera necesario a la tabla de atributos. shape + name_ruta2_out
if (System.IO.File.Exists(path_import + NAME_RUTA2_OUT))
path_lyr_arr[nopen_++] = path_import + NAME_RUTA2_OUT;
//se añade la capa de la ruta a las instalaciones, comprueba si hay configurada coordenadas de la instalación - shape + name_inst_out
if (System.IO.File.Exists(path_import + NAME_INSTAL_OUT))
path_lyr_arr[nopen_++] = path_import + NAME_INSTAL_OUT;
NOPEN = nopen_;
bool[] visible_arr = {true,false,true,false,false,false };
int i;
var resb = new Respuesta<bool>();
for(i =0;i<NOPEN;i++)
{
com.ProgrSrc.IncMessage((uint)(60 / NOPEN));
resb = HelperGdb.OpenLayerUniqueValue(path_lyr_arr[i], ComunDef.CamposCom.consulta_sector, visible_arr[i]);
if (!resb.Value)
break;
}
if(i<NOPEN)
{
res.Value = string.Empty;
res.Error.Add("Error al abrir capa " + path_lyr_arr[i] + " con Valor único. "+resb.Error.FirstOrDefault() );
}
else
{
res.Value = path_import;
}
return res;
}
/**
* Realiza las funciones de importación, modo 0 secto, modo 1 planif
*/
public Respuesta<string> Import(string GdbFileName, int modo, string FtClssName="")
{
var res = new Respuesta<string> { Value = string.Empty };
/////////////////////////////////////////
string path_shape = OliviaGlob.Paths.PathData;
string dir_shp = System.IO.Path.GetDirectoryName(path_shape);
string shapefile = System.IO.Path.GetFileNameWithoutExtension(path_shape);
int ind = shapefile.IndexOf("_", 0);
string prefijo = shapefile.Substring(ind + 1, 1);
//////////////////////////////////////////////////////////////////////////////////
//decodifica el nombre del shapefile para asignarle el correspondiente nombre en la GDB a la que se importa el shape
string tratamiento = string.Empty;
string ambitos = string.Empty;
com.decode_gdb(shapefile, out tratamiento, out ambitos); //supsuestamente distingue si es limpieza o recogida
if(string.IsNullOrEmpty(tratamiento) || string.IsNullOrEmpty(ambitos))
{
res.Error.Add(string.Format("Nombre del archivo a importar erróneo. No se reconoce el prefijo introducido: {0}", prefijo));
return res;
}
bool reco_o_limp_con_instala = (prefijo == "F") ||
((prefijo == "T") && !com.CoordsInstal.Equals(new Coordinate2D(0, 0)));
bool reco_tramos = System.IO.File.Exists(System.IO.Path.Combine(dir_shp, shapefile + NAME_RUTA2 + EXT_SHP));
/////////////////////////////////////////
/////mira a ver si tiene configurado Dataset
string msg_avisa = string.Empty;
string amb_aux = string.Empty;
bool sobreescribe = false;
if (!string.IsNullOrEmpty(OliviaGlob.Paths.PathDatasetImport))
{
var datname = new System.IO.DirectoryInfo(OliviaGlob.Paths.PathDatasetImport).Name;
var task1 = HelperGdb.CheckDataset(OliviaGlob.Paths.PathDatasetImport);
task1.Wait();
if (task1.Result)
{
tratamiento = datname;
}
else
{
msg_avisa = "No se encuentra el Dataset " + datname + ". ";
}
}
else
{
/////////////////////////////////////////
//no tiene un dataset configurado, saca ventana para elegir uno
//saca ventana para elegir Dataset, si se cancela, se guarda en el nombre por defecto en función del tratamiento y los ámbitos
//HelperGlobal.ponMsg("A continuación, introduzca nombre de Feature Class y ubicación (Dataset) para importación. Si cancela el proceso, se establecerán el nombre y Dataset por defecto en función de los ámbitos y el tratamiento");
string path_aux = FtClssName;
//HelperGdb.SaveFileDlg("Introduzca nombre de Feature Class a importar", GdbFileName, null, ArcGIS.Desktop.Catalog.ItemFilters.featureClasses_all);
if (!string.IsNullOrEmpty(path_aux))
{
tratamiento = new DirectoryInfo(System.IO.Path.GetDirectoryName(path_aux)).Name;
//tratamiento = System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(path_aux));
amb_aux = System.IO.Path.GetFileNameWithoutExtension(path_aux);
//comprueba si ya existe ese ft class
FeatureClass ft = HelperGdb.GetFtClassSync(path_aux);
if (ft != null)
sobreescribe = true;
HelperGdb.Free(ft);
}
}
//crea el dataset o comprueba si existe
string datasetNameOut = string.Empty;
var resp = HelperGdb.CreateDataset(GdbFileName, tratamiento, spatRefData, out datasetNameOut);
if(resp.Value==0)
{
//avisa
msg_avisa += "Se importan los archivos en " + GdbFileName + "\\" + datasetNameOut;
//HelperGlobal.ponMsg("Se importan los archivos en "+ GdbFileName+"\\"+ datasetNameOut);
tratamiento = datasetNameOut;
}
else if (resp.Value == 1)
{
res.Error.Add("Error al crear el Dataset para importar " + tratamiento);
return res;
}
else //2 o 4 if (resp.Value == 2)
{
//avisa
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;
}
//avisa ahora para dar tiempo?
if (!string.IsNullOrEmpty(msg_avisa))
{
if(!HelperGlobal.ponMsg(msg_avisa, MessageBoxImage.Question, "OLIVIA", MessageBoxButton.OKCancel))
{
res.Error.Add("Proceso de importación Cancelado por el usuario");
return res;
}
}
string dataset = tratamiento;
/////////////////////////////////////////
if (!string.IsNullOrEmpty(amb_aux))
ambitos = amb_aux;
/////////////////////////////////////////
//todo ok, se pone a importar
string err_st =string.Empty;
string path_import = GdbFileName + "\\" + dataset + "\\" + ambitos;
int NIMPORT;
string[] noms_shp = null;
string[] noms_gdb = null;
int i;
int ii = 0;
NIMPORT = 0;
if (modo == 0) //sectoriza
{
NIMPORT = 1;
noms_shp = new string[NIMPORT];
noms_gdb = new string[NIMPORT];
noms_shp[0] = shapefile;
noms_gdb[0] = ambitos;
/*noms_shp[1] = shapefile + NAME_AUX;
noms_gdb[1] = ambitos + NAME_SECT;*/
}
else if (modo == 1) //planifica
{
if (reco_o_limp_con_instala)
NIMPORT = 5;
else
NIMPORT = 4;
if (reco_tramos)
NIMPORT++;
noms_shp = new string[NIMPORT];
noms_gdb = new string[NIMPORT];
noms_shp[0] = shapefile;
noms_gdb[0] = ambitos;
/*noms_shp[1] = shapefile + NAME_AUX;
noms_gdb[1] = ambitos + NAME_SECT;*/
noms_shp[1] = shapefile + NAME_CONTROL;
noms_gdb[1] = ambitos + NAME_CONTROL_OUT;
noms_shp[2] = shapefile + NAME_RUTA;
noms_gdb[2] = ambitos + NAME_RUTA_OUT;
noms_shp[3] = shapefile + NAME_RUTA_AUX;
noms_gdb[3] = ambitos + NAME_RUTA_OUT + NAME_AUX;
ii = 4;
if (reco_o_limp_con_instala)
{
noms_shp[4] = shapefile + NAME_INSTAL;
noms_gdb[4] = ambitos + NAME_INSTAL_OUT;
ii++;
}
if (reco_tramos)
{
noms_shp[ii] = shapefile + NAME_RUTA2;
noms_gdb[ii] = ambitos + NAME_RUTA2_OUT;
}
}
if (noms_gdb == null || noms_shp==null)
{
res.Error.Add("Errores al crear los nombres de las Feature Class");
return res;
}
Respuesta<bool> resp2;
try
{
/////////////////////////////////////////
//se embucla para hacer todas las importaciones necesarias
for (i = 0; i < NIMPORT; i++)
{
//mira a ver si hay que borrar para reemplazar
if (sobreescribe)
{
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];
break;
}
}
resp2 = HelperGdb.ImportShp(dir_shp + "\\" + noms_shp[i] + HelperGdb.SHP_EXT, GdbFileName + "\\" + dataset, noms_gdb[i]);
if (!resp2.Value)
{
err_st = "Error al importar la capa " + noms_gdb[i];
if (resp2.HasError)
err_st += " " + resp2.Error.First();
break;
}
}
if (i < NIMPORT)
{
res.Error.Add("Errores en la importación: "+err_st);
return res;
}
//cambia el nombre de los campos que había truncado a 10 caracteres al exportar a shp
//solo para la capa original
resp2 = com.RestauraNomCampos(GdbFileName + "\\" + dataset + "\\" + noms_gdb[0]);
if (!resp2.Value)
{
err_st = "Error al renombrar campos " + noms_gdb[0];
if (resp2.HasError)
err_st += " " + resp2.Error.First();
res.Error.Add("Errores en la importación: " + err_st);
return res;
}
}
catch
{
res.Error.Add("Errores en la importación");
return res;
}
finally
{
}
res.Value = path_import;
return res;
}
/**
* Cierra del mapa las capas de trabajo después de la exportación
*/
public void CierraCapas()
{
if (!string.IsNullOrEmpty(OliviaGlob.Paths.PathData))
{
string capa_principal = System.IO.Path.GetFileNameWithoutExtension(OliviaGlob.Paths.PathData);
HelperGdb.CloseLayer(capa_principal);
}
if (!string.IsNullOrEmpty(OliviaGlob.Paths.PathNW))
{
string capa_principal_nw = System.IO.Path.GetFileNameWithoutExtension(OliviaGlob.Paths.PathNW);
HelperGdb.CloseLayer(capa_principal_nw);
}
if (!string.IsNullOrEmpty(OliviaGlob.Paths.PathNW_c))
{
string capa_principal_nw_c = System.IO.Path.GetFileNameWithoutExtension(OliviaGlob.Paths.PathNW_c);
HelperGdb.CloseLayer(capa_principal_nw_c);
}
}
}
}