Пример #1
0
        public void SaveMapDocument(string filename, bool performEncryption)
        {
            if (filename == "")
            {
                return;
            }

            if (filename.ToLower() == SystemVariables.ApplicationDirectory.ToLower() + @"\normal.mxl" ||
                filename == "normal.mxl")
            {
                switch (MessageBox.Show("Override normal.mxl?", "gView.Carto", MessageBoxButtons.YesNo))
                {
                case DialogResult.No:
                    return;
                }
            }

            XmlStream stream = new XmlStream("MapApplication", performEncryption);

            stream.Save("MapDocument", _doc);

            foreach (DataView dv in _dataViews)
            {
                stream.Save("DataView", dv);
            }

            System.IO.FileInfo fi = new System.IO.FileInfo(filename);
            if (fi.Extension.ToLower() == ".rdm")
            {
                StringBuilder sb    = new StringBuilder();
                StringWriter  strwr = new StringWriter(sb);
                stream.WriteStream(strwr, Formatting.None);
                strwr.Close();

                byte[] bytes = Encoding.Unicode.GetBytes(sb.ToString());
                bytes = Crypto.Encrypt(bytes, _cryptoKey);
                StreamWriter sw = new StreamWriter(fi.FullName);
                BinaryWriter bw = new BinaryWriter(sw.BaseStream);
                bw.Write(bytes);
                sw.Close();
            }
            else if (fi.Extension.ToLower() == ".axl")
            {
                MessageBox.Show("Can't save AXL Documents...", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                stream.WriteStream(filename);
            }

            IsDirty      = false;
            _docFilename = filename;

            _appWindow.Title = "gView.Carto " + fi.Name;
        }
Пример #2
0
        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);
        }
        async public Task SaveConfig(ServerMapDocument mapDocument)
        {
            try
            {
                if (MapDocument == null)
                {
                    return;
                }

                var map = mapDocument?.Maps.First() as Map;
                if (map == null)
                {
                    throw new MapServerException("Mapdocument don't contain a map");
                }

                XmlStream stream = new XmlStream("MapServer");
                stream.Save("MapDocument", mapDocument);

                stream.WriteStream(_mapServerService.Options.ServicesPath + "/" + map.Name + ".mxl");

                if (map is Map)
                {
                    await ApplyMetadata(map);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Map { mapDocument?.Maps?.First()?.Name }: LoadConfig - { ex.Message }");
            }
        }
Пример #4
0
        static public void SaveConfig(IMap map)
        {
            try
            {
                if (mapDocument == null)
                {
                    return;
                }

                ServerMapDocument doc = new ServerMapDocument();
                if (!doc.AddMap(map))
                {
                    return;
                }

                XmlStream stream = new XmlStream("MapServer");
                stream.Save("MapDocument", doc);

                stream.WriteStream(ServicesPath + @"\" + map.Name + ".mxl");
            }
            catch (Exception ex)
            {
                if (Functions.log_errors)
                {
                    Logger.Log(loggingMethod.error, "LoadConfig: " + ex.Message);
                }
            }
        }
Пример #5
0
        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;
            }
        }
Пример #6
0
        static public void SaveServiceableDataset(IServiceableDataset sds, string name)
        {
            try
            {
                if (sds != null)
                {
                    XmlStream stream = new XmlStream("MapServer");
                    stream.Save("IServiceableDataset", sds);

                    stream.WriteStream(ServicesPath + @"\" + name + ".svc");

                    if (sds is IMetadata)
                    {
                        stream = new XmlStream("Metadata");
                        ((IMetadata)sds).WriteMetadata(stream);
                        stream.WriteStream(ServicesPath + @"\" + name + ".svc.meta");
                    }
                }
            }
            catch (Exception ex)
            {
                if (Functions.log_errors)
                {
                    Logger.Log(loggingMethod.error, "LoadConfig: " + ex.Message);
                }
            }
        }
Пример #7
0
        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);
        }
        public static byte[] SerializeWeight(IGraphWeight weight)
        {
            if (weight != null)
            {
                XmlStream stream = new XmlStream("weight");
                weight.Save(stream);

                MemoryStream ms = new MemoryStream();
                stream.WriteStream(ms);
                return(ms.GetBuffer());
            }
            return(null);
        }
        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));
        }
