Avances importación

Elena/develop
Elena 2022-05-17 15:06:02 +02:00
parent 7f824052a3
commit 7ab639b800
8 changed files with 400 additions and 145 deletions

View File

@ -29,7 +29,8 @@ namespace OliviaAddInPro.Helper
{ {
private static string ObjectId = "OBJECTID"; private static string ObjectId = "OBJECTID";
private static string out_str = string.Empty; private static string out_str = string.Empty;
public static string OutStr { public static string OutStr
{
get get
{ {
/*string val = ""; /*string val = "";
@ -43,7 +44,8 @@ namespace OliviaAddInPro.Helper
private static string texto_sal = string.Empty; private static string texto_sal = string.Empty;
public static string TextoSal public static string TextoSal
{ {
get { get
{
/*string val = ""; /*string val = "";
val.CopyFrom(texto_sal); val.CopyFrom(texto_sal);
texto_sal = string.Empty; //lo borra cada vez que se consulta texto_sal = string.Empty; //lo borra cada vez que se consulta
@ -58,10 +60,10 @@ namespace OliviaAddInPro.Helper
[Flags] [Flags]
public enum TiposOpenFileDlg public enum TiposOpenFileDlg
{ {
OpenFtrClassLine=1, OpenFtrClassLine = 1,
OpenFtrClassPoint=2, OpenFtrClassPoint = 2,
OpenFtrClassPolygon=4, OpenFtrClassPolygon = 4,
OpenGdb=8, OpenGdb = 8,
} }
private static void ReiniciaOutStr() private static void ReiniciaOutStr()
@ -112,8 +114,8 @@ namespace OliviaAddInPro.Helper
/** /**
* Devuelve el sistema de coordenadas de una capa * Devuelve el sistema de coordenadas de una capa
*/ */
public static int GetCoorSys(string ftclasspath) public static int GetCoorSys(string ftclasspath)
{ {
FeatureClass fc = GetFtClass(ftclasspath); FeatureClass fc = GetFtClass(ftclasspath);
if (fc == null) if (fc == null)
@ -129,23 +131,23 @@ namespace OliviaAddInPro.Helper
{ {
FeatureClass fc = null; FeatureClass fc = null;
ReiniciaOutStr(); ReiniciaOutStr();
string path = OpenFileDialog( tipo, initialLoc); string path = OpenFileDialog(tipo, initialLoc);
if(!string.IsNullOrEmpty(path)) if (!string.IsNullOrEmpty(path))
{ {
fc = GetFtClass(path); fc = GetFtClass(path);
} }
return fc; return fc;
} }
//Libera el objeto //Libera el objeto
public static void Free(IDisposable obj) public static void Free(IDisposable obj)
{ {
if(obj!=null) if (obj != null)
obj.Dispose(); obj.Dispose();
} }
//Devuelve el Path del archivo seleccionado o un string vacío si se ha cancelado //Devuelve el Path del archivo seleccionado o un string vacío si se ha cancelado
public static string OpenFileDialog(TiposOpenFileDlg tipo, string initialLoc="") public static string OpenFileDialog(TiposOpenFileDlg tipo, string initialLoc = "", string tit_ = "")
{ {
string titulo; string titulo;
ReiniciaOutStr(); ReiniciaOutStr();
@ -155,9 +157,9 @@ namespace OliviaAddInPro.Helper
//fuentes filtros //fuentes filtros
//https://github.com/Esri/arcgis-pro-sdk-community-samples/blob/master/Map-Exploration/IdentifyWindow/Daml.cs //https://github.com/Esri/arcgis-pro-sdk-community-samples/blob/master/Map-Exploration/IdentifyWindow/Daml.cs
BrowseProjectFilter filtro = new BrowseProjectFilter(); BrowseProjectFilter filtro = new BrowseProjectFilter();
if ((tipo & TiposOpenFileDlg.OpenFtrClassLine)== TiposOpenFileDlg.OpenFtrClassLine) if ((tipo & TiposOpenFileDlg.OpenFtrClassLine) == TiposOpenFileDlg.OpenFtrClassLine)
{ {
filtro.AddFilter(BrowseProjectFilter.GetFilter("esri_browseDialogFilters_featureClasses_line")); filtro.AddFilter(BrowseProjectFilter.GetFilter("esri_browseDialogFilters_featureClasses_line"));
titulo = "Abrir Feature Class"; titulo = "Abrir Feature Class";
} }
if ((tipo & TiposOpenFileDlg.OpenFtrClassPoint) == TiposOpenFileDlg.OpenFtrClassPoint) if ((tipo & TiposOpenFileDlg.OpenFtrClassPoint) == TiposOpenFileDlg.OpenFtrClassPoint)
@ -175,19 +177,24 @@ namespace OliviaAddInPro.Helper
filtro.AddFilter(BrowseProjectFilter.GetFilter("esri_browseDialogFilters_geodatabases")); filtro.AddFilter(BrowseProjectFilter.GetFilter("esri_browseDialogFilters_geodatabases"));
titulo = "Abrir Geodatabase"; titulo = "Abrir Geodatabase";
} }
if(tipo==0) if (tipo == 0)
{ {
filtro.AddFilter(BrowseProjectFilter.GetFilter("")); filtro.AddFilter(BrowseProjectFilter.GetFilter(""));
} }
if (!string.IsNullOrEmpty(tit_))
titulo = tit_;
//Display the filter in an Open Item dialog //Display the filter in an Open Item dialog
OpenItemDialog aNewFilter = new OpenItemDialog OpenItemDialog aNewFilter = new OpenItemDialog
{ {
Title = titulo, Title = titulo,
InitialLocation = initialLoc,
MultiSelect = false, MultiSelect = false,
//Set the BrowseFilter property to Pro's Geodatabase filter. //Set the BrowseFilter property to Pro's Geodatabase filter.
BrowseFilter = filtro BrowseFilter = filtro
}; };
if (!string.IsNullOrEmpty(initialLoc))
aNewFilter.InitialLocation = initialLoc;
bool? ok = aNewFilter.ShowDialog(); bool? ok = aNewFilter.ShowDialog();
if ((ok ?? true) && aNewFilter.Items.Count() > 0) if ((ok ?? true) && aNewFilter.Items.Count() > 0)
return aNewFilter.Items.First().Path; return aNewFilter.Items.First().Path;
@ -203,10 +210,10 @@ namespace OliviaAddInPro.Helper
return string.Empty; return string.Empty;
string pathGdb = string.Empty; string pathGdb = string.Empty;
int i = 0; int i = 0;
if(path.Contains(GDB_EXT)) if (path.Contains(GDB_EXT))
{ {
i = path.IndexOf(GDB_EXT, 0, path.Length); i = path.IndexOf(GDB_EXT, 0, path.Length);
pathGdb = path.Substring(0,i + 4); pathGdb = path.Substring(0, i + 4);
} }
return pathGdb; return pathGdb;
@ -221,7 +228,7 @@ namespace OliviaAddInPro.Helper
return null; return null;
ReiniciaOutStr(); ReiniciaOutStr();
return ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run((Func<Geodatabase>)(() => return ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run((Func<Geodatabase>)(() =>
{ {
string path = GetPathGdb(pathGdb); string path = GetPathGdb(pathGdb);
if (!string.IsNullOrEmpty(path)) if (!string.IsNullOrEmpty(path))
{ {
@ -260,7 +267,7 @@ namespace OliviaAddInPro.Helper
Free(gdb); Free(gdb);
return ftclss; return ftclss;
} }
//Dado el path de una gdb y el nombre de una feature class, devuelve la //Dado el path de una gdb y el nombre de una feature class, devuelve la
//feature class abierta, o null si hay algun problema //feature class abierta, o null si hay algun problema
public static Task<FeatureClass> GetFtClass(string nameFtclss, Geodatabase gdb) public static Task<FeatureClass> GetFtClass(string nameFtclss, Geodatabase gdb)
@ -296,7 +303,7 @@ namespace OliviaAddInPro.Helper
try try
{ {
string shpname = System.IO.Path.GetFileNameWithoutExtension(pathShp); string shpname = System.IO.Path.GetFileNameWithoutExtension(pathShp);
var shapeFileConnPath = new FileSystemConnectionPath(new Uri(System.IO.Path.GetDirectoryName(pathShp)), var shapeFileConnPath = new FileSystemConnectionPath(new Uri(System.IO.Path.GetDirectoryName(pathShp)),
FileSystemDatastoreType.Shapefile); FileSystemDatastoreType.Shapefile);
var shapefile = new FileSystemDatastore(shapeFileConnPath); var shapefile = new FileSystemDatastore(shapeFileConnPath);
ftclss = shapefile.OpenDataset<FeatureClass>(shpname); ftclss = shapefile.OpenDataset<FeatureClass>(shpname);
@ -316,7 +323,7 @@ namespace OliviaAddInPro.Helper
{ {
FeatureClassDefinition ftcldef = ftClss.GetDefinition(); FeatureClassDefinition ftcldef = ftClss.GetDefinition();
ReiniciaOutStr(); ReiniciaOutStr();
ArcGIS.Core.Data.Field field=null; ArcGIS.Core.Data.Field field = null;
return ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run((Func<ArcGIS.Core.Data.Field>)(() => return ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run((Func<ArcGIS.Core.Data.Field>)(() =>
{ {
try try
@ -330,13 +337,13 @@ namespace OliviaAddInPro.Helper
} }
return field; return field;
})); }));
} }
//Crea un filtro espacial a partir de una consulta y en todo caso, una geometría //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.Contains) public static ArcGIS.Core.Data.SpatialQueryFilter CreateFiler(string consulta, ArcGIS.Core.Geometry.Geometry geom, SpatialRelationship rel = SpatialRelationship.Contains)
{ {
ArcGIS.Core.Data.SpatialQueryFilter filt =null; ArcGIS.Core.Data.SpatialQueryFilter filt = null;
if (geom != null) if (geom != null)
{ {
SpatialQueryFilter filtSpat = new SpatialQueryFilter SpatialQueryFilter filtSpat = new SpatialQueryFilter
@ -361,7 +368,7 @@ namespace OliviaAddInPro.Helper
{ {
ReiniciaOutStr(); ReiniciaOutStr();
List<long> ids = new List<long>(); List<long> ids = new List<long>();
Selection sel=null; Selection sel = null;
return ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run((Func<List<long>>)(() => return ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run((Func<List<long>>)(() =>
{ {
if (fc == null) if (fc == null)
@ -372,7 +379,7 @@ namespace OliviaAddInPro.Helper
filt = new ArcGIS.Core.Data.QueryFilter(); filt = new ArcGIS.Core.Data.QueryFilter();
sel = fc.Select(filt, SelectionType.ObjectID, SelectionOption.Normal); sel = fc.Select(filt, SelectionType.ObjectID, SelectionOption.Normal);
int nsel = sel.GetCount(); int nsel = sel.GetCount();
IReadOnlyList<long> ids_= sel.GetObjectIDs(); IReadOnlyList<long> ids_ = sel.GetObjectIDs();
ids = ids_.ToList(); ids = ids_.ToList();
return ids; return ids;
} }
@ -391,8 +398,8 @@ namespace OliviaAddInPro.Helper
//Devuelve una lista con los campos de una feature class //Devuelve una lista con los campos de una feature class
public static Task<ObservableCollection<string>> GetFields(FeatureClass fc) public static Task<ObservableCollection<string>> GetFields(FeatureClass fc)
{ {
FeatureClassDefinition ftcldef=null; FeatureClassDefinition ftcldef = null;
IReadOnlyList<ArcGIS.Core.Data.Field> fields = null; IReadOnlyList<ArcGIS.Core.Data.Field> fields = null;
ReiniciaOutStr(); ReiniciaOutStr();
ObservableCollection<string> fields_st = new ObservableCollection<string>(); ObservableCollection<string> fields_st = new ObservableCollection<string>();
@ -422,7 +429,7 @@ namespace OliviaAddInPro.Helper
* Comprueba que en la capa dada exista un campo con nombre 'field' * Comprueba que en la capa dada exista un campo con nombre 'field'
*/ */
public static bool CheckField(string pathCapa, string field) public static bool CheckField(string pathCapa, string field)
{ {
FeatureClass fc = GetFtClass(pathCapa); FeatureClass fc = GetFtClass(pathCapa);
if (fc == null) if (fc == null)
{ {
@ -500,8 +507,8 @@ namespace OliviaAddInPro.Helper
return GetFieldVals(fc, fieldName, uniquevals); return GetFieldVals(fc, fieldName, uniquevals);
} }
//Dado un nombre de campo, devuelve los valores que encuentra para ese nombre de campo //Dado un nombre de campo, devuelve los valores que encuentra para ese nombre de campo
public static Task<ObservableCollection<string>> GetFieldVals(FeatureClass fc, string fieldName, bool uniquevals) public static Task<ObservableCollection<string>> GetFieldVals(FeatureClass fc, string fieldName, bool uniquevals)
{ {
ObservableCollection<string> attribs_st = new ObservableCollection<string>(); ObservableCollection<string> attribs_st = new ObservableCollection<string>();
ReiniciaOutStr(); ReiniciaOutStr();
@ -544,7 +551,7 @@ namespace OliviaAddInPro.Helper
* Devuelve una geometría que es la suma de la inicial y la que se añade Add * Devuelve una geometría que es la suma de la inicial y la que se añade Add
*/ */
public static ArcGIS.Core.Geometry.Geometry IntersectGeom(ArcGIS.Core.Geometry.Geometry geomIni, ArcGIS.Core.Geometry.Geometry geomInters, public static ArcGIS.Core.Geometry.Geometry IntersectGeom(ArcGIS.Core.Geometry.Geometry geomIni, ArcGIS.Core.Geometry.Geometry geomInters,
GeometryDimension resultDimension= GeometryDimension.esriGeometryNoDimension) GeometryDimension resultDimension = GeometryDimension.esriGeometryNoDimension)
{ {
if (geomIni == null) if (geomIni == null)
return geomInters; return geomInters;
@ -553,8 +560,8 @@ namespace OliviaAddInPro.Helper
ArcGIS.Core.Geometry.Geometry geomSal = null; ArcGIS.Core.Geometry.Geometry geomSal = null;
try try
{ {
if(resultDimension== GeometryDimension.esriGeometryNoDimension) if (resultDimension == GeometryDimension.esriGeometryNoDimension)
geomSal =GeometryEngine.Instance.Intersection(geomIni, geomInters); geomSal = GeometryEngine.Instance.Intersection(geomIni, geomInters);
else else
geomSal = GeometryEngine.Instance.Intersection(geomIni, geomInters, resultDimension); geomSal = GeometryEngine.Instance.Intersection(geomIni, geomInters, resultDimension);
@ -579,7 +586,7 @@ namespace OliviaAddInPro.Helper
try try
{ {
geomSal = GeometryEngine.Instance.Union(geomIni, geomUne); geomSal = GeometryEngine.Instance.Union(geomIni, geomUne);
return geomSal; return geomSal;
} }
catch catch
@ -620,7 +627,7 @@ namespace OliviaAddInPro.Helper
return ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run((Func<ArcGIS.Core.Geometry.Geometry>)(() => return ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run((Func<ArcGIS.Core.Geometry.Geometry>)(() =>
{ {
geomIni = GetGeomUnique(fclss, filter); geomIni = GetGeomUnique(fclss, filter);
return geomIni; return geomIni;
})); }));
} }
@ -631,7 +638,7 @@ namespace OliviaAddInPro.Helper
{ {
ArcGIS.Core.Geometry.Geometry geomsal = null; ArcGIS.Core.Geometry.Geometry geomsal = null;
ReiniciaOutStr(); ReiniciaOutStr();
try try
{ {
var geom = new List<ArcGIS.Core.Geometry.Geometry>(); var geom = new List<ArcGIS.Core.Geometry.Geometry>();
@ -643,10 +650,10 @@ namespace OliviaAddInPro.Helper
using (Row row = rowCursor.Current) using (Row row = rowCursor.Current)
{ {
if (row is Feature ft) if (row is Feature ft)
geom.Add(ft.GetShape()); geom.Add(ft.GetShape());
} }
} }
geomsal= GeometryEngine.Instance.Union(geom); geomsal = GeometryEngine.Instance.Union(geom);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -665,7 +672,7 @@ namespace OliviaAddInPro.Helper
{ {
ArcGIS.Core.Geometry.Geometry geomsal = null; ArcGIS.Core.Geometry.Geometry geomsal = null;
ArcGIS.Core.Geometry.Geometry geomAux = null; ArcGIS.Core.Geometry.Geometry geomAux = null;
string where = ""; string where = "";
ArcGIS.Core.Data.Field f; ArcGIS.Core.Data.Field f;
ArcGIS.Core.Data.QueryFilter filtro; ArcGIS.Core.Data.QueryFilter filtro;
bool ok = true; bool ok = true;
@ -685,7 +692,7 @@ namespace OliviaAddInPro.Helper
where = $"{fieldName} = {Quote(f)}{selFieldVals[i]}{Quote(f)}"; where = $"{fieldName} = {Quote(f)}{selFieldVals[i]}{Quote(f)}";
filtro = new ArcGIS.Core.Data.QueryFilter { WhereClause = where }; filtro = new ArcGIS.Core.Data.QueryFilter { WhereClause = where };
geomAux = GetGeomUnique(fclss, filtro); geomAux = GetGeomUnique(fclss, filtro);
if(geomAux == null) if (geomAux == null)
{ {
ok = false; ok = false;
continue; continue;
@ -698,7 +705,7 @@ namespace OliviaAddInPro.Helper
} }
catch (Exception ex) catch (Exception ex)
{ {
HelperGdb.OutStr = "Error al generar geometría en " + fclss.GetName() + " Con filtro " + where +": " + ex.Message; HelperGdb.OutStr = "Error al generar geometría en " + fclss.GetName() + " Con filtro " + where + ": " + ex.Message;
return geomsal; return geomsal;
} }
@ -718,8 +725,8 @@ namespace OliviaAddInPro.Helper
if (gdb != null) if (gdb != null)
{ {
fc = GetFtClass(ftclssName, gdb).Result; fc = GetFtClass(ftclssName, gdb).Result;
if(fc!=null) if (fc != null)
n= GetNumElems(fc, consulta).Result; n = GetNumElems(fc, consulta).Result;
} }
Free(fc); Free(fc);
Free(gdb); Free(gdb);
@ -729,7 +736,7 @@ namespace OliviaAddInPro.Helper
/** /**
* Devuelve los valores únicos de un campo dado * Devuelve los valores únicos de un campo dado
*/ */
public static ObservableCollection<string> GetUniqueVals(string capa, string campo) public static ObservableCollection<string> GetUniqueVals(string capa, string campo)
{ {
ObservableCollection<string> uniqueVals = null; ObservableCollection<string> uniqueVals = null;
FeatureClass ftclass = GetFtClass(capa); FeatureClass ftclass = GetFtClass(capa);
@ -742,11 +749,11 @@ namespace OliviaAddInPro.Helper
ArcGIS.Core.Data.Field fld = featureClassDefinition.GetFields().First(x => x.Name.Equals(campo)); ArcGIS.Core.Data.Field fld = featureClassDefinition.GetFields().First(x => x.Name.Equals(campo));
// Create StatisticsDescriptions // Create StatisticsDescriptions
StatisticsDescription uniqStatDesc = new StatisticsDescription(fld, new List<ArcGIS.Core.Data.StatisticsFunction>() StatisticsDescription uniqStatDesc = new StatisticsDescription(fld, new List<ArcGIS.Core.Data.StatisticsFunction>()
{ ArcGIS.Core.Data.StatisticsFunction.Count }); { ArcGIS.Core.Data.StatisticsFunction.Count });
// Create TableStatisticsDescription // Create TableStatisticsDescription
TableStatisticsDescription tableStatisticsDescription = new TableStatisticsDescription(new List<StatisticsDescription>() { uniqStatDesc}); TableStatisticsDescription tableStatisticsDescription = new TableStatisticsDescription(new List<StatisticsDescription>() { uniqStatDesc });
tableStatisticsDescription.GroupBy = new List<ArcGIS.Core.Data.Field>() { fld }; tableStatisticsDescription.GroupBy = new List<ArcGIS.Core.Data.Field>() { fld };
tableStatisticsDescription.OrderBy = new List<SortDescription>() { new SortDescription(fld) }; tableStatisticsDescription.OrderBy = new List<SortDescription>() { new SortDescription(fld) };
@ -756,7 +763,7 @@ namespace OliviaAddInPro.Helper
// Code to process results goes here... // Code to process results goes here...
uniqueVals = new ObservableCollection<string>(); uniqueVals = new ObservableCollection<string>();
for(int i=0; i< statRes.StatisticsResults.Count; i++) for (int i = 0; i < statRes.StatisticsResults.Count; i++)
{ {
uniqueVals.Add(statRes.StatisticsResults.ElementAt(i).ToString()); uniqueVals.Add(statRes.StatisticsResults.ElementAt(i).ToString());
} }
@ -804,7 +811,7 @@ namespace OliviaAddInPro.Helper
public static int GetNumElems(string pathFtClss, string consulta = "") public static int GetNumElems(string pathFtClss, string consulta = "")
{ {
FeatureClass fc = GetFtClass(pathFtClss); FeatureClass fc = GetFtClass(pathFtClss);
int n=GetNumElems(fc,consulta).Result; int n = GetNumElems(fc, consulta).Result;
Free(fc); Free(fc);
return n; return n;
} }
@ -815,13 +822,13 @@ namespace OliviaAddInPro.Helper
string name = System.IO.Path.GetFileName(path); string name = System.IO.Path.GetFileName(path);
if (!string.IsNullOrEmpty(old_ext)) if (!string.IsNullOrEmpty(old_ext))
name.Replace(old_ext,""); name.Replace(old_ext, "");
string _ex =System.IO.Path.GetExtension(nameNew); string _ex = System.IO.Path.GetExtension(nameNew);
string nn = nameNew; string nn = nameNew;
if (!string.IsNullOrEmpty(_ex)) if (!string.IsNullOrEmpty(_ex))
nn=nn.Replace(_ex, ""); nn = nn.Replace(_ex, "");
var res = true; var res = true;
foreach(var ex in extensions) foreach (var ex in extensions)
{ {
try try
{ {
@ -830,9 +837,9 @@ namespace OliviaAddInPro.Helper
if (!File.Exists(po)) if (!File.Exists(po))
res = false;//no existe res = false;//no existe
if (File.Exists(pn)) if (File.Exists(pn))
File.Delete(pn); File.Delete(pn);
File.Move(po,pn ); File.Move(po, pn);
} }
catch catch
{ {
@ -843,7 +850,7 @@ namespace OliviaAddInPro.Helper
return res; return res;
} }
public static bool ExportShp2(string pathLayerIn, SpatialQueryFilter filter, string nameShp, string outpath, IprocessManager cps, ArcGIS.Core.Geometry.SpatialReference sr=null, int incmax=100 ) public static bool ExportShp2(string pathLayerIn, SpatialQueryFilter filter, string nameShp, string outpath, IprocessManager cps, ArcGIS.Core.Geometry.SpatialReference sr = null, int incmax = 100)
{ {
if (!System.IO.Directory.Exists(outpath)) if (!System.IO.Directory.Exists(outpath))
System.IO.Directory.CreateDirectory(outpath); System.IO.Directory.CreateDirectory(outpath);
@ -860,7 +867,7 @@ namespace OliviaAddInPro.Helper
return false; return false;
} }
List<long> ids = new List<long>(); List<long> ids = new List<long>();
//Añade a la lista los ids que cumplen el filtro espacial //Añade a la lista los ids que cumplen el filtro espacial
using (RowCursor cursor = fc.Search(filter)) using (RowCursor cursor = fc.Search(filter))
{ {
@ -885,9 +892,9 @@ namespace OliviaAddInPro.Helper
///Exporta ///Exporta
string[] args = { pathLayerIn, outpath, nameShp, whereClause }; string[] args = { pathLayerIn, outpath, nameShp, whereClause };
// execute the tool // execute the tool
if(sr==null) if (sr == null)
{ {
sr= fc.GetDefinition().GetSpatialReference(); sr = fc.GetDefinition().GetSpatialReference();
} }
var environments = Geoprocessing.MakeEnvironmentArray(outputCoordinateSystem: sr); var environments = Geoprocessing.MakeEnvironmentArray(outputCoordinateSystem: sr);
//SpatialReferenceBuilder.CreateSpatialReference(3857) //SpatialReferenceBuilder.CreateSpatialReference(3857)
@ -907,7 +914,7 @@ namespace OliviaAddInPro.Helper
case "OnProgressMessage": case "OnProgressMessage":
{ {
string msg = string.Format("{0}: {1}", new object[] { event_name, (string)o }); string msg = string.Format("{0}: {1}", new object[] { event_name, (string)o });
Debug.WriteLine(msg); ; Debug.WriteLine(msg); ;
} }
break; break;
@ -915,11 +922,11 @@ namespace OliviaAddInPro.Helper
{ {
string msg2 = string.Format("{0}: {1} %", new object[] { event_name, (int)o }); string msg2 = string.Format("{0}: {1} %", new object[] { event_name, (int)o });
Debug.WriteLine(msg2); Debug.WriteLine(msg2);
var av = (int)o; var av = (int)o;
if (av > 0) if (av > 0)
{ {
cps.SetProgress(valini + (Math.Min((double)av/100.0, 100.0)*Math.Min(incmax, 100-valini))); cps.SetProgress(valini + (Math.Min((double)av / 100.0, 100.0) * Math.Min(incmax, 100 - valini)));
} }
// if ((int)o < 0) // if ((int)o < 0)
//System.Windows.MessageBox.Show(msg2); //System.Windows.MessageBox.Show(msg2);
//_cts.Cancel(); //_cts.Cancel();
@ -933,7 +940,7 @@ namespace OliviaAddInPro.Helper
cps.Setcancelled(); cps.Setcancelled();
return false; return false;
} }
if(gpResult.IsFailed) if (gpResult.IsFailed)
{ {
string msg; string msg;
if (gpResult.ErrorMessages != null) if (gpResult.ErrorMessages != null)
@ -957,12 +964,12 @@ namespace OliviaAddInPro.Helper
} }
public static bool ExportShp(string pathLayerIn, SpatialQueryFilter filter, string nameShp, string outpath, CancelableProgressorSource cps, out string msgOut, ProgressorSource progrDialog = null) public static bool ExportShp(string pathLayerIn, SpatialQueryFilter filter, string nameShp, string outpath, CancelableProgressorSource cps, out string msgOut, ProgressorSource progrDialog = null)
{ {
msgOut = ""; msgOut = "";
if (!System.IO.Directory.Exists(outpath)) if (!System.IO.Directory.Exists(outpath))
System.IO.Directory.CreateDirectory(outpath); System.IO.Directory.CreateDirectory(outpath);
//fc. //fc.
/* /*
@ -1026,7 +1033,7 @@ namespace OliviaAddInPro.Helper
*/ */
cps.Status = "Guardando geometria a shp"; cps.Status = "Guardando geometria a shp";
string[] args = { pathLayerIn, outpath }; string[] args = { pathLayerIn, outpath };
// execute the tool // execute the tool
IGPResult gpResult = Geoprocessing.ExecuteToolAsync("FeatureClassToShapefile_conversion", args, IGPResult gpResult = Geoprocessing.ExecuteToolAsync("FeatureClassToShapefile_conversion", args,
@ -1037,8 +1044,8 @@ namespace OliviaAddInPro.Helper
switch (event_name) switch (event_name)
{ {
case "OnValidate": // stop execute if any warnings case "OnValidate": // stop execute if any warnings
//if ((o as IGPMessage[]).Any(it => it.Type == GPMessageType.Warning)) //if ((o as IGPMessage[]).Any(it => it.Type == GPMessageType.Warning))
//_cts.Cancel(); //_cts.Cancel();
break; break;
case "OnProgressMessage": case "OnProgressMessage":
@ -1046,8 +1053,8 @@ namespace OliviaAddInPro.Helper
string msg = string.Format("{0}: {1}", new object[] { event_name, (string)o }); string msg = string.Format("{0}: {1}", new object[] { event_name, (string)o });
//progrDialog.Message = (string)o; //progrDialog.Message = (string)o;
Debug.WriteLine(msg); Debug.WriteLine(msg);
; ;
//System.Windows.MessageBox.Show(msg); //System.Windows.MessageBox.Show(msg);
//_cts.Cancel(); //_cts.Cancel();
} }
@ -1092,9 +1099,9 @@ namespace OliviaAddInPro.Helper
/** /**
* Comprueba si un punto está contenido en un polígono * Comprueba si un punto está contenido en un polígono
*/ */
public static Respuesta<bool> IsPtoInGeom(Coordinate2D pto, ArcGIS.Core.Geometry.Geometry geom) public static Respuesta<bool> IsPtoInGeom(Coordinate2D pto, ArcGIS.Core.Geometry.Geometry geom)
{ {
Respuesta<bool> resp=new Respuesta<bool>(); Respuesta<bool> resp = new Respuesta<bool>();
try try
{ {
ArcGIS.Core.Geometry.Geometry geom_convexhull = GeometryEngine.Instance.ConvexHull(geom); ArcGIS.Core.Geometry.Geometry geom_convexhull = GeometryEngine.Instance.ConvexHull(geom);
@ -1104,7 +1111,7 @@ namespace OliviaAddInPro.Helper
return resp; return resp;
} }
catch catch
{ {
resp.Value = false; resp.Value = false;
resp.Error.Add("Error al comprobar si punto está contenido en polígono"); resp.Error.Add("Error al comprobar si punto está contenido en polígono");
return resp; return resp;
@ -1113,7 +1120,7 @@ namespace OliviaAddInPro.Helper
/** /**
* Amplía la geometría para añadirele buffer * Amplía la geometría para añadirele buffer
*/ */
public static Respuesta<ArcGIS.Core.Geometry.Geometry> BufferGeom(ArcGIS.Core.Geometry.Geometry geom, double buffer) public static Respuesta<ArcGIS.Core.Geometry.Geometry> BufferGeom(ArcGIS.Core.Geometry.Geometry geom, double buffer)
{ {
Respuesta<ArcGIS.Core.Geometry.Geometry> resp = new Respuesta<ArcGIS.Core.Geometry.Geometry>(); Respuesta<ArcGIS.Core.Geometry.Geometry> resp = new Respuesta<ArcGIS.Core.Geometry.Geometry>();
ArcGIS.Core.Geometry.Geometry geomBuff = null; ArcGIS.Core.Geometry.Geometry geomBuff = null;
@ -1143,14 +1150,14 @@ namespace OliviaAddInPro.Helper
{ {
buffer += 100; buffer += 100;
geom_pto = GeometryEngine.Instance.Buffer(pto.ToMapPoint(), buffer); geom_pto = GeometryEngine.Instance.Buffer(pto.ToMapPoint(), buffer);
if(geom_pto==null || geom_pto.IsEmpty) if (geom_pto == null || geom_pto.IsEmpty)
{ {
resp.Value = null; resp.Value = null;
resp.Error.Add("Error al bufferear punto para incluirlo en polígono"); resp.Error.Add("Error al bufferear punto para incluirlo en polígono");
return resp; return resp;
} }
//hace la convex hull, por si no fueran conexas las zonas //hace la convex hull, por si no fueran conexas las zonas
repite= GeometryEngine.Instance.Disjoint(geom_pto, geom); repite = GeometryEngine.Instance.Disjoint(geom_pto, geom);
/*if (geom_aux == null || geom_aux.IsEmpty) /*if (geom_aux == null || geom_aux.IsEmpty)
{ {
ArcGIS.Core.Geometry.Envelope env1 = geom_sal.Extent; ArcGIS.Core.Geometry.Envelope env1 = geom_sal.Extent;
@ -1241,8 +1248,9 @@ namespace OliviaAddInPro.Helper
string message = String.Empty; string message = String.Empty;
bool deletionResult = false; bool deletionResult = false;
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
EditOperation editOperation = new EditOperation(); EditOperation editOperation = new EditOperation();
editOperation.Callback(context => editOperation.Callback(context =>
{ {
@ -1275,7 +1283,7 @@ namespace OliviaAddInPro.Helper
{ {
message = exObj.Message; message = exObj.Message;
} }
}); });
if (!string.IsNullOrEmpty(message)) if (!string.IsNullOrEmpty(message))
@ -1364,7 +1372,7 @@ namespace OliviaAddInPro.Helper
double longi_zon = 0, longi_tot = 0; double longi_zon = 0, longi_tot = 0;
List<long> quita = new List<long>(); List<long> quita = new List<long>();
int j=0; int j = 0;
List<long> ids; List<long> ids;
try try
{ {
@ -1372,14 +1380,14 @@ namespace OliviaAddInPro.Helper
ids = GetIds(fc, null).Result; ids = GetIds(fc, null).Result;
//Recorre las features de la capa //Recorre las features de la capa
RowCursor cursor = fc.Search(); RowCursor cursor = fc.Search();
while(cursor.MoveNext()) while (cursor.MoveNext())
{ {
f = (Feature)cursor.Current; f = (Feature)cursor.Current;
geom = f.GetShape(); geom = f.GetShape();
line = (ArcGIS.Core.Geometry.Polyline)geom; line = (ArcGIS.Core.Geometry.Polyline)geom;
longi_tot = line.Length; longi_tot = line.Length;
geom= IntersectGeom(geom_zon, line,GeometryDimension.esriGeometry1Dimension); geom = IntersectGeom(geom_zon, line, GeometryDimension.esriGeometry1Dimension);
line =(ArcGIS.Core.Geometry.Polyline)geom; line = (ArcGIS.Core.Geometry.Polyline)geom;
longi_zon = line.Length;//se consigue la longitud de ámbito (linea) que interseca con el nivel) longi_zon = line.Length;//se consigue la longitud de ámbito (linea) que interseca con el nivel)
if ((longi_zon / longi_tot) < porc) if ((longi_zon / longi_tot) < porc)
{ {
@ -1393,7 +1401,7 @@ namespace OliviaAddInPro.Helper
Free(cursor); Free(cursor);
//comprueba que no se haya quedado sin ámbitos //comprueba que no se haya quedado sin ámbitos
if (quita.Count>=fc.GetCount()) if (quita.Count >= fc.GetCount())
{ {
OutStr = "No quedan ámbitos que cumplan la geometría seleccionada."; OutStr = "No quedan ámbitos que cumplan la geometría seleccionada.";
return false; return false;
@ -1418,12 +1426,12 @@ namespace OliviaAddInPro.Helper
HelperGdb.Free(fc); HelperGdb.Free(fc);
HelperGdb.Free(f); HelperGdb.Free(f);
} }
} }
/** /**
* Dado un nombre de capa mira si está abierta y la cierra * Dado un nombre de capa mira si está abierta y la cierra
*/ */
public static bool CloseLayer(string nombCapa) public static bool CloseLayer(string nombCapa)
{ {
try try
@ -1440,5 +1448,30 @@ namespace OliviaAddInPro.Helper
} }
} }
/**
* Saca diálogo para guardar un archivo
*/
public static string SaveFileDlg(string title_, string initloc_, string ext_, string filt_)
{
//Display the filter in an Open Item dialog
SaveItemDialog dlg = new SaveItemDialog
{
Title = title_,
OverwritePrompt = true,
};
if (!string.IsNullOrEmpty(initloc_))
dlg.InitialLocation = initloc_;
if (!string.IsNullOrEmpty(filt_))
dlg.Filter = filt_;
if (!string.IsNullOrEmpty(ext_))
dlg.DefaultExt = ext_;
bool? ok = dlg.ShowDialog();
if ((ok ?? true) && dlg.FilePath.Length > 0)
return dlg.FilePath;
else
return string.Empty;
}
} }
} }

View File

@ -36,7 +36,17 @@ namespace OliviaAddInPro.Model
* Instancia para las funciones de exportación y demás * Instancia para las funciones de exportación y demás
*/ */
public LimpiezaServ Serv { get; set; } = null; public LimpiezaServ Serv
{
get
{
return (LimpiezaServ)ServCom;
}
set
{
ServCom = value;
}
}
public LanzaLimpSrv LanzaSrv { get; set; } = null; public LanzaLimpSrv LanzaSrv { get; set; } = null;
/** /**
@ -46,9 +56,7 @@ namespace OliviaAddInPro.Model
public Limpieza() public Limpieza()
{ {
Serv = new LimpiezaServ(this); Serv = new LimpiezaServ(this);
LanzaSrv = new LanzaLimpSrv(); LanzaSrv = new LanzaLimpSrv();
ProceSrv = new ProcesoEjecServ();
ProgrSrc = new MyCancelableProgressorSource(OliviaGlob.progrDialog.GetViewModel());
} }
public override Respuesta<TiposEjecucion> Ejecuta(ModosEjec modo) public override Respuesta<TiposEjecucion> Ejecuta(ModosEjec modo)
@ -73,5 +81,55 @@ namespace OliviaAddInPro.Model
} }
return res2; return res2;
} }
/**
* Descodifica el nombre del sahpefile de entrada identificando el tipo de tratamiento y los ámbitos de trabajo
*/
public override void decode_gdb(string shapefile, out string tratamiento, out string ambitos)
{
int aux, auxl, mbito, indice, tratamient;
string auxili, ambi, auxi;
indice = shapefile.IndexOf("_");
indice = indice + 2;//para saltarse la T que va antes del identificador del tipo de tratamiento
auxili = shapefile.Substring(indice, 2);
tratamient = Convert.ToInt32(auxili);
tratamiento = LimpiezaDef.tto_gdb[tratamient];
indice = shapefile.IndexOf("_", indice);
indice = indice + 2;//para saltarse la A que va antes del identificador de los ámbitos que intervienen
aux = shapefile.IndexOf("_", indice);
auxl = aux - indice;
auxi = "";
while (auxl > 0)
{
ambi = shapefile.Substring(indice, 2);
mbito = Convert.ToInt32(ambi);
indice = indice + 2;
auxl = auxl - 2;
if (auxl != 0)
auxi = auxi + LimpiezaDef.ambs_gdb[mbito] + "_";
else
auxi = auxi + LimpiezaDef.ambs_gdb[mbito];
}
ambitos = LimpiezaDef.preftto_gdb[tratamient] + "_" + auxi;
//quita los espacios
tratamiento = tratamiento.Replace(" ", "_");
ambitos = ambitos.Replace(" ", "_");
auxi = shapefile;
//para poner la zona cuando es seleccionada
for (int i = 0; i < 2; i++)
{
indice = auxi.LastIndexOf("_");
auxi = auxi.Substring(0, indice);
}
auxl = indice - aux;
if (auxl <= 0)
return;
auxili = shapefile.Substring(aux, auxl);
ambitos = ambitos + auxili;
}
} }
} }

View File

@ -100,7 +100,6 @@ namespace OliviaAddInPro.Model
get { return reco; } get { return reco; }
set { reco = value; } set { reco = value; }
} }
public static EjecServ Serv { get; } = new EjecServ();
public static SpatialReference SpatRef { get; set; } = null; public static SpatialReference SpatRef { get; set; } = null;
public static MarchandoUnaDe progrDialog { get; set; } = null; public static MarchandoUnaDe progrDialog { get; set; } = null;
#endregion Properties #endregion Properties

View File

@ -69,12 +69,22 @@ namespace OliviaAddInPro.Model
get; get;
set; set;
} }
public RecogidaServ Serv { get; set; } = null; public RecogidaServ Serv
{
get
{
return (RecogidaServ)ServCom;
}
set
{
ServCom = value;
}
}
public LanzaRecoSrv LanzaSrv { get; set; } = null; public LanzaRecoSrv LanzaSrv { get; set; } = null;
public Recogida() public Recogida()
{ {
Serv = new RecogidaServ(this); Serv = new RecogidaServ(this);
LanzaSrv = new LanzaRecoSrv(); LanzaSrv = new LanzaRecoSrv();
} }
public override Respuesta<TiposEjecucion> Ejecuta(ModosEjec modo) public override Respuesta<TiposEjecucion> Ejecuta(ModosEjec modo)
@ -99,5 +109,48 @@ namespace OliviaAddInPro.Model
} }
return res2; return res2;
} }
/**
* Descodifica el nombre del sahpefile de entrada identificando el tipo de fracción y la carga para la recogida de residuos
*/
public override void decode_gdb(string shapefile, out string fraccion, out string carga)
{
int aux, auxl, carg, indice, fracc;
string auxili, fra, auxi;
indice = shapefile.IndexOf("_");
indice = indice + 2;//para saltarse la F que va antes del identificador del tipo de fracción
auxili = shapefile.Substring(indice, 2);
fracc = Convert.ToInt32(auxili);
fraccion = RecogidaDef.tipos_fracc_str[fracc];
indice = shapefile.IndexOf("_", indice);
indice = indice + 2;//para saltarse la C que va antes del identificador de los tipos de carga de los vehículos
aux = shapefile.IndexOf("_", indice);
auxi = "";
fra = shapefile.Substring(indice, 2);
carg = Convert.ToInt32(fra);
carga = RecogidaDef.tipos_fracc_str[fracc] + "_" + RecogidaDef.tipos_carg_str[carg];
//quita los espacios
fraccion = fraccion.Replace(" ", "_");
carga = carga.Replace(" ", "_");
////////////////////////
auxi = shapefile;
for (int i = 0; i < 2; i++)
{
indice = auxi.LastIndexOf("_");
auxi = auxi.Substring(0, indice);
}
auxl = indice - aux;
if (auxl <= 0)
return;
auxili = shapefile.Substring(aux, auxl);
carga = carga + auxili;
}
} }
} }

View File

@ -136,6 +136,7 @@ namespace OliviaAddInPro.Model
public MyCancelableProgressorSource ProgrSrc { get; set; } = null; public MyCancelableProgressorSource ProgrSrc { get; set; } = null;
public ProcesoEjecServ ProceSrv { get; set; } = null; public ProcesoEjecServ ProceSrv { get; set; } = null;
public FinProcServ FinProceSrv { get; set; } = null; public FinProcServ FinProceSrv { get; set; } = null;
public EjecServ ServCom { get; set; } = null;
public TratamientoComun() public TratamientoComun()
{ {
@ -151,15 +152,15 @@ namespace OliviaAddInPro.Model
//oculta la ventana //oculta la ventana
OliviaGlob.ShowHidePane(false); OliviaGlob.ShowHidePane(false);
//comienza ejecución //comienza ejecución
Action<Respuesta<TiposEjecucion>> ac = FinProceSrv.finEjecuta; Action<Respuesta<TiposEjecucion>, TratamientoComun> ac = FinProceSrv.finEjecuta;
EjecutaAsync(modo, ac); EjecutaAsync(modo, ac);
} }
public async void EjecutaAsync(ModosEjec modo, Action<Respuesta<TiposEjecucion>> ffin) public async void EjecutaAsync(ModosEjec modo, Action<Respuesta<TiposEjecucion>, TratamientoComun> ffin)
{ {
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{ {
var res = Ejecuta(modo); var res = Ejecuta(modo);
ffin(res); ffin(res, this);
return res; return res;
}); });
@ -170,5 +171,14 @@ namespace OliviaAddInPro.Model
res.Error.Add("No implementado"); res.Error.Add("No implementado");
return res; return res;
} }
/**
* Descodifica el nombre del sahpefile de entrada identificando el tipo de tratamiento y los ámbitos de trabajo
*/
public virtual void decode_gdb(string shapefile, out string tratamiento, out string ambitos)
{
tratamiento = string.Empty;
ambitos = string.Empty;
}
} }
} }

View File

@ -72,15 +72,7 @@ namespace OliviaAddInPro.Services
} }
//mira spatialreference de los datos de entrada //mira spatialreference de los datos de entrada
spatRefData = geom_export.SpatialReference; spatRefData = geom_export.SpatialReference;
//AQUÍ COMPARAR SI ES IGUAL QUE SPATREFDEF Y SI NO, REPROYECTAR
/*if(spatRef.Wkid!=GeneralDef.SpatRefDef)
{
/*
* FALTA HACER
* dame_geom_coords en v2010
*/
//}
//crea el filtro de exportación //crea el filtro de exportación
filtroEspacial = HelperGdb.CreateFiler(com.ConsultaAmbs, geom_export); filtroEspacial = HelperGdb.CreateFiler(com.ConsultaAmbs, geom_export);
@ -204,8 +196,7 @@ namespace OliviaAddInPro.Services
} }
//mira spatialreference del nw //mira spatialreference del nw
FeatureClass fc = HelperGdb.GetFtClass(OliviaGlob.Paths.PathGdbNw); /*FeatureClass fc = HelperGdb.GetFtClass(OliviaGlob.Paths.PathGdbNw);
/*
if (fc != null) if (fc != null)
{ {
spatRef = fc.GetDefinition().GetSpatialReference(); spatRef = fc.GetDefinition().GetSpatialReference();
@ -367,6 +358,52 @@ namespace OliviaAddInPro.Services
return false; return false;
} }
/**
* Realiza las funciones de importación de la sectorización
*/
public Respuesta<bool> ImportSecto(string GdbFileName)
{
var res = new Respuesta<bool> { Value = false };
/*
try
{
//temp
string name;
res = import_secto_fin(GdbFileName, out name);
if (!res.Value)
{
res.Error.Add("Error al importar resultados.");
return res;
}
res = pinta_sectores(GdbFileName, name, 4);
if (!res.Value)
{
res.Error.Add("Error al pintar sectores.");
return res;
}
}
catch (Exception)
{
res.Error.Add("Se ha cancelado la importación de resultados.");
return res;
}
res.Value = true;
return res;*/
return res;
}
/**
* Realiza las funciones de importación de la planificación
*/
public Respuesta<bool> ImportPlanif(string GdbFileName)
{
var res = new Respuesta<bool> { Value = false };
return res;
}
} }
} }

View File

@ -12,8 +12,9 @@ namespace OliviaAddInPro.Services
{ {
public class FinProcServ public class FinProcServ
{ {
public void finEjecuta(Respuesta<TiposEjecucion> res) public void finEjecuta(Respuesta<TiposEjecucion> res, TratamientoComun inst)
{ {
//REVISAR CUANDO ACABA, SE CAMBIE EL MARCHANDO PARA QUE SE LE DE A FINALIZAR Y TERMINA OK
String msg=string.Empty; String msg=string.Empty;
//gestiona los flags, el estado de finok o finnok va en res.Vale //gestiona los flags, el estado de finok o finnok va en res.Vale
@ -24,51 +25,50 @@ namespace OliviaAddInPro.Services
OliviaGlob.RemoveFlagTipEjec(TiposEjecucion.FinEjecNOk); OliviaGlob.RemoveFlagTipEjec(TiposEjecucion.FinEjecNOk);
} }
else else
{ {
msg = Resource1.String_exito;
bool todoOk = true;
//importa resultados
if (OliviaGlob.HasFlagTipEjec(TiposEjecucion.EjecSecto)) //Ha terminado bien la sectorización
{
/*if (!gdb.import_secto_ini())
{
todoOk=false;
msg = msg + " " + gdb.err_st;
}*/
}
else if (OliviaGlob.HasFlagTipEjec(TiposEjecucion.EjecPlanif)) //Ha terminado bien la planificación
{
/*guarda_csv();
if (!gdb.import_planif())
{
todoOk=false;
msg = msg + " " + gdb.err_st;
}*/
}
//actualiza los flags //actualiza los flags
OliviaGlob.RemoveFlagTipEjec(TiposEjecucion.FinEjecOk); OliviaGlob.RemoveFlagTipEjec(TiposEjecucion.FinEjecOk);
if (todoOk) //importa resultados
var resp = IniImport();
if (resp.HasError)
msg = resp.Error.First();
else
{ {
//pone modo config2 string GdbFileName = resp.Value;
OliviaGlob.AddFlagTipEjec(TiposEjecucion.Config2); var resp2 = new Respuesta<bool> { Value=false};
if (OliviaGlob.HasFlagTipEjec(TiposEjecucion.EjecSecto)) //Ha terminado bien la sectorización
{
resp2 = inst.ServCom.ImportSecto(GdbFileName);
}
else if (OliviaGlob.HasFlagTipEjec(TiposEjecucion.EjecPlanif)) //Ha terminado bien la planificación
{
GuardaCsv(inst);
resp2 = inst.ServCom.ImportPlanif(GdbFileName);
}
if (!resp2.Value)
{
msg = resp2.Error.First();
}
else
{
msg = Resource1.String_exito;
//pone modo config2
OliviaGlob.AddFlagTipEjec(TiposEjecucion.Config2);
}
} }
} }
//borra los archivos que le toca borrar //borra los archivos que le toca borrar
BorraFiles(); BorraFiles();
HelperGlobal.ponMsg(msg); HelperGlobal.ponMsg(msg);
Application.Current.Dispatcher.Invoke(new Action(() => { finEjecuta2(); })); Application.Current.Dispatcher.Invoke(new Action(() => { finEjecuta2(); }));
} }
public void finEjecuta2() public void finEjecuta2()
{ {
OliviaGlob.progrDialog.Hide(); OliviaGlob.progrDialog.Hide();
//muestra la ventana //muestra la ventana
OliviaGlob.ShowHidePane(true); OliviaGlob.ShowHidePane(true);
} }
/** /**
* Borra los archivos exportados para el proceso * Borra los archivos exportados para el proceso
@ -113,5 +113,69 @@ namespace OliviaAddInPro.Services
MessageBox.Show(ex.Message); MessageBox.Show(ex.Message);
} }
} }
public static string NAME_CSV = "_L";
public static string EXT_CSV = ".csv";
/*
* Permite guardar el archivo CSV que contiene la secuencia que se ha llevado a cabo en las rutas en la planificación.
*/
public static void GuardaCsv(TratamientoComun inst)
{
string auxi, nombre = null;
string[] nameDokL;
string DirData = System.IO.Path.GetDirectoryName(OliviaGlob.Paths.PathData);
nameDokL = Directory.GetFiles(DirData,
System.IO.Path.GetFileNameWithoutExtension(OliviaGlob.Paths.PathData) + NAME_CSV + ".*");
string Title = "Guardar Secuencia de la Planificación";
string Filter = "Secuencia en formato CSV (*.csv)|*.csv";
inst.decode_gdb(System.IO.Path.GetFileNameWithoutExtension(OliviaGlob.Paths.PathData),
out auxi, out nombre);
string InitialDirectory = System.IO.Path.Combine(DirData, nombre);
string FileName = HelperGdb.SaveFileDlg(Title, InitialDirectory, EXT_CSV, Filter);
if (string.IsNullOrEmpty(FileName) || FileName.Length == 0)
{
bool ok = HelperGlobal.ponMsg("Se va a perder el archivo que contiene la secuencia en planificación, ¿está seguro?",
MessageBoxImage.Question,"OLIVIA",MessageBoxButton.YesNo);
if (!ok)
GuardaCsv(inst);
}
else
{
if (File.Exists(FileName))
File.Delete(FileName);
File.Move(nameDokL[0], FileName);
}
}
/*
* Inicializa la importación
*/
public Respuesta<string> IniImport()
{
var res = new Respuesta<string>() { Value = string.Empty };
//Lanza ventana para elegir gdb a la que importar resultados
bool sal = true;
string GdbFileName="";
do
{
sal = true;
//repite por si se ha equivocado hasta que elige la gdb
GdbFileName = HelperGdb.OpenFileDialog(HelperGdb.TiposOpenFileDlg.OpenGdb,"", "Seleccionar GDB a la que importar los resultados");
if(string.IsNullOrEmpty(GdbFileName))
sal= HelperGlobal.ponMsg("¿Desea cancelar el proceso de imporación?",
MessageBoxImage.Question, "OLIVIA", MessageBoxButton.YesNo);
} while (!sal);
if (string.IsNullOrEmpty(GdbFileName) || !Directory.Exists(GdbFileName))
{
res.Error.Add("Se ha cancelado la importación de resultados.");
return res;
}
res.Value = GdbFileName;
return res;
}
} }
} }

View File

@ -208,5 +208,6 @@ namespace OliviaAddInPro.Services
} }
return amb_com; return amb_com;
} }
} }
} }