public bool AddFavorite(string name, string path, Image image) { try { RemoveFavorite(name, path); FileInfo fi = new FileInfo(ConfigPath); XmlStream stream = new XmlStream("Favorites"); FavoriteList favList = new FavoriteList(); if (fi.Exists) { stream.ReadStream(fi.FullName); favList = (FavoriteList)stream.Load("favlist", null, favList); if (favList == null) { favList = new FavoriteList(); } } favList.Add(new Favorite(name, path, image)); stream = new XmlStream("Favorites"); stream.Save("favlist", favList); stream.WriteStream(fi.FullName); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error - Add Favorite"); } return(false); }
public bool RemoveFavorite(string name, string path) { try { FileInfo fi = new FileInfo(ConfigPath); if (!fi.Exists) { return(false); } XmlStream stream = new XmlStream("Favorites"); stream.ReadStream(fi.FullName); FavoriteList favList = (FavoriteList)stream.Load("favlist", null, new FavoriteList()); if (favList == null) { return(false); } favList.Remove(name, path); stream = new XmlStream("Favorites"); stream.Save("favlist", favList); stream.WriteStream(fi.FullName); return(true); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error - Remove Favorite"); } return(false); }
static private void Load() { try { _loaded = true; XmlStream stream = new XmlStream("localcaching"); if (!stream.ReadStream(SystemVariables.CommonApplicationData + @"\options_tilecache_local_caching.xml")) { stream = new XmlStream("localcaching"); stream.Save("use", (bool)true); stream.Save("folder", SystemVariables.CommonApplicationData + @"\temp\tilecache"); stream.WriteStream(SystemVariables.CommonApplicationData + @"\options_tilecache_local_caching.xml"); stream = new XmlStream("webproxy"); stream.ReadStream(SystemVariables.CommonApplicationData + @"\options_tilecache_local_caching.xml"); } _use = (bool)stream.Load("use", (bool)true); _folder = (string)stream.Load("folder", SystemVariables.CommonApplicationData + @"\temp\tilecache"); } catch (Exception ex) { _loaded = false; } }
public bool LoadMapDocument(string path) { XmlStream stream = new XmlStream(""); if (stream.ReadStream(path)) { while (_maps.Count > 0) { this.RemoveMap((IMap)_maps[0]); } stream.Load("MapDocument", null, this); if (_maps.Count > 0) { FocusMap = _maps[0]; } else { FocusMap = null; } return(true); } return(false); }
async public override Task <bool> Refresh() { try { await base.Refresh(); _mapDocument = new MapDocument(); XmlStream stream = new XmlStream(""); stream.ReadStream(_filename); //_mapDocument.LoadMapDocument(_filename); await stream.LoadAsync("MapDocument", _mapDocument); foreach (IMap map in _mapDocument.Maps) { base.AddChildObject(new MapExplorerObject(this, _filename, map)); } return(true); } catch (Exception ex) { string errMsg = ex.Message; return(false); } }
public void FromXmlString(string xml) { XmlStream stream = new XmlStream("EventTableConnection"); StringReader sr = new StringReader(xml); stream.ReadStream(sr); Load(stream); }
public void FromXmlString(string xml) { XmlStream stream = new XmlStream("SpatialReference"); StringReader sr = new StringReader(xml); stream.ReadStream(sr); this.Load(stream); }
public void FromString(string connection) { XmlStream stream = new XmlStream("DbConnectionString"); StringReader sr = new StringReader(connection); stream.ReadStream(sr); Load(stream); }
async public Task <bool> SetMetadata(string mapName, string metadata, string usr, string pwd) { await _accessControlService.CheckPublishAccess(mapName.FolderName(), usr, pwd); FileInfo fi = new FileInfo(_mapServerService.Options.ServicesPath + @"/" + mapName + ".meta"); StringReader sr = new StringReader(metadata); XmlStream xmlStream = new XmlStream(""); xmlStream.ReadStream(sr); xmlStream.WriteStream(fi.FullName); return(await ReloadMap(mapName, usr, pwd)); }
async private Task ApplyMetadata(Map map) { try { if (map == null) { return; } FileInfo fi = new FileInfo(_mapServerService.Options.ServicesPath + @"/" + map.Name + ".meta"); IEnumerable <IMapApplicationModule> modules = null; if (MapDocument is IMapDocumentModules) { modules = ((IMapDocumentModules)MapDocument).GetMapModules(map); } IServiceMap sMap = await ServiceMap.CreateAsync(map, _mapServerService.Instance, modules); XmlStream xmlStream; // 1. Bestehende Metadaten auf sds anwenden if (fi.Exists) { xmlStream = new XmlStream(""); xmlStream.ReadStream(fi.FullName); sMap.ReadMetadata(xmlStream); } // 2. Metadaten neu schreiben... xmlStream = new XmlStream("Metadata"); await sMap.WriteMetadata(xmlStream); if (map is Metadata) { await map.SetMetadataProviders(await sMap.GetMetadataProviders(), map, true); await map.UpdateMetadataProviders(); } // Overriding: no good idea -> problem, if multiple instances do this -> killing the metadata file!!! //fi.Refresh(); //if (!fi.Exists) //{ // xmlStream.WriteStream(fi.FullName); //} } catch (Exception ex) { _logger.LogError($"Map { map.Name }: ApplyMetadata - { ex.Message }"); } }
public static IGraphWeight DeserializeWeight(byte[] bytes) { if (bytes != null) { XmlStream stream = new XmlStream("weight"); MemoryStream ms = new MemoryStream(bytes); stream.ReadStream(ms); GraphWeight weight = new GraphWeight(); weight.Load(stream); return(weight); } return(null); }
async public Task <bool> LoadMapDocumentAsync(string path) { XmlStream stream = new XmlStream(""); if (stream.ReadStream(path)) { while (_maps.Count > 0) { this.RemoveMap((IMap)_maps.First()); } return(await stream.LoadAsync("MapDocument", this) != null); } return(false); }
private void btnLoad_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Xml Datei|*.xml"; dlg.InitialDirectory = SystemVariables.ApplicationDirectory + @"\misc\tiling\import"; if (dlg.ShowDialog() == DialogResult.OK) { XmlStream stream = new XmlStream("TileService"); stream.ReadStream(dlg.FileName); this.LoadStream(stream); } }
private void btnLoad_Click(object sender, EventArgs e) { if (_metadata != null) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Xml Datei|*.xml"; if (dlg.ShowDialog() == DialogResult.OK) { XmlStream stream = new XmlStream("TileService"); stream.ReadStream(dlg.FileName); _metadata.Load(stream); this.Parameter = _metadata; } } }
static public bool SetMetadata(string mapName, string metadata, string usr, string pwd) { if (InternetMapServer.acl != null && !InternetMapServer.acl.HasAccess(Identity.FromFormattedString(usr), pwd, "admin_metadata_set")) { return(false); } FileInfo fi = new FileInfo(InternetMapServer.ServicesPath + @"/" + mapName + ".meta"); StringReader sr = new StringReader(metadata); XmlStream xmlStream = new XmlStream(""); xmlStream.ReadStream(sr); xmlStream.WriteStream(fi.FullName); return(ReloadMap(mapName, usr, pwd)); }
public static TileServiceMetadata FromService(this TileServiceMetadata metadata, string server, string service) { var url = server.ToWmtsUrl(service, "GetMetadata"); using (var client = new HttpClient()) { var response = client.GetAsync(url).Result; if (!response.IsSuccessStatusCode) { throw new Exception($"{ url } return with status code { response.StatusCode }"); } var responseStream = response.Content.ReadAsStreamAsync().Result; XmlStream xmlStream = new XmlStream("WmtsMetadata"); xmlStream.ReadStream(responseStream); return(xmlStream.Load("TileServiceMetadata") as TileServiceMetadata); } }
static public void Load() { try { _loaded = true; XmlStream stream = new XmlStream("webproxy"); if (!stream.ReadStream(SystemVariables.CommonApplicationData + @"/options_webproxy.xml")) { stream = new XmlStream("webproxy"); stream.Save("useproxy", (int)UseProxyType.none); stream.Save("server", String.Empty); stream.Save("port", 80); stream.Save("exceptions", "localhost;127.0.0.1"); stream.Save("domain", String.Empty); stream.Save("user", String.Empty); stream.Save("password", String.Empty); stream.WriteStream(SystemVariables.CommonApplicationData + @"/options_webproxy.xml"); stream = new XmlStream("webproxy"); stream.ReadStream(SystemVariables.CommonApplicationData + @"/options_webproxy.xml"); } _useProxy = (UseProxyType)stream.Load("useproxy"); _server = (string)stream.Load("server", ""); _port = (int)stream.Load("port", 80); _exceptions = (string)stream.Load("exceptions", ""); _domain = (string)stream.Load("domain", ""); _user = (string)stream.Load("user", ""); _password = (string)stream.Load("password", ""); ProxySettings.LoadProxy(); } catch (Exception ex) { LastErrorMessage = ex.Message; _useProxy = UseProxyType.defaultProxy; } }
private static void ApplyMetadata(Map map) { try { if (map == null) { return; } FileInfo fi = new FileInfo(ServicesPath + @"\" + map.Name + ".meta"); IServiceMap sMap = new ServiceMap(map, mapServer); XmlStream xmlStream; // 1. Bestehende Metadaten auf sds anwenden if (fi.Exists) { xmlStream = new XmlStream(""); xmlStream.ReadStream(fi.FullName); sMap.ReadMetadata(xmlStream); } // 2. Metadaten neu schreiben... xmlStream = new XmlStream("Metadata"); sMap.WriteMetadata(xmlStream); if (map is Metadata) { ((Metadata)map).Providers = sMap.Providers; } // Overriding: no good idea -> problem, if multiple instances do this -> killing the metadata file!!! //xmlStream.WriteStream(fi.FullName); } catch (Exception ex) { if (Functions.log_errors) { Logger.Log(loggingMethod.error, "LoadConfig: " + ex.Message); } } }
internal static IMap LoadMap(string name, IServiceRequestContext context) { try { DirectoryInfo di = new DirectoryInfo(ServicesPath); if (!di.Exists) { di.Create(); } FileInfo fi = new FileInfo(ServicesPath + @"\" + name + ".mxl"); if (fi.Exists) { ServerMapDocument doc = new ServerMapDocument(); doc.LoadMapDocument(fi.FullName); if (doc.Maps.Count == 1) { ApplyMetadata(doc.Maps[0] as Map); if (!mapDocument.AddMap(doc.Maps[0])) { return(null); } return(doc.Maps[0]); } return(null); } fi = new FileInfo(ServicesPath + @"\" + name + ".svc"); if (fi.Exists) { XmlStream stream = new XmlStream(""); stream.ReadStream(fi.FullName); IServiceableDataset sds = stream.Load("IServiceableDataset", null) as IServiceableDataset; if (sds != null && sds.Datasets != null) { Map map = new Map(); map.Name = name; foreach (IDataset dataset in sds.Datasets) { if (dataset is IRequestDependentDataset) { if (!((IRequestDependentDataset)dataset).Open(context)) { return(null); } } else { if (!dataset.Open()) { return(null); } } //map.AddDataset(dataset, 0); foreach (IDatasetElement element in dataset.Elements) { if (element == null) { continue; } ILayer layer = LayerFactory.Create(element.Class, element as ILayer); if (layer == null) { continue; } map.AddLayer(layer); if (element.Class is IWebServiceClass) { if (map.SpatialReference == null) { map.SpatialReference = ((IWebServiceClass)element.Class).SpatialReference; } foreach (IWebServiceTheme theme in ((IWebServiceClass)element.Class).Themes) { map.SetNewLayerID(theme); } } else if (element.Class is IFeatureClass && map.SpatialReference == null) { map.SpatialReference = ((IFeatureClass)element.Class).SpatialReference; } else if (element.Class is IRasterClass && map.SpatialReference == null) { map.SpatialReference = ((IRasterClass)element.Class).SpatialReference; } } } ApplyMetadata(map); if (!mapDocument.AddMap(map)) { return(null); } return(map); } return(null); } } catch (Exception ex) { if (Functions.log_errors) { Logger.Log(loggingMethod.error, "LoadConfig: " + ex.Message); } } return(null); }
async private Task <bool> AddMap(string mapName, string mapXml) { string folder = mapName.FolderName(); if (!String.IsNullOrWhiteSpace(folder)) { if (!Directory.Exists((_mapServerService.Options.ServicesPath + "/" + folder).ToPlatformPath())) { throw new MapServerException("Folder not exists"); } } if (String.IsNullOrEmpty(mapXml)) { return(await ReloadMap(mapName)); } if ((await _mapServerService.Instance.Maps(null)).Count() >= _mapServerService.Instance.MaxServices) { // Überprüfen, ob schon eine Service mit gleiche Namen gibt... // wenn ja, ist es nur einem Refresh eines bestehenden Services bool found = false; foreach (IMapService existingMap in await _mapServerService.Instance.Maps(null)) { if (existingMap.Name == mapName) { found = true; break; } } if (!found) { //return false; throw new MapServerException("Unknown error"); } } XmlStream xmlStream = new XmlStream("MapDocument"); using (StringReader sr = new StringReader(mapXml)) { if (!xmlStream.ReadStream(sr, String.Empty)) // invariant culture { throw new MapServerException("Unable to read MapXML"); } } ServerMapDocument mapDocument = new ServerMapDocument(_mapServerService); await mapDocument.LoadAsync(xmlStream); if (mapDocument.Maps.Count() == 0) { throw new MapServerException("No maps found in document"); } var map = mapDocument.Maps.First() as Map; //Map map = new Map(); //map.Load(xmlStream); map.Name = mapName; StringBuilder errors = new StringBuilder(); bool hasErrors = false; foreach (var dataset in map.Datasets) { if (!String.IsNullOrWhiteSpace(dataset.LastErrorMessage)) { errors.Append("Dataset " + dataset.GetType().ToString() + Environment.NewLine); errors.Append(dataset.LastErrorMessage + Environment.NewLine + Environment.NewLine); hasErrors = true; } } if (map.HasErrorMessages) { //errors.Append("Map Errors/Warnings:" + Environment.NewLine); foreach (var errorMessage in map.ErrorMessages) { errors.Append(errorMessage + Environment.NewLine); hasErrors |= errorMessage.ToLower().StartsWith("warning:") == false; // Warnings should not throw an exception } } if (map.LastException != null) { errors.Append("Map Exception:" + Environment.NewLine); errors.Append(map.LastException.Message?.ToString()); hasErrors = true; } foreach (IFeatureLayer featureLayer in map.MapElements.Where(e => e is IFeatureLayer)) { if (featureLayer.Class is IFeatureClass && ((IFeatureClass)featureLayer.Class).SpatialReference == null) { if (map.LayerDefaultSpatialReference != null) { errors.Append($"Warning: { featureLayer.Title } has no spatial reference. Map default '{ map.LayerDefaultSpatialReference.EpsgCode }' will used for this layer." + Environment.NewLine); } else { errors.Append($"Error: { featureLayer.Title } has no spatial reference. Fix this or at least set a default spatial reference for this map in the carto app" + Environment.NewLine); } } } if (hasErrors) { throw new MapServerException("Errors: " + Environment.NewLine + errors.ToString()); } XmlStream pluginStream = new XmlStream("Moduls"); using (StringReader sr = new StringReader(mapXml)) { if (!xmlStream.ReadStream(sr)) { throw new MapServerException("Unable to read MapXML (Moduls)"); } } ModulesPersists modules = new ModulesPersists(map); modules.Load(pluginStream); //foreach (IMap m in ListOperations<IMap>.Clone(_doc.Maps)) //{ // if (m.Name == map.Name) _doc.RemoveMap(m); //} //if (!_doc.AddMap(map)) return false; _mapServerService.AddMapService(mapName, MapServiceType.MXL); await SaveConfig(mapDocument); var result = await ReloadMap(mapName); if (errors.Length > 0) // Warnings { throw new MapServerException("Warnings: " + Environment.NewLine + errors.ToString()); } return(result); }
public bool AddMap(string mapName, string MapXML, string usr, string pwd) { if (String.IsNullOrEmpty(MapXML)) { return(ReloadMap(mapName, usr, pwd)); } if (IMS.acl != null && !IMS.acl.HasAccess(Identity.FromFormattedString(usr), pwd, "admin_addmap")) { return(false); } if (IMS.mapServer.Maps.Count >= IMS.mapServer.MaxServices) { // Überprüfen, ob schon eine Service mit gleiche Namen gibt... // wenn ja, ist es nur einem Refresh eines bestehenden Services bool found = false; foreach (IMapService map in IMS.mapServer.Maps) { if (map.Name == mapName) { found = true; break; } } if (!found) { return(false); } } if (MapXML.IndexOf("<IServiceableDataset") == 0) { XmlStream xmlStream = new XmlStream(""); StringReader sr = new StringReader("<root>" + MapXML + "</root>"); if (!xmlStream.ReadStream(sr)) { return(false); } IServiceableDataset sds = xmlStream.Load("IServiceableDataset", null) as IServiceableDataset; if (sds != null && sds.Datasets != null) { IMS.SaveServiceableDataset(sds, mapName); AddMapService(mapName, MapServiceType.SVC); } } else if (MapXML.IndexOf("<ServiceCollection") == 0) { XmlStream stream = new XmlStream(""); StringReader sr = new StringReader(MapXML); if (!stream.ReadStream(sr)) { return(false); } IMS.SaveServiceCollection(mapName, stream); } else // Map { XmlStream xmlStream = new XmlStream("IMap"); StringReader sr = new StringReader(MapXML); if (!xmlStream.ReadStream(sr)) { return(false); } Map map = new Map(); map.Load(xmlStream); map.Name = mapName; foreach (IMap m in ListOperations <IMap> .Clone(_doc.Maps)) { if (m.Name == map.Name) { _doc.RemoveMap(m); } } if (!_doc.AddMap(map)) { return(false); } AddMapService(mapName, MapServiceType.MXL); IMS.SaveConfig(map); } /* * // Alle Layer sichtbar schalten... * IEnum layers = map.MapLayers; * IDatasetElement element; * while((element=(IDatasetElement)layers.Next)!=null) * { * ITOCElement tocElement = map.TOC.GetTOCElement(element); * if (tocElement != null) tocElement.LayerVisible = true; * } */ return(true); }
static public bool AddMap(string mapName, string MapXML, string usr, string pwd) { if (String.IsNullOrEmpty(MapXML)) { return(ReloadMap(mapName, usr, pwd)); } if (InternetMapServer.acl != null && !InternetMapServer.acl.HasAccess(Identity.FromFormattedString(usr), pwd, "admin_addmap")) { return(false); } if (InternetMapServer.Instance.Maps.Count >= InternetMapServer.Instance.MaxServices) { // Überprüfen, ob schon eine Service mit gleiche Namen gibt... // wenn ja, ist es nur einem Refresh eines bestehenden Services bool found = false; foreach (IMapService map in InternetMapServer.Instance.Maps) { if (map.Name == mapName) { found = true; break; } } if (!found) { return(false); } } if (MapXML.IndexOf("<IServiceableDataset") == 0) { XmlStream xmlStream = new XmlStream(""); StringReader sr = new StringReader("<root>" + MapXML + "</root>"); if (!xmlStream.ReadStream(sr)) { return(false); } IServiceableDataset sds = xmlStream.Load("IServiceableDataset", null) as IServiceableDataset; if (sds != null && sds.Datasets != null) { InternetMapServer.SaveServiceableDataset(sds, mapName); AddMapService(mapName, MapServiceType.SVC); } } else if (MapXML.IndexOf("<ServiceCollection") == 0) { XmlStream stream = new XmlStream(""); StringReader sr = new StringReader(MapXML); if (!stream.ReadStream(sr)) { return(false); } InternetMapServer.SaveServiceCollection(mapName, stream); } else // Map { XmlStream xmlStream = new XmlStream("IMap"); StringReader sr = new StringReader(MapXML); if (!xmlStream.ReadStream(sr)) { return(false); } Map map = new Map(); map.Load(xmlStream); map.Name = mapName; //foreach (IMap m in ListOperations<IMap>.Clone(_doc.Maps)) //{ // if (m.Name == map.Name) _doc.RemoveMap(m); //} //if (!_doc.AddMap(map)) return false; AddMapService(mapName, MapServiceType.MXL); InternetMapServer.SaveConfig(map); } return(true); }
async public Task LoadMapDocument(string filename) { if (_doc == null || filename == "") { return; } _docFilename = filename; System.IO.FileInfo fi = new System.IO.FileInfo(filename); if (!fi.Exists) { return; } if (fi.Extension.ToLower() != ".axl") { RemoveAllDataViews(); if (_appWindow != null) { _appWindow.RemoveAllToolbars(); } _activeDataView = null; } XmlStream stream = new XmlStream(""); if (fi.Extension.ToLower() == ".rdm") { StreamReader sr = new StreamReader(filename); byte[] bytes = new byte[fi.Length]; BinaryReader br = new BinaryReader(sr.BaseStream); br.Read(bytes, 0, bytes.Length); sr.Close(); bytes = Crypto.Decrypt(bytes, _cryptoKey); MemoryStream ms = new MemoryStream(bytes); stream.ReadStream(ms); ms.Close(); } else { stream.ReadStream(filename); } while (_doc.Maps.Count() > 0) { _doc.RemoveMap(_doc.Maps.First()); } _dataViews.Clear(); await stream.LoadAsync("MapDocument", _doc); // Load DataViews... DataView dv; while ((dv = (DataView)stream.Load("DataView", null, new DataView(_doc.Maps))) != null) { if (!(dv.Map is Map)) { continue; } DataView dataView = _appWindow.AddDataView((Map)dv.Map); if (dataView == null) { continue; } dataView.Envelope = dv.Envelope; dataView.TOC = dv.TOC; dataView.DisplayRotation = dv.DisplayRotation; if (_activeDataView == null) { _activeDataView = dataView; } } if (_dataViews.Count == 0 && _doc.Maps.Count() > 0) { //_appWindow.AddDataView((Map)_doc.Maps[0]); _activeDataView = _dataViews[0]; } if (_activeDataView != null && _activeDataView.MapView != null) { _activeDataView.MapView.Tool = this.ActiveTool; } ValidateUI(); IsDirty = false; if (fi.Extension.ToLower() == ".restore") { IsDirty = true; fi = new FileInfo(fi.FullName.Substring(0, fi.FullName.Length - ".restore".Length)); _docFilename = fi.FullName; } _appWindow.Title = "gView.Carto " + fi.Name; _readonly = (fi.Extension.ToLower() == ".rdm"); foreach (var map in _doc.Maps) { if (map.HasErrorMessages) { FormToolException.Show($"Loading Map '{ map.Name }'", String.Join(Environment.NewLine, map.ErrorMessages)); } } if (AfterLoadMapDocument != null) { AfterLoadMapDocument(_doc); } }
async public Task Run(string[] args) { string inFile = String.Empty; string outFile = String.Empty; string command = "info"; int datasetIndex = -1; List <string> parameterNames = new List <string>(); List <string> newParameterValues = new List <string>(); for (int i = 1; i < args.Length - 1; i++) { switch (args[i].ToLower()) { case "-cmd": command = args[++i]; break; case "-mxl": inFile = args[++i]; break; case "-out-mxl": outFile = args[++i]; break; case "-dsindex": case "-dataset-index": datasetIndex = int.Parse(args[++i]); break; case "-parameter-name": case "-parameter": parameterNames.Add(args[++i]); break; case "-new-value": case "-new-parameter-value": newParameterValues.Add(args[++i]); break; } } if (String.IsNullOrEmpty(inFile)) { throw new IncompleteArgumentsException(); } XmlStream stream = new XmlStream(""); stream.ReadStream(inFile); MxlDocument doc = new MxlDocument(); await stream.LoadAsync("MapDocument", doc); var map = doc.Maps.FirstOrDefault() as Map; if (map.HasErrorMessages) { throw new Exception($"Can't load source mxl { inFile }:{ Environment.NewLine }{ String.Join('\n', map.ErrorMessages) }"); } bool saveOutput = false; switch (command) { case "info": DatasetInfo(map); break; case "modify-connectionstring": case "modify-cs": await ModifyConnectionString(map, datasetIndex, parameterNames, newParameterValues); saveOutput = true; break; default: throw new Exception($"Unkown command: { command }"); } if (saveOutput) { stream = new XmlStream(""); stream.Save("MapDocument", doc); Console.WriteLine($"Write: { outFile }"); stream.WriteStream(outFile); Console.WriteLine("succeeded..."); } }
private static async Task <int> Main(string[] args) { try { string inFile = args.FirstOrDefault(); for (int i = 1; i < args.Length; i++) { if (args[i] == "-??" && i < args.Length - 1) { } } if (String.IsNullOrWhiteSpace(inFile)) { Console.WriteLine("Usage: gView.Cmd.MxlInfo mxl-file [Options]"); } XmlStream stream = new XmlStream(""); stream.ReadStream(inFile); MapDocument doc = new MapDocument(); await stream.LoadAsync("MapDocument", doc); foreach (var map in doc.Maps) { if (map?.MapElements == null) { continue; } Console.WriteLine($"Map: { map.Name }"); Console.WriteLine("=========================================================="); var featureLayers = map.TOC.Layers.Where(l => l is IFeatureLayer) .Select(l => (IFeatureLayer)l); Console.WriteLine("FeatureLayers:"); Console.WriteLine("-------------------------------------------------------------"); if (map.Datasets != null) { int datasetID = 0; foreach (var dataset in map.Datasets) { Console.WriteLine($"Dataset: { dataset.DatasetName }"); Console.WriteLine($" { dataset.GetType().ToString() }"); Console.WriteLine("-------------------------------------------------------"); foreach (var dsElement in map.MapElements.Where(e => e.DatasetID == datasetID)) { if (dsElement?.Class == null) { continue; } var featureLayer = featureLayers.Where(l => l.DatasetID == datasetID && l.Class == dsElement.Class) .FirstOrDefault(); if (featureLayer == null) { continue; } Console.WriteLine($"FeatureLayer: { featureLayer.Title }"); Console.WriteLine($" Class: { dsElement.Class.Name }"); Console.WriteLine($" { dsElement.Class.GetType().ToString() }"); } } } } return(0); } catch (Exception ex) { Console.WriteLine("Exception:"); Console.WriteLine(ex.Message); return(1); } }
async public Task Run(string[] args) { string inFile = String.Empty; string outFile = String.Empty; string targetConnectionString = String.Empty; IEnumerable <string> dontCopyFeatues = null; Guid targetGuid = new Guid(); for (int i = 1; i < args.Length - 1; i++) { switch (args[i].ToLower()) { case "-mxl": inFile = args[++i]; break; case "-target-connectionstring": targetConnectionString = args[++i]; break; case "-target-guid": var guid = args[++i]; switch (guid.ToLower()) { case "sqlserver": targetGuid = new Guid("3B870AB5-8BE0-4a00-911D-ECC6C83DD6B4"); break; case "postgres": targetGuid = new Guid("33254063-133D-4b17-AAE2-46AF7A7DA733"); break; case "sqlite": targetGuid = new Guid("36DEB6AC-EA0C-4B37-91F1-B2E397351555"); break; default: targetGuid = new Guid(guid); break; } break; case "-out-mxl": outFile = args[++i]; break; case "-dont-copy-features-from": dontCopyFeatues = args[++i].Split(',').Select(n => n.Trim().ToLower()); break; } } if (String.IsNullOrEmpty(inFile) || String.IsNullOrEmpty(targetConnectionString) || targetGuid.Equals(new Guid())) { throw new IncompleteArgumentsException(); } if (String.IsNullOrEmpty(outFile)) { outFile = String.IsNullOrEmpty(inFile) ? String.Empty : inFile.Substring(0, inFile.LastIndexOf(".")) + "_fdb.mxl"; } XmlStream stream = new XmlStream(""); stream.ReadStream(inFile); MxlDocument doc = new MxlDocument(); await stream.LoadAsync("MapDocument", doc); var pluginManager = new PlugInManager(); #region Destination Dataset IFeatureDataset targetFeatureDataset = pluginManager.CreateInstance(targetGuid) as IFeatureDataset; if (targetFeatureDataset == null) { throw new Exception("Plugin with GUID '" + targetGuid.ToString() + "' is not a feature dataset..."); } await targetFeatureDataset.SetConnectionString(targetConnectionString); await targetFeatureDataset.Open(); var targetDatabase = (IFDBDatabase)targetFeatureDataset.Database; #endregion Destination Dataset var map = doc.Maps.FirstOrDefault() as Map; var featureLayers = map.TOC.Layers.Where(l => l is IFeatureLayer) .Select(l => (IFeatureLayer)l); if (map.Datasets != null) { int datasetId = 0; foreach (var dataset in map.Datasets.ToArray()) { Console.WriteLine(); Console.WriteLine($"Dataset: { dataset.DatasetName }"); Console.WriteLine($" { dataset.GetType() }"); Console.WriteLine("-------------------------------------------------------"); foreach (var dsElement in map.MapElements.Where(e => e.DatasetID == datasetId)) { if (dsElement?.Class == null) { continue; } var featureLayer = featureLayers.Where(l => l.DatasetID == datasetId && l.Class == dsElement.Class) .FirstOrDefault(); if (featureLayer == null) { continue; } Console.WriteLine(); Console.WriteLine($"FeatureLayer: { featureLayer.Title }"); Console.WriteLine($" Class: { dsElement.Class.Name }"); Console.WriteLine($" { dsElement.Class.GetType() }"); Console.WriteLine(); var sourceFc = dsElement.Class as IFeatureClass; if (sourceFc == null) { Console.WriteLine("Class is not a FeatureClass"); continue; } #region Create Target Featureclass (if not exists) string targetFcName = dsElement.Class.Name; if (targetFcName.Contains(".")) { targetFcName = targetFcName.Substring(targetFcName.LastIndexOf(".") + 1); } var targetFc = (await targetFeatureDataset.Element(targetFcName))?.Class as IFeatureClass; if (targetFc != null) { var count = await targetFc.CountFeatures(); if (count > 0) { Console.Write($"Already exists in target fdb ({ count } features)"); } else { if (!await targetDatabase.DeleteFeatureClass(targetFcName)) { throw new Exception($"Can't delete existing (empty) featureclass { targetFcName }"); } } } else { var fcId = await targetDatabase.CreateFeatureClass( targetFeatureDataset.DatasetName, targetFcName, new GeometryDef() { GeometryType = sourceFc.GeometryType, HasM = sourceFc.HasM, HasZ = sourceFc.HasZ, SpatialReference = sourceFc.SpatialReference }, new Fields(sourceFc.Fields.ToEnumerable().Select(f => { if (f != null && f.type == FieldType.ID && f.name.ToUpper().Equals("FDB_OID") == false) // also include original ID Column { return(new Field(f.name, FieldType.integer)); } return(f); }))); if (fcId <= 0) { throw new Exception($"Can't create featureclass { targetFcName }: { targetDatabase.LastErrorMessage }"); } targetFc = (await targetFeatureDataset.Element(targetFcName)).Class as IFeatureClass; if (targetFc == null) { throw new Exception($"Can't load target FeatureClass { targetFcName }"); } var copyFeatures = dontCopyFeatues == null || (!dontCopyFeatues.Contains(sourceFc.Name.ToLower()) && !dontCopyFeatues.Contains(targetFc.Name.ToLower())); if (copyFeatures) { var sIndexDef = new gViewSpatialIndexDef(null, 62); var tree2 = await SpatialIndex2( targetDatabase, sourceFc, sIndexDef); tree2.Trim(); List <long> nids = new List <long>(); foreach (BinaryTree2BuilderNode node in tree2.Nodes) { nids.Add(node.Number); } await((AccessFDB)targetDatabase).ShrinkSpatialIndex(targetFcName, nids); await((AccessFDB)targetDatabase).SetSpatialIndexBounds(targetFcName, "BinaryTree2", tree2.Bounds, tree2.SplitRatio, tree2.MaxPerNode, tree2.maxLevels); await((AccessFDB)targetDatabase).SetFeatureclassExtent(targetFcName, tree2.Bounds); #endregion Create Target Featureclass (if not exists) var featureBag = new List <IFeature>(); IFeature feature = null; int counter = 0; Console.WriteLine("Copy features:"); if (sourceFc is IFeatureClassPerformanceInfo && ((IFeatureClassPerformanceInfo)sourceFc).SupportsHighperformanceOidQueries == false) { using (var memoryFeatureBag = new FeatureBag()) { #region Read all Features to FeatureBag (Memory) // // eg. SDE Multiversion Views are very slow, queiried win OID Filter!! // Console.WriteLine("Source feature class do not support high performance oid quries!"); QueryFilter filter = new QueryFilter() { WhereClause = "1=1" }; filter.AddField("*"); Console.WriteLine("Read all features to memory feature bag..."); using (var featureCursor = await sourceFc.GetFeatures(filter)) { if (featureCursor == null) { throw new Exception($"Can't query features from soure featureclass: { (sourceFc is IDebugging ? ((IDebugging)sourceFc).LastException?.Message : "") }"); } while ((feature = await featureCursor.NextFeature()) != null) { memoryFeatureBag.AddFeature(feature); counter++; if (counter % 10000 == 0) { Console.Write($"...{ counter }"); } } } #endregion Read all Features to FeatureBag (Memory) #region Write to target featureclass Console.WriteLine($"...{ counter }"); Console.WriteLine("copy feature to target feature class"); counter = 0; foreach (BinaryTree2BuilderNode node in tree2.Nodes) { foreach (var memoryFeature in memoryFeatureBag.GetFeatures(node.OIDs)) { memoryFeature.Fields.Add(new FieldValue("$FDB_NID", node.Number)); featureBag.Add(memoryFeature); counter++; if (counter % 10000 == 0) { await Store(targetDatabase, targetFc, featureBag, counter); } } } #endregion Write to target featureclass } GC.Collect(); } else { #region Query all per Oid and Node foreach (BinaryTree2BuilderNode node in tree2.Nodes) { RowIDFilter filter = new RowIDFilter(sourceFc.IDFieldName); filter.IDs = node.OIDs; filter.SubFields = "*"; using (var featureCursor = await sourceFc.GetFeatures(filter)) { if (featureCursor == null) { throw new Exception($"Can't query features from soure featureclass: { (sourceFc is IDebugging ? ((IDebugging)sourceFc).LastException?.Message : "") }"); } while ((feature = await featureCursor.NextFeature()) != null) { feature.Fields.Add(new FieldValue("$FDB_NID", node.Number)); featureBag.Add(feature); counter++; if (counter % 10000 == 0) { await Store(targetDatabase, targetFc, featureBag, counter); } } } } #endregion Query all per Oid and Node } await Store(targetDatabase, targetFc, featureBag, counter); await((AccessFDB)targetDatabase).CalculateExtent(targetFcName); } } dsElement.Title = targetFc.Name; ((DatasetElement)dsElement).Class = targetFc; } ((MapPersist)map).SetDataset(datasetId, targetFeatureDataset); datasetId++; } } map.Compress(); stream = new XmlStream(""); stream.Save("MapDocument", doc); Console.WriteLine($"Write: { outFile }"); stream.WriteStream(outFile); Console.WriteLine("succeeded..."); }
public void LoadMapDocument(string filename) { if (_doc == null || filename == "") { return; } _docFilename = filename; System.IO.FileInfo fi = new System.IO.FileInfo(filename); if (!fi.Exists) { return; } if (fi.Extension.ToLower() != ".axl") { RemoveAllDataViews(); if (_appWindow != null) { _appWindow.RemoveAllToolbars(); } _activeDataView = null; } XmlStream stream = new XmlStream(""); if (fi.Extension.ToLower() == ".rdm") { StreamReader sr = new StreamReader(filename); byte[] bytes = new byte[fi.Length]; BinaryReader br = new BinaryReader(sr.BaseStream); br.Read(bytes, 0, bytes.Length); sr.Close(); bytes = Crypto.Decrypt(bytes, _cryptoKey); MemoryStream ms = new MemoryStream(bytes); stream.ReadStream(ms); ms.Close(); } else if (fi.Extension.ToLower() == ".axl") { IMap map = _doc.Maps[0]; PlugInManager pman = new PlugInManager(); #region AXL XmlDocument axl = new XmlDocument(); axl.Load(fi.FullName); #region Extent XmlNode envNode = axl.SelectSingleNode("ARCXML/CONFIG/MAP/PROPERTIES/ENVELOPE[@minx and @maxx and @miny and @miny]"); if (envNode != null) { Envelope env = new Envelope(envNode); map.Display.Limit = new Envelope(env); map.Display.ZoomTo(env); } #endregion #region Workspaces Dictionary <string, IDataset> _workspaces = new Dictionary <string, IDataset>(); foreach (XmlNode workspaceNode in axl.SelectNodes("ARCXML/CONFIG/MAP/WORKSPACES/*")) { switch (workspaceNode.Name) { case "SDEWORKSPACE": string connectionString = "server=" + workspaceNode.Attributes["server"].Value; if (workspaceNode.Attributes["instance"] != null) { connectionString += ";instance=" + workspaceNode.Attributes["instance"].Value; } if (workspaceNode.Attributes["database"] != null) { connectionString += ";database=" + workspaceNode.Attributes["database"].Value; } if (workspaceNode.Attributes["user"] != null) { connectionString += ";user="******"user"].Value; } if (workspaceNode.Attributes["password"] != null) { connectionString += ";password="******"password"].Value; } IDataset sdeDataset = pman.CreateInstance(new Guid("CE42218B-6962-48c9-9BAC-39E4C5003AE5")) as IDataset; if (sdeDataset == null) { continue; } sdeDataset.ConnectionString = connectionString; if (!sdeDataset.Open()) { continue; } _workspaces.Add(workspaceNode.Attributes["name"].Value, sdeDataset); break; case "SHAPEWORKSPACE": IDataset shapeDataset = pman.CreateInstance(new Guid("80F48262-D412-41fb-BF43-2D611A2ABF42")) as IDataset; if (shapeDataset == null) { continue; } shapeDataset.ConnectionString = workspaceNode.Attributes["directory"].Value; if (!shapeDataset.Open()) { continue; } _workspaces.Add(workspaceNode.Attributes["name"].Value, shapeDataset); break; case "IMAGEWORKSPACE": IDataset rasterDataset = pman.CreateInstance(new Guid("43DFABF1-3D19-438c-84DA-F8BA0B266592")) as IDataset; _workspaces.Add(workspaceNode.Attributes["name"].Value, rasterDataset); break; } } #endregion #region Layers XmlNodeList layerNodes = axl.SelectNodes("ARCXML/CONFIG/MAP/LAYER[@name and @id and @type]"); if (layerNodes == null) { return; } for (int i = layerNodes.Count - 1; i >= 0; i--) { XmlNode layerNode = layerNodes[i]; if (layerNode.Attributes["type"].Value == "featureclass") { XmlNode datasetNode = layerNode.SelectSingleNode("DATASET[@name and @workspace]"); if (datasetNode == null) { continue; } if (!_workspaces.ContainsKey(datasetNode.Attributes["workspace"].Value)) { continue; } IDataset dataset = _workspaces[datasetNode.Attributes["workspace"].Value]; IDatasetElement dsElement = dataset[datasetNode.Attributes["name"].Value]; if (dsElement == null || dsElement.Class == null) { continue; } IFeatureLayer layer = (IFeatureLayer)LayerFactory.Create(dsElement.Class); if (layerNode.Attributes["visible"] != null) { layer.Visible = layerNode.Attributes["visible"].Value == "true"; } layer.SID = layerNode.Attributes["id"].Value; map.AddLayer(layer); SetLayernameAndScales(layerNode, layer); SetRenderers(layerNode, layer); XmlNode queryNode = layerNode.SelectSingleNode("QUERY[@where]"); if (queryNode != null) { layer.FilterQuery = new QueryFilter(); layer.FilterQuery.WhereClause = queryNode.Attributes["where"].Value; } } else if (layerNode.Attributes["type"].Value == "image") { XmlNode datasetNode = layerNode.SelectSingleNode("DATASET[@name and @workspace]"); if (datasetNode == null) { continue; } if (!_workspaces.ContainsKey(datasetNode.Attributes["workspace"].Value)) { continue; } IRasterFileDataset dataset = _workspaces[datasetNode.Attributes["workspace"].Value] as IRasterFileDataset; if (dataset == null) { continue; } XmlNode workspaceNode = axl.SelectSingleNode("ARCXML/CONFIG/MAP/WORKSPACES/IMAGEWORKSPACE[@name='" + datasetNode.Attributes["workspace"].Value + "' and @directory]"); if (workspaceNode == null) { continue; } IRasterLayer rLayer = dataset.AddRasterFile(workspaceNode.Attributes["directory"].Value + @"\" + datasetNode.Attributes["name"].Value); if (rLayer == null) { continue; } if (layerNode.Attributes["visible"] != null) { rLayer.Visible = layerNode.Attributes["visible"].Value == "true"; } rLayer.SID = layerNode.Attributes["id"].Value; map.AddLayer(rLayer); SetLayernameAndScales(layerNode, rLayer); } } #endregion ValidateUI(); IsDirty = false; _appWindow.Title = "gView.Carto " + fi.Name; if (AfterLoadMapDocument != null) { AfterLoadMapDocument(_doc); } return; #endregion } else { stream.ReadStream(filename); } while (_doc.Maps.Count > 0) { _doc.RemoveMap(_doc.Maps[0]); } _dataViews.Clear(); stream.Load("MapDocument", null, _doc); // Load DataViews... DataView dv; while ((dv = (DataView)stream.Load("DataView", null, new DataView(_doc.Maps))) != null) { if (!(dv.Map is Map)) { continue; } DataView dataView = _appWindow.AddDataView((Map)dv.Map); if (dataView == null) { continue; } dataView.Envelope = dv.Envelope; dataView.TOC = dv.TOC; dataView.DisplayRotation = dv.DisplayRotation; if (_activeDataView == null) { _activeDataView = dataView; } } if (_dataViews.Count == 0 && _doc.Maps.Count > 0) { //_appWindow.AddDataView((Map)_doc.Maps[0]); _activeDataView = _dataViews[0]; } if (_activeDataView != null && _activeDataView.MapView != null) { _activeDataView.MapView.Tool = this.ActiveTool; } ValidateUI(); IsDirty = false; _appWindow.Title = "gView.Carto " + fi.Name; _readonly = (fi.Extension.ToLower() == ".rdm"); if (AfterLoadMapDocument != null) { AfterLoadMapDocument(_doc); } }