Пример #10
0
 static public bool Commit()
 {
     try
     {
         XmlStream stream = new XmlStream("localcaching");
         stream.Save("use", _use);
         stream.Save("folder", _folder);
         stream.WriteStream(SystemVariables.CommonApplicationData + @"\options_tilecache_local_caching.xml");
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Пример #11
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Filter = "Xml Datei|*.xml";

            dlg.InitialDirectory = SystemVariables.ApplicationDirectory + @"\misc\tiling\import";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                XmlStream stream = new XmlStream("TileCache");
                this.SaveStream(stream);
                stream.WriteStream(dlg.FileName);
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (_metadata != null)
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "Xml Datei|*.xml";

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    XmlStream stream = new XmlStream("TileService");
                    _metadata.Save(stream);
                    stream.WriteStream(dlg.FileName);
                }
            }
        }
Пример #13
0
        async private Task <bool> AddMap2Connection(List <string> serviceNames, List <IMap> maps)
        {
            try
            {
                if (serviceNames.Count != maps.Count)
                {
                    return(false);
                }

                for (int i = 0; i < serviceNames.Count; i++)
                {
                    XmlStream stream = new XmlStream("MapDocument");
                    stream.Save("IMap", maps[i]);
                    stream.ReduceDocument("//IMap");

                    StringBuilder sb = new StringBuilder();
                    StringWriter  sw = new StringWriter(sb);
                    stream.WriteStream(sw);

                    //XmlDocument doc = new XmlDocument();
                    //doc.LoadXml(sb.ToString());

                    ServerConnection service = new ServerConnection(ConfigTextStream.ExtractValue(_connectionString, "server"));
                    if (!service.AddMap(serviceNames[i], sb.ToString(),
                                        ConfigTextStream.ExtractValue(_connectionString, "user"),
                                        ConfigTextStream.ExtractValue(_connectionString, "pwd")))
                    {
                        System.Windows.Forms.MessageBox.Show("Can't add map", "ERROR");
                    }
                }

                await Refresh();

                if (Refreshed != null)
                {
                    Refreshed(this);
                }

                return(true);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "ERROR");

                return(false);
            }
        }
Пример #14
0
        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));
        }
Пример #15
0
        public ExtensionSerializer(object extension)
        {
            if (PlugInManager.IsPlugin(extension) &&
                extension is IPersistable)
            {
                XmlStream stream = new XmlStream("");

                ((IPersistable)extension).Save(stream);

                MemoryStream ms = new MemoryStream();
                stream.WriteStream(ms);
                ms.Position = 0;
                byte[] b = new byte[ms.Length];
                ms.Read(b, 0, (int)ms.Length);

                _string = System.Text.Encoding.Unicode.GetString(b).Trim();
                _guid   = PlugInManager.PlugInID(extension);
            }
        }
Пример #16
0
        async private Task <bool> AddService2Connection(XmlStream stream)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                StringWriter  sw = new StringWriter(sb);
                stream.WriteStream(sw);

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(sb.ToString());

                FormAddServiceableDataset dlg = new FormAddServiceableDataset();
                if (dlg.ShowDialog() != DialogResult.OK)
                {
                    return(false);
                }

                ServerConnection service = new ServerConnection(ConfigTextStream.ExtractValue(_connectionString, "server"));
                if (!service.AddMap(dlg.ServiceName, doc.SelectSingleNode("//IServiceableDataset").OuterXml,
                                    ConfigTextStream.ExtractValue(_connectionString, "user"),
                                    ConfigTextStream.ExtractValue(_connectionString, "pwd")))
                {
                    System.Windows.Forms.MessageBox.Show("Can't add map", "ERROR");
                }
                //Refresh();
                if (!await Refresh())
                {
                    return(false);
                }
                if (Refreshed != null)
                {
                    Refreshed(this);
                }

                return(true);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "ERROR");

                return(false);
            }
        }
Пример #17
0
        static public bool Commit()
        {
            try
            {
                XmlStream stream = new XmlStream("webproxy");
                stream.Save("useproxy", (int)_useProxy);
                stream.Save("server", _server);
                stream.Save("port", _port);
                stream.Save("exceptions", _exceptions);
                stream.Save("domain", _domain);
                stream.Save("user", _user);
                stream.Save("password", _password);
                stream.WriteStream(SystemVariables.CommonApplicationData + @"/options_webproxy.xml");

                ProxySettings.LoadProxy();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Пример #18
0
        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;
            }
        }
Пример #19
0
        private void AddServiceCollection2Connection(string collectionName, string[] services)
        {
            XmlStream stream = new XmlStream("ServiceCollection");

            stream.Save("Services", new XmlStreamStringArray(services));

            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            stream.WriteStream(sw);

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(sb.ToString());

            ServerConnection service = new ServerConnection(ConfigTextStream.ExtractValue(_connectionString, "server"));

            if (!service.AddMap(collectionName, doc.SelectSingleNode("//ServiceCollection").OuterXml,
                                ConfigTextStream.ExtractValue(_connectionString, "user"),
                                ConfigTextStream.ExtractValue(_connectionString, "pwd")))
            {
                System.Windows.Forms.MessageBox.Show("Can't add map", "ERROR");
            }
        }
Пример #20
0
        public void Request(IServiceRequestContext context)
        {
            try
            {
                if (context == null || context.ServiceRequest == null || context.ServiceMap == null)
                {
                    return;
                }

                if (_mapServer == null)
                {
                    context.ServiceRequest.Response = "<FATALERROR>MapServer Object is not available!</FATALERROR>";
                    return;
                }

                TileServiceMetadata metadata = context.ServiceMap.MetadataProvider(_metaprovider) as TileServiceMetadata;
                if (metadata == null || metadata.Use == false)
                {
                    context.ServiceRequest.Response = "<ERROR>Service is not used with Tile Service</ERROR>";
                }

                string service = context.ServiceRequest.Service;
                string request = context.ServiceRequest.Request;
                if (request.ToLower().StartsWith("path="))
                {
                    request = request.Substring(5);
                }

                string[] args = request.Split('/');

                string command        = args[0].ToLower();
                bool   renderOnTheFly = false;
                if (command.Contains(":"))
                {
                    switch (command.Split(':')[1])
                    {
                    case "render":
                        renderOnTheFly = true;
                        break;
                    }

                    command = command.Split(':')[0];
                }

                switch (command)
                {
                case "metadata":
                    XmlStream stream = new XmlStream("metadata");
                    metadata.Save(stream);
                    StringWriter sw = new StringWriter();
                    stream.WriteStream(sw);
                    sw.Close();
                    context.ServiceRequest.Response = sw.ToString();
                    break;

                case "osm":
                case "tms":
                    if (args.Length == 4)
                    {
                        int epsg = int.Parse(args[1]);
                        if (metadata.EPSGCodes.Contains(epsg))
                        {
                            context.ServiceRequest.Response = TmsCapabilities(context, metadata, epsg);
                        }
                    }
                    else if (args.Length == 7)     // tms/srs/1.0.0/service/0/0/0.png
                    {
                        int    epsg   = int.Parse(args[1]);
                        double scale  = metadata.Scales[int.Parse(args[4])];
                        int    row    = (args[0] == "tms" ? int.Parse(args[5]) : int.Parse(args[6].Split('.')[0]));
                        int    col    = (args[0] == "tms" ? int.Parse(args[6].Split('.')[0]) : int.Parse(args[5]));
                        string format = ".png";
                        if (args[6].ToLower().EndsWith(".jpg"))
                        {
                            format = ".jpg";
                        }

                        GetTile(context, metadata, epsg, scale, row, col, format, (args[0] == "tms" ? GridOrientation.LowerLeft : GridOrientation.UpperLeft), renderOnTheFly);
                    }
                    else if (args.Length == 10)      // tms/srs/service/01/000/000/001/000/000/001.png
                    {
                        int    epsg   = int.Parse(args[1]);
                        double scale  = metadata.Scales[int.Parse(args[3])];
                        int    col    = int.Parse(args[4]) * 1000000 + int.Parse(args[5]) * 1000 + int.Parse(args[6]);
                        int    row    = int.Parse(args[7]) * 1000000 + int.Parse(args[8]) * 1000 + int.Parse(args[9].Split('.')[0]);
                        string format = ".png";
                        if (args[9].ToLower().EndsWith(".jpg"))
                        {
                            format = ".jpg";
                        }

                        GetTile(context, metadata, epsg, scale, row, col, format, (args[0] == "tms" ? GridOrientation.LowerLeft : GridOrientation.UpperLeft), renderOnTheFly);
                    }
                    break;

                case "init":
                    if (args.Length >= 5)
                    {
                        string cacheFormat = args[1].ToLower() == "compact" ? "compact" : "";
                        if (args[2].ToLower() != "ul" &&
                            args[2].ToLower() != "ll")
                        {
                            throw new ArgumentException();
                        }

                        int    epsg   = int.Parse(args[3]);
                        string format = "image/" + args[4].ToLower();
                        if (args[4].ToLower().EndsWith(".jpg"))
                        {
                            format = ".jpg";
                        }

                        WriteConfFile(context, metadata, cacheFormat, epsg, format,
                                      (args[2].ToLower() == "ul" ? GridOrientation.UpperLeft : GridOrientation.LowerLeft));
                    }
                    break;

                case "tile":
                    if (args.Length == 5)
                    {
                        int    epsg   = int.Parse(args[1]);
                        double scale  = GetScale(metadata, args[2]);    // double.Parse(args[2].Replace(",", "."), _nhi);
                        int    row    = int.Parse(args[3]);
                        int    col    = int.Parse(args[4].Split('.')[0]);
                        string format = ".png";
                        if (args[4].ToLower().EndsWith(".jpg"))
                        {
                            format = ".jpg";
                        }

                        GetTile(context, metadata, epsg, scale, row, col, format, GridOrientation.UpperLeft, renderOnTheFly);
                    }
                    else if (args.Length == 6)
                    {
                        if (args[1].ToLower() != "ul" &&
                            args[1].ToLower() != "ll")
                        {
                            throw new ArgumentException();
                        }

                        int    epsg   = int.Parse(args[2]);
                        double scale  = GetScale(metadata, args[3]);    // double.Parse(args[3].Replace(",", "."), _nhi);
                        int    row    = int.Parse(args[4]);
                        int    col    = int.Parse(args[5].Split('.')[0]);
                        string format = ".png";
                        if (args[5].ToLower().EndsWith(".jpg"))
                        {
                            format = ".jpg";
                        }

                        GetTile(context, metadata, epsg, scale, row, col, format,
                                (args[1].ToLower() == "ul" ? GridOrientation.UpperLeft : GridOrientation.LowerLeft), renderOnTheFly);
                    }
                    else if (args.Length >= 7)
                    {
                        string cacheFormat = args[1].ToLower();
                        if (args[2].ToLower() != "ul" &&
                            args[2].ToLower() != "ll")
                        {
                            throw new ArgumentException();
                        }

                        int    epsg   = int.Parse(args[3]);
                        double scale  = GetScale(metadata, args[4]);    // double.Parse(args[4].Replace(",", "."), _nhi);
                        int    row    = int.Parse(args[5]);
                        int    col    = int.Parse(args[6].Split('.')[0]);
                        string format = ".png";
                        if (args[6].ToLower().EndsWith(".jpg"))
                        {
                            format = ".jpg";
                        }

                        if (cacheFormat == "compact")
                        {
                            var boundingTiles = args.Length > 7 ? new BoundingTiles(args[7]) : null;

                            GetCompactTile(context, metadata, epsg, scale, row, col, format,
                                           (args[2].ToLower() == "ul" ? GridOrientation.UpperLeft : GridOrientation.LowerLeft), boundingTiles, renderOnTheFly);
                        }
                        else
                        {
                            GetTile(context, metadata, epsg, scale, row, col, format,
                                    (args[2].ToLower() == "ul" ? GridOrientation.UpperLeft : GridOrientation.LowerLeft), renderOnTheFly);
                        }
                    }
                    else
                    {
                        throw new ArgumentException();
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                if (context != null && context.ServiceRequest != null)
                {
                    context.ServiceRequest.Response = "<Exception>" + ex.Message + "</Exception>";
                }
            }
        }
Пример #21
0
 static public void SaveServiceCollection(string name, XmlStream stream)
 {
     stream.WriteStream(ServicesPath + @"\" + name + ".scl");
 }
Пример #22
0
        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...");
        }
Пример #23
0
        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...");
            }
        }