예제 #1
0
        private IEnvelope ClassEnvelope(IClass Class, ISpatialReference sRef)
        {
            IEnvelope         envelope  = null;
            ISpatialReference classSRef = null;

            if (Class is IFeatureClass)
            {
                envelope  = ((IFeatureClass)Class).Envelope;
                classSRef = ((IFeatureClass)Class).SpatialReference;
            }
            else if (Class is IRasterClass && ((IRasterClass)Class).Polygon != null)
            {
                envelope  = ((IRasterClass)Class).Polygon.Envelope;
                classSRef = ((IRasterClass)Class).SpatialReference;
            }

            if (envelope != null && classSRef != null && sRef != null && !sRef.Equals(classSRef))
            {
                using (var geometricTransformer = GeometricTransformerFactory.Create())
                {
                    geometricTransformer.SetSpatialReferences(classSRef, sRef);
                    IGeometry geom = geometricTransformer.Transform2D(envelope) as IGeometry;
                    if (geom == null)
                    {
                        return(null);
                    }

                    envelope = geom.Envelope;
                }
            }
            return(envelope);
        }
예제 #2
0
        public IGeometry Transform(IGeometry geometry, ISpatialReference geometrySpatialReference)
        {
            if (geometry == null)
            {
                return(null);
            }

            if (geometrySpatialReference == null || _spatialReference == null || geometrySpatialReference.Equals(_spatialReference))
            {
                return(geometry);
            }

            IGeometricTransformer transformer = GeometricTransformerFactory.Create();

            //transformer.FromSpatialReference = geometrySpatialReference;
            //transformer.ToSpatialReference = _spatialReference;
            transformer.SetSpatialReferences(geometrySpatialReference, _spatialReference);

            IGeometry geom = transformer.Transform2D(geometry) as IGeometry;

            transformer.Release();

            return(geom);
        }
예제 #3
0
        static void TestProj4()
        {
            var sRef4326 = SpatialReference.FromID("epsg:4326");

            var sRef31255 = SpatialReference.FromID("epsg:31255");
            var sRef31256 = SpatialReference.FromID("epsg:31256");
            var sRef3857  = SpatialReference.FromID("epsg:3857");
            var sRef23032 = new SpatialReference("test", "", "+proj=utm +zone=32 +ellps=intl +towgs84=-87,-98,-121,0,0,0,0 +units=m +no_defs ", null);

            using (var transformer = GeometricTransformerFactory.Create())
            {
                //var point = new Point(1443413.9574, 6133464.20414);
                ////var point = new Point(-27239.046, 335772.696625);
                //Console.WriteLine(point.X.ToString() + "    " + point.Y.ToString());

                //transformer.SetSpatialReferences(sRef3857, sRef4326);
                //point = (Point)transformer.Transform2D(point);
                //Console.WriteLine(point.X.ToString() + "    " + point.Y.ToString());

                var pCollection = new PointCollection();
                //pCollection.AddPoint(new Point(1443413.9574, 6133464.20414));
                pCollection.AddPoint(new Point(-27239.046, 335772.696625));
                Console.WriteLine(pCollection[0].X.ToString() + "    " + pCollection[0].Y.ToString());

                transformer.SetSpatialReferences(sRef31255, sRef3857);
                pCollection = (PointCollection)transformer.Transform2D(pCollection);
                Console.WriteLine(pCollection[0].X.ToString() + "    " + pCollection[0].Y.ToString());


                //transformer.SetSpatialReferences(sRef3857, sRef4326);
                //point = (Point)transformer.Transform2D(point);
                //Console.WriteLine(point.X.ToString() + "    " + point.Y.ToString());

                //transformer.SetSpatialReferences(sRef4326, sRef31255);
                //point = (Point)transformer.Transform2D(point);
                //Console.WriteLine(point.X.ToString() + "    " + point.Y.ToString());


                //var point = new Point(-27239.046, 335772.696625);

                //Console.WriteLine(point.X.ToString() + "    " + point.Y.ToString());

                //transformer.SetSpatialReferences(sRef31255, sRef23032);
                //var point2 = (Point)transformer.Transform2D(point);

                //Console.WriteLine(point2.X.ToString() + "    " + point2.Y.ToString());

                //transformer.SetSpatialReferences(sRef31255, sRef31256);
                //point2 = (Point)transformer.Transform2D(point);

                //Console.WriteLine(point2.X.ToString() + "    " + point2.Y.ToString());

                //transformer.SetSpatialReferences(sRef31256, sRef3857);
                //point=(Point)transformer.Transform2D(point);

                //Console.WriteLine(point.X.ToString() + "    " + point.Y.ToString());

                //transformer.SetSpatialReferences(sRef4326, sRef3857);
                //point = (Point)transformer.Transform2D(point);

                //Console.WriteLine(point.X.ToString() + "    " + point.Y.ToString());
            }
        }
예제 #4
0
        async override public Task <bool> RefreshMap(DrawPhase phase, ICancelTracker cancelTracker)
        {
            base.ResetRequestExceptions();

            if (_canvas != null && phase == DrawPhase.Graphics)
            {
                return(true);
            }

            this.ZoomTo(m_actMinX, m_actMinY, m_actMaxX, m_actMaxY);

            if (cancelTracker == null)
            {
                cancelTracker = new CancelTracker();
            }

            using (var datasetCachingContext = new DatasetCachingContext(this))
                using (var geoTransformer = GeometricTransformerFactory.Create())
                {
                    //geoTransformer.ToSpatialReference = this.SpatialReference;

                    if (_bitmap == null)
                    {
                        _bitmap = Current.Engine.CreateBitmap(iWidth, iHeight, PixelFormat.Rgba32);
                    }

                    _canvas = _bitmap.CreateCanvas();
                    //_canvas.CompositingMode = CompositingMode.SourceCopy;
                    //this.dpi = _canvas.DpiX * this.ScaleSymbolFactor;

                    if (BackgroundColor.A != 0 && !Display.MakeTransparent)
                    {
                        using (var brush = Current.Engine.CreateSolidBrush(BackgroundColor))
                        {
                            _canvas.FillRectangle(brush, new CanvasRectangle(0, 0, _bitmap.Width, _bitmap.Height));
                        }
                    }

                    if (phase == DrawPhase.All || phase == DrawPhase.Geography)
                    {
                        this.GeometricTransformer = geoTransformer;

                        // Thread für MapServer Datasets starten...

                        #region WebServiceLayer
                        List <IWebServiceLayer> webServices;
                        if (this.TOC != null)
                        {
                            webServices = ListOperations <IWebServiceLayer> .Swap(this.TOC.VisibleWebServiceLayers);
                        }
                        else
                        {
                            webServices = new List <IWebServiceLayer>();
                            foreach (IDatasetElement layer in this.MapElements)
                            {
                                if (!(layer is IWebServiceLayer))
                                {
                                    continue;
                                }

                                if (((ILayer)layer).Visible)
                                {
                                    webServices.Add((IWebServiceLayer)layer);
                                }
                            }
                        }
                        int webServiceOrder = 0, webServiceOrder2 = 1;
                        foreach (IWebServiceLayer element in webServices)
                        {
                            if (!element.Visible)
                            {
                                continue;
                            }

                            IWebServiceLayer wsLayer = LayerFactory.Create(element.WebServiceClass.Clone() as IClass, element) as IWebServiceLayer;

                            if (wsLayer == null || wsLayer.WebServiceClass == null)
                            {
                                continue;
                            }

                            wsLayer.WebServiceClass.SpatialReference = this.SpatialReference;

                            List <IWebServiceClass> additionalWebServices = new List <IWebServiceClass>();
                            if (BeforeRenderLayers != null)
                            {
                                List <ILayer> modLayers = new List <ILayer>();
                                foreach (IWebServiceTheme theme in wsLayer.WebServiceClass.Themes)
                                {
                                    if (theme is ILayer)
                                    {
                                        modLayers.Add(theme);
                                    }
                                }
                                BeforeRenderLayers(this, modLayers);

                                foreach (ILayer additionalLayer in MapServerHelper.FindAdditionalWebServiceLayers(wsLayer.WebServiceClass, modLayers))
                                {
                                    IWebServiceClass additionalWebService = MapServerHelper.CloneNonVisibleWebServiceClass(wsLayer.WebServiceClass);
                                    MapServerHelper.CopyWebThemeProperties(additionalWebService, additionalLayer);

                                    if (MapServerHelper.HasVisibleThemes(additionalWebService))
                                    {
                                        additionalWebServices.Add(additionalWebService);
                                    }
                                }
                            }


                            var srt = new RenderServiceRequest(this, wsLayer, webServiceOrder++);
                            srt.finish += new RenderServiceRequest.RequestThreadFinished(MapRequestThread_finished);
                            //Thread thread = new Thread(new ThreadStart(srt.ImageRequest));
                            m_imageMerger.max++;
                            //thread.Start();
                            var task = srt.ImageRequest(); // start Task and continue...


                            foreach (IWebServiceClass additionalWebService in additionalWebServices)
                            {
                                wsLayer = LayerFactory.Create(additionalWebService, element) as IWebServiceLayer;
                                if (wsLayer == null || wsLayer.WebServiceClass == null)
                                {
                                    continue;
                                }

                                wsLayer.WebServiceClass.SpatialReference = this.SpatialReference;

                                srt         = new RenderServiceRequest(this, wsLayer, (++webServiceOrder2) + webServices.Count);
                                srt.finish += new RenderServiceRequest.RequestThreadFinished(MapRequestThread_finished);
                                //thread = new Thread(new ThreadStart(srt.ImageRequest));
                                m_imageMerger.max++;
                                //thread.Start();
                                var additionalTask = srt.ImageRequest(); // start task and continue...
                            }
                        }
                        #endregion

                        List <ILayer> layers = new List <ILayer>();
                        if (this.TOC != null)
                        {
                            if (this.GetType().Equals(typeof(ServiceMap)))
                            {
                                layers = ListOperations <ILayer> .Swap(this.TOC.Layers);
                            }
                            else
                            {
                                layers = ListOperations <ILayer> .Swap(this.TOC.VisibleLayers);
                            }
                        }
                        else
                        {
                            layers = new List <ILayer>();
                            foreach (IDatasetElement layer in this.MapElements)
                            {
                                if (!(layer is ILayer))
                                {
                                    continue;
                                }

                                if (((ILayer)layer).Visible)
                                {
                                    layers.Add((ILayer)layer);
                                }
                            }
                        }

                        if (BeforeRenderLayers != null)
                        {
                            //
                            // Kopie der Original Layer erstellen
                            // ACHTUNG: Renderer werden nicht kopiert!
                            // dürfen in BeforeRenderLayers nicht verändert werden...
                            // Eine zuweisung eines neuen Renderers ist jedoch legitim.
                            //
                            List <ILayer> modLayers = new List <ILayer>();
                            foreach (IDatasetElement element in layers)
                            {
                                if (!(element is ILayer) || element is IWebServiceTheme)
                                {
                                    continue;
                                }

                                ILayer layer = (ILayer)element;
                                if (layer.MinimumScale > 1 && layer.MinimumScale > this.mapScale)
                                {
                                    continue;
                                }

                                if (layer.MaximumScale > 1 && layer.MaximumScale < this.mapScale)
                                {
                                    continue;
                                }

                                modLayers.Add(LayerFactory.Create(layer.Class, layer));
                            }
                            BeforeRenderLayers(this, modLayers);
                            layers = modLayers;
                        }
                        //layers = ModifyLayerList(layers);
                        List <IFeatureLayer> labelLayers = this.OrderedLabelLayers(layers);

                        LabelEngine.Init(this.Display, false);
                        foreach (IDatasetElement element in layers)
                        {
                            if (!cancelTracker.Continue)
                            {
                                break;
                            }

                            if (!(element is ILayer))
                            {
                                continue;
                            }

                            ILayer layer = (ILayer)element;

                            //if (_ceckLayerVisibilityBeforeDrawing)
                            //{
                            //    if (!LayerIsVisible(layer)) continue;
                            //}
                            if (!layer.Visible)
                            {
                                continue;
                            }

                            if (!layer.RenderInScale(this))
                            {
                                continue;
                            }
#if (DEBUG)
                            //Logger.LogDebug("Drawing Layer:" + element.Title);
#endif
                            SetGeotransformer((ILayer)element, geoTransformer);

                            if (layer is IFeatureLayer)
                            {
                                if (layer.Class?.Dataset is IFeatureCacheDataset)
                                {
                                    await((IFeatureCacheDataset)layer.Class.Dataset).InitFeatureCache(datasetCachingContext);
                                }

                                IFeatureLayer fLayer = (IFeatureLayer)layer;
                                if (fLayer.FeatureRenderer == null &&
                                    (
                                        fLayer.LabelRenderer == null ||
                                        (fLayer.LabelRenderer != null && fLayer.LabelRenderer.RenderMode != LabelRenderMode.RenderWithFeature)
                                    ))
                                {
                                    //continue;
                                }
                                else
                                {
                                    RenderFeatureLayer rlt = new RenderFeatureLayer(this, datasetCachingContext, fLayer, cancelTracker, new FeatureCounter());
                                    if (fLayer.LabelRenderer != null && fLayer.LabelRenderer.RenderMode == LabelRenderMode.RenderWithFeature)
                                    {
                                        rlt.UseLabelRenderer = true;
                                    }
                                    else
                                    {
                                        rlt.UseLabelRenderer = labelLayers.IndexOf(fLayer) == 0; // letzten Layer gleich mitlabeln
                                    }

                                    if (rlt.UseLabelRenderer)
                                    {
                                        labelLayers.Remove(fLayer);
                                    }

                                    await rlt.Render();
                                }
                                //thread = new Thread(new ThreadStart(rlt.Render));
                                //thread.Start();
                            }
                            if (layer is IRasterLayer && ((IRasterLayer)layer).RasterClass != null)
                            {
                                IRasterLayer rLayer = (IRasterLayer)layer;
                                if (rLayer.RasterClass.Polygon == null)
                                {
                                    continue;
                                }

                                IEnvelope dispEnvelope = this.Envelope;
                                if (Display.GeometricTransformer != null)
                                {
                                    dispEnvelope = ((IGeometry)Display.GeometricTransformer.InvTransform2D(dispEnvelope)).Envelope;
                                }

                                if (gView.Framework.SpatialAlgorithms.Algorithm.IntersectBox(rLayer.RasterClass.Polygon, dispEnvelope))
                                {
                                    if (rLayer.Class is IParentRasterLayer)
                                    {
                                        await DrawRasterParentLayer((IParentRasterLayer)rLayer.Class, cancelTracker, rLayer);
                                    }
                                    else
                                    {
                                        RenderRasterLayer rlt = new RenderRasterLayer(this, rLayer, rLayer, cancelTracker);
                                        await rlt.Render();

                                        //thread = new Thread(new ThreadStart(rlt.Render));
                                        //thread.Start();
                                    }
                                }
                            }
                            // Andere Layer (zB IRasterLayer)

#if (DEBUG)
                            //Logger.LogDebug("Finished drawing layer: " + element.Title);
#endif
                        }

                        // Label Features
                        if (labelLayers.Count != 0)
                        {
                            foreach (IFeatureLayer fLayer in labelLayers)
                            {
                                this.SetGeotransformer(fLayer, geoTransformer);

                                if (!fLayer.Visible)
                                {
                                    continue;
                                }

                                RenderLabel rlt = new RenderLabel(this, fLayer, cancelTracker, new FeatureCounter());
                                await rlt.Render();
                            }
                        }

                        LabelEngine.Draw(this.Display, cancelTracker);
                        LabelEngine.Release();

                        if (cancelTracker.Continue)
                        {
                            while (m_imageMerger.Count < m_imageMerger.max)
                            {
                                await Task.Delay(10);
                            }
                        }
                        if (_drawScaleBar)
                        {
                            m_imageMerger.mapScale = this.mapScale;
                            m_imageMerger.dpi      = this.dpi;
                        }
#if (DEBUG)
                        //Logger.LogDebug("Merge Images");
#endif
                        m_imageMerger.Merge(_bitmap, this.Display);
                        m_imageMerger.Clear();
#if (DEBUG)
                        //Logger.LogDebug("Merge Images Finished");
#endif
                    }

                    if (phase == DrawPhase.All || phase == DrawPhase.Graphics)
                    {
                        foreach (IGraphicElement grElement in Display.GraphicsContainer.Elements)
                        {
                            grElement.Draw(Display);
                        }
                    }

                    base.AppendRequestExceptionsToImage();

                    if (_canvas != null)
                    {
                        _canvas.Dispose();
                    }

                    _canvas = null;

                    this.GeometricTransformer = null;
                }

            return(this.HasRequestExceptions == false);
        }
예제 #5
0
        async public Task <bool> ImportToNewFeatureclass(IFeatureDatabase fdb, string dsname, string fcname, IFeatureClass sourceFC, FieldTranslation fieldTranslation, bool project, List <IQueryFilter> filters, ISpatialIndexDef sIndexDef, geometryType?sourceGeometryType = null)
        {
            if (!_cancelTracker.Continue)
            {
                return(true);
            }

            if (fdb is AccessFDB)
            {
                ISpatialIndexDef dsSpatialIndexDef = await((AccessFDB)fdb).SpatialIndexDef(dsname);
                if (sIndexDef == null)
                {
                    sIndexDef = dsSpatialIndexDef;
                }
                else if (sIndexDef.GeometryType != dsSpatialIndexDef.GeometryType)
                {
                    _errMsg = "Spatial-Index-Definition-GeometryTypes are not compatible!";
                    return(false);
                }
            }
            if (sIndexDef == null)
            {
                sIndexDef = new gViewSpatialIndexDef();
            }

            bool msSpatial = false;

            if (fdb is SqlFDB &&
                (sIndexDef.GeometryType == GeometryFieldType.MsGeography ||
                 sIndexDef.GeometryType == GeometryFieldType.MsGeometry))
            {
                msSpatial = true;
            }
            else
            {
                int maxAllowedLevel = ((fdb is SqlFDB || fdb is pgFDB) ? 62 : 30);
                if (sIndexDef.Levels > maxAllowedLevel)
                {
                    ISpatialReference defSRef = sIndexDef.SpatialReference;
                    sIndexDef = new gViewSpatialIndexDef(
                        sIndexDef.SpatialIndexBounds,
                        Math.Min(sIndexDef.Levels, maxAllowedLevel),
                        sIndexDef.MaxPerNode,
                        sIndexDef.SplitRatio);
                    ((gViewSpatialIndexDef)sIndexDef).SpatialReference = defSRef;
                }
            }

            try
            {
                fcname = fcname.Replace(".", "_");

                IFeatureDataset destDS = await fdb.GetDataset(dsname);

                if (destDS == null)
                {
                    _errMsg = fdb.LastErrorMessage;
                    return(false);
                }

                IDatasetElement destLayer = await destDS.Element(fcname);

                if (destLayer != null)
                {
                    if (ReportRequest != null)
                    {
                        RequestArgs args = new RequestArgs(
                            "Featureclass " + fcname + " already exists in " + dsname + "\nDo want to replace it?",
                            MessageBoxButtons.YesNoCancel,
                            DialogResult.Cancel);
                        ReportRequest(this, args);
                        switch (args.Result)
                        {
                        case DialogResult.No:
                            return(true);

                        case DialogResult.Cancel:
                            _errMsg = "Import is canceled by the user...";
                            return(false);
                        }
                    }
                }

                GeometryDef geomDef = new GeometryDef(sourceFC);
                if (geomDef.GeometryType == geometryType.Unknown && sourceGeometryType != null)
                {
                    geomDef.GeometryType = sourceGeometryType.Value;
                }

                int fcID = -1;
                if (destLayer != null)
                {
                    if (fdb is AccessFDB)
                    {
                        fcID = await((AccessFDB)fdb).ReplaceFeatureClass(destDS.DatasetName,
                                                                         fcname,
                                                                         geomDef,
                                                                         (fieldTranslation == null) ?
                                                                         ((sourceFC.Fields != null) ? (IFields)sourceFC.Fields.Clone() : new Fields()) :
                                                                         fieldTranslation.DestinationFields);
                        if (fcID < 0)
                        {
                            _errMsg = "Can't replace featureclass " + fcname + "...\r\n" + fdb.LastErrorMessage;
                            destDS.Dispose();
                            return(false);
                        }
                    }
                    else
                    {
                        await fdb.DeleteFeatureClass(fcname);
                    }
                }
                if (fcID < 0)
                {
                    fcID = await fdb.CreateFeatureClass(destDS.DatasetName,
                                                        fcname,
                                                        geomDef,
                                                        (fieldTranslation == null)?
                                                        ((sourceFC.Fields != null) ? (IFields)sourceFC.Fields.Clone() : new Fields()) :
                                                        fieldTranslation.DestinationFields);
                }
                if (fcID < 0)
                {
                    _errMsg = "Can't create featureclass " + fcname + "...\r\n" + fdb.LastErrorMessage;
                    destDS.Dispose();
                    return(false);
                }

                destLayer = await destDS.Element(fcname);

                if (destLayer == null || !(destLayer.Class is IFeatureClass))
                {
                    _errMsg = "Can't load featureclass " + fcname + "...\r\n" + destDS.LastErrorMessage;
                    destDS.Dispose();
                    return(false);
                }
                IFeatureClass destFC = destLayer.Class as IFeatureClass;

                if (project && destFC.SpatialReference != null && !destFC.SpatialReference.Equals(sourceFC.SpatialReference))
                {
                    _transformer = GeometricTransformerFactory.Create();
                    //_transformer.FromSpatialReference = sourceFC.SpatialReference;
                    //_transformer.ToSpatialReference = destFC.SpatialReference;
                    _transformer.SetSpatialReferences(sourceFC.SpatialReference, destFC.SpatialReference);
                }

                if (!Envelope.IsNull(sIndexDef.SpatialIndexBounds) &&
                    sIndexDef.SpatialReference != null && !sIndexDef.SpatialReference.Equals(destFC.SpatialReference))
                {
                    if (!sIndexDef.ProjectTo(destFC.SpatialReference))
                    {
                        _errMsg = "Can't project SpatialIndex Boundaries...";
                        destDS.Dispose();
                        return(false);
                    }
                }

                DualTree           tree  = null;
                BinaryTree2Builder tree2 = null;

                if (msSpatial)
                {
                    ((SqlFDB)fdb).SetMSSpatialIndex((MSSpatialIndex)sIndexDef, destFC.Name);
                    await((SqlFDB)fdb).SetFeatureclassExtent(destFC.Name, sIndexDef.SpatialIndexBounds);
                }
                else
                {
                    if (_treeVersion == TreeVersion.BinaryTree)
                    {
                        tree = await SpatialIndex(sourceFC, sIndexDef.MaxPerNode, filters);

                        if (tree == null)
                        {
                            return(false);
                        }
                    }
                    else if (_treeVersion == TreeVersion.BinaryTree2)
                    {
                        if (_schemaOnly && sourceFC.Dataset.Database is IImplementsBinarayTreeDef)
                        {
                            BinaryTreeDef tDef = await((IImplementsBinarayTreeDef)sourceFC.Dataset.Database).BinaryTreeDef(sourceFC.Name);
                            tree2 = new BinaryTree2Builder(tDef.Bounds, tDef.MaxLevel, tDef.MaxPerNode, tDef.SplitRatio);
                        }
                        else
                        {
                            tree2 = await SpatialIndex2(fdb, sourceFC, sIndexDef, filters);

                            if (tree2 == null)
                            {
                                return(false);
                            }
                        }
                    }

                    // Vorab einmal alle "Bounds" festlegen, damit auch
                    // ein aufzubauender Layer geviewt werden kann
                    if (_treeVersion == TreeVersion.BinaryTree2 && fdb is AccessFDB)
                    {
                        if (ReportAction != null)
                        {
                            ReportAction(this, "Insert spatial index nodes");
                        }
                        List <long> nids = new List <long>();
                        foreach (BinaryTree2BuilderNode node in tree2.Nodes)
                        {
                            nids.Add(node.Number);
                        }
                        await((AccessFDB)fdb).ShrinkSpatialIndex(fcname, nids);

                        if (ReportAction != null)
                        {
                            ReportAction(this, "Set spatial index bounds");
                        }
                        //((AccessFDB)fdb).SetSpatialIndexBounds(fcname, "BinaryTree2", tree2.Bounds, sIndexDef.SplitRatio, sIndexDef.MaxPerNode, tree2.maxLevels);
                        await((AccessFDB)fdb).SetSpatialIndexBounds(fcname, "BinaryTree2", tree2.Bounds, tree2.SplitRatio, tree2.MaxPerNode, tree2.maxLevels);
                        await((AccessFDB)fdb).SetFeatureclassExtent(fcname, tree2.Bounds);
                    }
                }
                if (_cancelTracker.Continue)
                {
                    bool result = true;
                    if (!_schemaOnly)
                    {
                        if (msSpatial)
                        {
                            result = await CopyFeatures(sourceFC, fdb, destFC, fieldTranslation, filters);
                        }
                        else if (_treeVersion == TreeVersion.BinaryTree)
                        {
                            if (String.IsNullOrEmpty(sourceFC.IDFieldName)) // SDE Views haben keine ID -> Tree enthält keine Features
                            {
                                result = await CopyFeatures(sourceFC, fdb, destFC, fieldTranslation, filters);
                            }
                            else
                            {
                                result = await CopyFeatures(sourceFC, fdb, destFC, fieldTranslation, tree);
                            }
                        }
                        else if (_treeVersion == TreeVersion.BinaryTree2)
                        {
                            if (String.IsNullOrEmpty(sourceFC.IDFieldName)) // SDE Views haben keine ID -> Tree enthält keine Features
                            {
                                result = await CopyFeatures(sourceFC, fdb, destFC, fieldTranslation, filters);
                            }
                            else
                            {
                                result = await CopyFeatures2(sourceFC, fdb, destFC, fieldTranslation, tree2);
                            }
                        }
                        if (!result)
                        {
                            await fdb.DeleteFeatureClass(fcname);

                            destDS.Dispose();
                            return(false);
                        }
                    }
                }

                destDS.Dispose();

                if (_cancelTracker.Continue && fdb is AccessFDB)
                {
                    if (ReportAction != null)
                    {
                        ReportAction(this, "Calculate extent");
                    }
                    await((AccessFDB)fdb).CalculateExtent(destFC);

                    if (msSpatial == false)
                    {
                        if (_treeVersion == TreeVersion.BinaryTree)
                        {
                            if (ReportAction != null)
                            {
                                ReportAction(this, "Set spatial index bounds");
                            }
                            await((AccessFDB)fdb).SetSpatialIndexBounds(fcname, "BinaryTree", tree.Bounds, sIndexDef.SplitRatio, sIndexDef.MaxPerNode, 0);

                            if (ReportAction != null)
                            {
                                ReportAction(this, "Insert spatial index nodes");
                            }
                            await((AccessFDB)fdb).__intInsertSpatialIndexNodes2(fcname, tree.Nodes);
                        }
                    }
                    return(true);
                }
                else
                {
                    await fdb.DeleteFeatureClass(fcname);

                    _errMsg = "Import is canceled by the user...";
                    return(false);
                }
            }
            finally
            {
                if (_transformer != null)
                {
                    _transformer.Release();
                    _transformer = null;
                }
            }
        }
예제 #6
0
        private void cmbEpsg_SelectedIndexChanged(object sender, EventArgs e)
        {
            lstScales.Items.Clear();

            if (_metadata == null)
            {
                return;
            }

            ISpatialReference sRef = SpatialReference.FromID("epsg:" + cmbEpsg.SelectedItem.ToString());

            if (sRef == null)
            {
                return;
            }

            IEnvelope extent = _metadata.GetEPSGEnvelope((int)cmbEpsg.SelectedItem);

            if (extent == null)
            {
                return;
            }

            double width  = extent.Width;
            double height = extent.Height;

            double dpu = 1.0;

            if (sRef.SpatialParameters.IsGeographic)
            {
                GeoUnitConverter converter = new GeoUnitConverter();
                dpu = converter.Convert(1.0, GeoUnits.Meters, GeoUnits.DecimalDegrees);
            }

            foreach (double scale in _metadata.Scales)
            {
                double tileWidth  = (double)_metadata.TileWidth * (double)scale / (96.0 / 0.0254);
                double tileHeight = (double)_metadata.TileHeight * (double)scale / (96.0 / 0.0254);

                tileWidth  *= dpu;
                tileHeight *= dpu;

                int tx = (int)Math.Floor(width / tileWidth) + 1;
                int ty = (int)Math.Floor(height / tileHeight) + 1;

                lstScales.Items.Add(new ListViewItem(new string[] { scale.ToString(_nhi), ty.ToString(), tx.ToString(), (tx * ty).ToString() }));
                lstScales.Items[lstScales.Items.Count - 1].Checked = true;
            }

            if (!Envelope.IsNull(this.CurrentExtent) &&
                cmbEpsg.SelectedItem != null)
            {
                ISpatialReference oldSRef = SpatialReference.FromID(lblEpsg.Text.Replace("(", "").Replace(")", ""));
                ISpatialReference newSRef = SpatialReference.FromID("epsg:" + cmbEpsg.SelectedItem.ToString());

                using (var geometricTransformer = GeometricTransformerFactory.Create())
                {
                    geometricTransformer.SetSpatialReferences(oldSRef, newSRef);
                    IGeometry geom = geometricTransformer.Transform2D(this.CurrentExtent) as IGeometry;
                    if (geom != null)
                    {
                        this.CurrentExtent = geom.Envelope;
                    }
                }
            }
            lblEpsg.Text = "(EPSG:" + (cmbEpsg.SelectedItem != null ? cmbEpsg.SelectedItem.ToString() : "0") + ")";
        }
예제 #7
0
        async private Task <bool> ImportToNewFeatureclass(IFeatureDataset destDS, string fcname, IFeatureClass sourceFC, FieldTranslation fieldTranslation, bool project, List <IQueryFilter> filters, DatasetNameCase namecase, geometryType?sourceGeometryType = null)
        {
            if (!_cancelTracker.Continue)
            {
                return(true);
            }

            switch (namecase)
            {
            case DatasetNameCase.upper:
                fcname = fcname.ToUpper();
                fieldTranslation.ToUpper();
                break;

            case DatasetNameCase.lower:
                fcname = fcname.ToLower();
                fieldTranslation.ToLower();
                break;

            case DatasetNameCase.classNameUpper:
                fcname = fcname.ToUpper();
                break;

            case DatasetNameCase.classNameLower:
                fcname = fcname.ToLower();
                break;

            case DatasetNameCase.fieldNamesUpper:
                fieldTranslation.ToUpper();
                break;

            case DatasetNameCase.fieldNamesLower:
                fieldTranslation.ToLower();
                break;
            }
            try
            {
                fcname = fcname.Replace(".", "_");

                if (destDS == null)
                {
                    _errMsg = "Argument Exception";
                    return(false);
                }
                IFeatureDatabase fdb = destDS.Database as IFeatureDatabase;
                if (!(fdb is IFeatureUpdater))
                {
                    _errMsg = "Database don't implement IFeatureUpdater...";
                    return(false);
                }

                IDatasetElement destLayer = await destDS.Element(fcname);

                if (destLayer != null)
                {
                    if (ReportRequest != null)
                    {
                        RequestArgs args = new RequestArgs(
                            "Featureclass " + fcname + " already exists in database\nDo want to replace it?",
                            MessageBoxButtons.YesNoCancel,
                            DialogResult.Cancel);
                        ReportRequest(this, args);
                        switch (args.Result)
                        {
                        case DialogResult.No:
                            return(true);

                        case DialogResult.Cancel:
                            _errMsg = "Import is canceled by the user...";
                            return(false);
                        }
                    }
                }

                if (destLayer != null)
                {
                    await fdb.DeleteFeatureClass(fcname);
                }

                GeometryDef geomDef = new GeometryDef(sourceFC);
                if (geomDef.GeometryType == geometryType.Unknown && sourceGeometryType != null)
                {
                    geomDef.GeometryType = sourceGeometryType.Value;
                }

                int fcID = await fdb.CreateFeatureClass(destDS.DatasetName,
                                                        fcname,
                                                        geomDef,
                                                        (fieldTranslation == null)?
                                                        ((sourceFC.Fields != null) ? (IFields)sourceFC.Fields.Clone() : new Fields()) :
                                                        fieldTranslation.DestinationFields);

                if (fcID < 0)
                {
                    _errMsg = "Can't create featureclass " + fcname + "...\r\n" + fdb.LastErrorMessage;
                    destDS.Dispose();
                    return(false);
                }

                destLayer = await destDS.Element(fcname);

                if (destLayer == null || !(destLayer.Class is IFeatureClass))
                {
                    _errMsg = "Can't load featureclass " + fcname + "...\r\n" + destDS.LastErrorMessage;
                    destDS.Dispose();
                    return(false);
                }
                IFeatureClass destFC = destLayer.Class as IFeatureClass;

                if (project && destFC.SpatialReference != null && !destFC.SpatialReference.Equals(sourceFC.SpatialReference))
                {
                    _transformer = GeometricTransformerFactory.Create();
                    //_transformer.FromSpatialReference = sourceFC.SpatialReference;
                    //_transformer.ToSpatialReference = destFC.SpatialReference;
                    _transformer.SetSpatialReferences(sourceFC.SpatialReference, destFC.SpatialReference);
                }

                var importBufferSizeAttribute = destFC.GetType().GetCustomAttribute <ImportFeaturesBufferSizeAttribute>();
                if (importBufferSizeAttribute != null && importBufferSizeAttribute.BufferSize > 0)
                {
                    this.FeatureBufferSize = importBufferSizeAttribute.BufferSize;
                }

                if (_cancelTracker.Continue)
                {
                    bool result = true;

                    if (fdb is IFeatureImportEvents)
                    {
                        ((IFeatureImportEvents)fdb).BeforeInsertFeaturesEvent(sourceFC, destFC);
                    }

                    if (!_schemaOnly)
                    {
                        result = await CopyFeatures(sourceFC, fdb, destFC, fieldTranslation, filters);
                    }
                    if (!result)
                    {
                        await fdb.DeleteFeatureClass(fcname);

                        destDS.Dispose();
                        return(false);
                    }

                    if (fdb is IFeatureImportEvents)
                    {
                        ((IFeatureImportEvents)fdb).AfterInsertFeaturesEvent(sourceFC, destFC);
                    }
                }

                if (fdb is IFileFeatureDatabase)
                {
                    if (!((IFileFeatureDatabase)fdb).Flush(destFC))
                    {
                        _errMsg = "Error executing flush for file database..." + fdb.LastErrorMessage;
                        return(false);
                    }
                }
                destDS.Dispose();

                if (_cancelTracker.Continue)
                {
                    return(true);
                }
                else
                {
                    await fdb.DeleteFeatureClass(fcname);

                    _errMsg = "Import is canceled by the user...";
                    return(false);
                }
            }
            finally
            {
                if (_transformer != null)
                {
                    _transformer.Release();
                    _transformer = null;
                }
            }
        }
예제 #8
0
        async override public Task <bool> RefreshMap(DrawPhase phase, ICancelTracker cancelTracker)
        {
            base.ResetRequestExceptions();
            bool printerMap = (this.GetType() == typeof(PrinterMap));

            try
            {
                _original.FireStartRefreshMap();

                using (var datasetCachingContext = new DatasetCachingContext(this))
                {
                    this.IsRefreshing = true;

                    _lastException = null;

                    if (_canvas != null && phase == DrawPhase.Graphics)
                    {
                        return(true);
                    }

                    #region Start Drawing/Initialisierung

                    this.ZoomTo(m_actMinX, m_actMinY, m_actMaxX, m_actMaxY);

                    if (cancelTracker == null)
                    {
                        cancelTracker = new CancelTracker();
                    }

                    IGeometricTransformer geoTransformer = GeometricTransformerFactory.Create();

                    //geoTransformer.ToSpatialReference = this.SpatialReference;
                    if (!printerMap)
                    {
                        if (phase == DrawPhase.All)
                        {
                            DisposeStreams();
                        }

                        if (_bitmap != null && (_bitmap.Width != iWidth || _bitmap.Height != iHeight))
                        {
                            if (!DisposeImage())
                            {
                                return(false);
                            }
                        }

                        if (_bitmap == null)
                        {
                            //DisposeStreams();
                            _bitmap = GraphicsEngine.Current.Engine.CreateBitmap(iWidth, iHeight, GraphicsEngine.PixelFormat.Rgba32);
                            //if (NewBitmap != null && cancelTracker.Continue) NewBitmap(_image);
                        }

                        _canvas = _bitmap.CreateCanvas();
                        //this.dpi = /*96f*/ /* _canvas.DpiX*/ GraphicsEngine.Current.Engine.ScreenDpi;

                        // NewBitmap immer aufrufen, da sonst neuer DataView nix mitbekommt
                        if (NewBitmap != null && cancelTracker.Continue)
                        {
                            NewBitmap?.BeginInvoke(_bitmap, new AsyncCallback(AsyncInvoke.RunAndForget), null);
                        }

                        using (var brush = GraphicsEngine.Current.Engine.CreateSolidBrush(_backgroundColor))
                        {
                            _canvas.FillRectangle(brush, new GraphicsEngine.CanvasRectangle(0, 0, iWidth, iHeight));
                        }
                    }

                    #endregion

                    #region Geometry

                    if (Bit.Has(phase, DrawPhase.Geography))
                    //if (phase == DrawPhase.All || phase == DrawPhase.Geography)
                    {
                        LabelEngine.Init(this.Display, printerMap);

                        this.GeometricTransformer = geoTransformer;

                        // Thread für MapServer Datasets starten...
                        #region WebServiceLayer
                        List <IWebServiceLayer> webServices;
                        if (this.TOC != null)
                        {
                            webServices = ListOperations <IWebServiceLayer> .Swap(this.TOC.VisibleWebServiceLayers);
                        }
                        else
                        {
                            webServices = new List <IWebServiceLayer>();
                            foreach (IDatasetElement layer in this.MapElements)
                            {
                                if (!(layer is IWebServiceLayer))
                                {
                                    continue;
                                }

                                if (((ILayer)layer).Visible)
                                {
                                    webServices.Add((IWebServiceLayer)layer);
                                }
                            }
                        }
                        int webServiceOrder = 0;
                        foreach (IWebServiceLayer element in webServices)
                        {
                            if (!element.Visible)
                            {
                                continue;
                            }

                            RenderServiceRequest srt = new RenderServiceRequest(this, element, webServiceOrder++);
                            srt.finish += new RenderServiceRequest.RequestThreadFinished(MapRequestThread_finished);
                            //Thread thread = new Thread(new ThreadStart(srt.ImageRequest));
                            m_imageMerger.max++;
                            //thread.Start();
                            var task = srt.ImageRequest();  // start the task...
                        }
                        #endregion

                        #region Layerlisten erstellen
                        List <ILayer> layers;
                        if (this.TOC != null)
                        {
                            if (this.ToString() == "gView.MapServer.Instance.ServiceMap")
                            {
                                layers = ListOperations <ILayer> .Swap(this.TOC.Layers);
                            }
                            else
                            {
                                layers = ListOperations <ILayer> .Swap(this.TOC.VisibleLayers);
                            }
                        }
                        else
                        {
                            layers = new List <ILayer>();
                            foreach (IDatasetElement layer in this.MapElements)
                            {
                                if (!(layer is ILayer))
                                {
                                    continue;
                                }

                                if (((ILayer)layer).Visible)
                                {
                                    layers.Add((ILayer)layer);
                                }
                            }
                        }

                        List <IFeatureLayer> labelLayers = this.OrderedLabelLayers(layers);

                        #endregion

                        #region Renderer Features

                        foreach (ILayer layer in layers)
                        {
                            if (!cancelTracker.Continue)
                            {
                                break;
                            }

                            if (!layer.RenderInScale(this))
                            {
                                continue;
                            }

                            SetGeotransformer(layer, geoTransformer);

                            DateTime startTime = DateTime.Now;

                            FeatureCounter fCounter = new FeatureCounter();
                            if (layer is IFeatureLayer)
                            {
                                if (layer.Class?.Dataset is IFeatureCacheDataset)
                                {
                                    await((IFeatureCacheDataset)layer.Class.Dataset).InitFeatureCache(datasetCachingContext);
                                }

                                IFeatureLayer fLayer = (IFeatureLayer)layer;
                                if (fLayer.FeatureRenderer == null &&
                                    (
                                        fLayer.LabelRenderer == null ||
                                        (fLayer.LabelRenderer != null && fLayer.LabelRenderer.RenderMode != LabelRenderMode.RenderWithFeature)
                                    ))
                                {
                                    //continue;
                                }
                                else
                                {
                                    RenderFeatureLayer rlt = new RenderFeatureLayer(this, datasetCachingContext, fLayer, cancelTracker, fCounter);
                                    if (fLayer.LabelRenderer != null && fLayer.LabelRenderer.RenderMode == LabelRenderMode.RenderWithFeature)
                                    {
                                        rlt.UseLabelRenderer = true;
                                    }
                                    else
                                    {
                                        rlt.UseLabelRenderer = labelLayers.IndexOf(fLayer) == 0;  // letzten Layer gleich mitlabeln
                                    }

                                    if (rlt.UseLabelRenderer)
                                    {
                                        labelLayers.Remove(fLayer);
                                    }

                                    if (cancelTracker.Continue)
                                    {
                                        DrawingLayer?.BeginInvoke(layer.Title, new AsyncCallback(AsyncInvoke.RunAndForget), null);
                                    }

                                    await rlt.Render();
                                }
                            }
                            if (layer is IRasterLayer && ((IRasterLayer)layer).RasterClass != null)
                            {
                                IRasterLayer rLayer = (IRasterLayer)layer;
                                if (rLayer.RasterClass.Polygon == null)
                                {
                                    continue;
                                }

                                IEnvelope dispEnvelope = this.DisplayTransformation.TransformedBounds(this); //this.Envelope;
                                if (Display.GeometricTransformer != null)
                                {
                                    dispEnvelope = ((IGeometry)Display.GeometricTransformer.InvTransform2D(dispEnvelope)).Envelope;
                                }

                                if (gView.Framework.SpatialAlgorithms.Algorithm.IntersectBox(rLayer.RasterClass.Polygon, dispEnvelope))
                                {
                                    if (rLayer.Class is IParentRasterLayer)
                                    {
                                        if (cancelTracker.Continue)
                                        {
                                            DrawingLayer?.BeginInvoke(layer.Title, new AsyncCallback(AsyncInvoke.RunAndForget), null);
                                        }

                                        await DrawRasterParentLayer((IParentRasterLayer)rLayer.Class, cancelTracker, rLayer);
                                    }
                                    else
                                    {
                                        RenderRasterLayer rlt = new RenderRasterLayer(this, rLayer, rLayer, cancelTracker);

                                        if (cancelTracker.Continue)
                                        {
                                            DrawingLayer?.BeginInvoke(layer.Title, new AsyncCallback(AsyncInvoke.RunAndForget), null);
                                        }

                                        await rlt.Render();
                                    }
                                }
                            }
                            // Andere Layer (zB IRasterLayer)

                            _original.FireDrawingLayerFinished(new gView.Framework.system.TimeEvent("Drawing: " + layer.Title, startTime, DateTime.Now, fCounter.Counter));

                            FireRefreshMapView(1000);
                        }
                        #endregion

                        #region Label Features

                        if (labelLayers.Count != 0)
                        {
                            StreamImage(ref _msGeometry, _bitmap);
                            foreach (IFeatureLayer fLayer in labelLayers)
                            {
                                this.SetGeotransformer(fLayer, geoTransformer);

                                FeatureCounter fCounter  = new FeatureCounter();
                                DateTime       startTime = DateTime.Now;

                                RenderLabel rlt = new RenderLabel(this, fLayer, cancelTracker, fCounter);

                                if (cancelTracker.Continue)
                                {
                                    DrawingLayer?.BeginInvoke(fLayer.Title, new AsyncCallback(AsyncInvoke.RunAndForget), null);
                                }

                                await rlt.Render();

                                _original.FireDrawingLayerFinished(new gView.Framework.system.TimeEvent("Labelling: " + fLayer.Title, startTime, DateTime.Now, fCounter.Counter));
                            }

                            DrawStream(_canvas, _msGeometry);
                        }

                        if (!printerMap)
                        {
                            LabelEngine.Draw(this.Display, cancelTracker);
                        }

                        LabelEngine.Release();

                        #endregion

                        #region Waiting for Webservices

                        if (cancelTracker.Continue)
                        {
                            if (webServices != null && webServices.Count != 0)
                            {
                                DrawingLayer?.BeginInvoke("...Waiting for WebServices...", new AsyncCallback(AsyncInvoke.RunAndForget), null);
                            }

                            while (m_imageMerger.Count < m_imageMerger.max)
                            {
                                await Task.Delay(100);
                            }
                        }
                        if (_drawScaleBar)
                        {
                            m_imageMerger.mapScale = this.mapScale;
                            m_imageMerger.dpi      = this.dpi;
                        }
                        if (m_imageMerger.Count > 0)
                        {
                            var clonedBitmap = _bitmap.Clone(GraphicsEngine.PixelFormat.Rgba32);
                            clonedBitmap.MakeTransparent(_backgroundColor);
                            m_imageMerger.Add(new GeorefBitmap(clonedBitmap), 999);

                            if (!m_imageMerger.Merge(_bitmap, this.Display) &&
                                (this is IServiceMap) &&
                                ((IServiceMap)this).MapServer != null)
                            {
                                await((IServiceMap)this).MapServer.LogAsync(
                                    this.Name,
                                    "Image Merger:",
                                    loggingMethod.error,
                                    m_imageMerger.LastErrorMessage);
                            }
                            m_imageMerger.Clear();
                        }

                        StreamImage(ref _msGeometry, _bitmap);

                        #endregion
                    }
                    #endregion

                    #region Draw Selection

                    if (Bit.Has(phase, DrawPhase.Selection))
                    {
                        if (phase != DrawPhase.All)
                        {
                            DrawStream(_canvas, _msGeometry);
                        }

                        foreach (IDatasetElement layer in this.MapElements)
                        {
                            if (!cancelTracker.Continue)
                            {
                                break;
                            }

                            if (!(layer is ILayer))
                            {
                                continue;
                            }

                            if (layer is IFeatureLayer &&
                                layer is IFeatureSelection &&
                                ((IFeatureSelection)layer).SelectionSet != null &&
                                ((IFeatureSelection)layer).SelectionSet.Count > 0)
                            {
                                SetGeotransformer((ILayer)layer, geoTransformer);
                                await RenderSelection(layer as IFeatureLayer, cancelTracker);
                            } // Andere Layer (zB IRasterLayer)
                            else if (layer is IWebServiceLayer)
                            {
                                IWebServiceLayer wLayer = (IWebServiceLayer)layer;
                                if (wLayer.WebServiceClass == null)
                                {
                                    continue;
                                }

                                foreach (IWebServiceTheme theme in wLayer.WebServiceClass.Themes)
                                {
                                    if (theme is IFeatureLayer &&
                                        theme.SelectionRenderer != null &&
                                        theme is IFeatureSelection &&
                                        ((IFeatureSelection)theme).SelectionSet != null &&
                                        ((IFeatureSelection)theme).SelectionSet.Count > 0)
                                    {
                                        SetGeotransformer(theme, geoTransformer);
                                        await RenderSelection(theme as IFeatureLayer, cancelTracker);
                                    }
                                }
                            }
                        }

                        StreamImage(ref _msSelection, _bitmap);
                    }

                    #endregion

                    #region Graphics

                    if (Bit.Has(phase, DrawPhase.Graphics))
                    //if (phase == DrawPhase.All || phase == DrawPhase.Graphics)
                    {
                        if (phase != DrawPhase.All)
                        {
                            DrawStream(_canvas, (_msSelection != null) ? _msSelection : _msGeometry);
                        }

                        foreach (IGraphicElement grElement in Display.GraphicsContainer.Elements)
                        {
                            grElement.Draw(Display);
                        }
                        foreach (IGraphicElement grElement in Display.GraphicsContainer.SelectedElements)
                        {
                            if (grElement is IGraphicElement2)
                            {
                                if (((IGraphicElement2)grElement).Ghost != null)
                                {
                                    ((IGraphicElement2)grElement).Ghost.Draw(Display);
                                }
                                ((IGraphicElement2)grElement).DrawGrabbers(Display);
                            }
                        }
                    }

                    #endregion

                    #region Cleanup

                    if (geoTransformer != null)
                    {
                        this.GeometricTransformer = null;
                        geoTransformer.Release();
                        geoTransformer = null;
                    }

                    #endregion

                    #region Send Events

                    // Überprüfen, ob sich Extent seit dem letztem Zeichnen geändert hat...
                    if (cancelTracker.Continue)
                    {
                        if (_lastRenderExtent == null)
                        {
                            _lastRenderExtent = new Envelope();
                        }

                        if (NewExtentRendered != null)
                        {
                            if (!_lastRenderExtent.Equals(Display.Envelope))
                            {
                                NewExtentRendered(this, Display.Envelope);
                            }
                        }
                        _lastRenderExtent.minx = Display.Envelope.minx;
                        _lastRenderExtent.miny = Display.Envelope.miny;
                        _lastRenderExtent.maxx = Display.Envelope.maxx;
                        _lastRenderExtent.maxy = Display.Envelope.maxy;
                    }

                    #endregion

                    return(true);
                }
            }
            catch (Exception ex)
            {
                _lastException = ex;
                AddRequestException(ex);
                //System.Windows.Forms.MessageBox.Show(ex.Message+"\n"+ex.InnerException+"\n"+ex.Source);
                return(false);
            }
            finally
            {
                AppendRequestExceptionsToImage();

                if (!printerMap)
                {
                    if (_canvas != null)
                    {
                        _canvas.Dispose();
                    }

                    _canvas = null;
                }

                this.IsRefreshing = false;
            }
        }
예제 #9
0
파일: Program.cs 프로젝트: jugstalt/gview5
        async static Task <int> Main(string[] args)
        {
            try
            {
                string cmd = "fill", jsonFile = (args.Length == 1 && args[0] != "fill" ? args[0] : String.Empty), indexUrl = String.Empty, indexName = String.Empty, category = String.Empty;

                string proxyUrl = String.Empty, proxyUser = String.Empty, proxyPassword = String.Empty;
                string basicAuthUser = String.Empty, basicAuthPassword = String.Empty;

                int  packageSize = 50000;
                bool replace     = false;

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "fill" && i < args.Length - 1)
                    {
                        cmd      = "fill";
                        jsonFile = args[i + 1];
                        i++;
                    }
                    if (args[i] == "remove-category")
                    {
                        cmd = "remove-category";
                    }
                    if (args[i] == "-s" && i < args.Length - 1)
                    {
                        indexUrl = args[i + 1];
                    }

                    if (args[i] == "-i" && i < args.Length - 1)
                    {
                        indexName = args[i + 1];
                    }

                    if (args[i] == "-c" && i < args.Length - 1)
                    {
                        category = args[i + 1];
                    }

                    if (args[i] == "-r")
                    {
                        replace = true;
                    }

                    if (args[i] == "-packagesize" && i < args.Length - 1)
                    {
                        packageSize = int.Parse(args[i + 1]);
                    }

                    #region Proxy

                    if (args[i] == "-proxy")
                    {
                        proxyUrl = args[i + 1];
                    }
                    if (args[i] == "-proxy-user")
                    {
                        proxyUser = args[i + 1];
                    }
                    if (args[i] == "-proxy-pwd")
                    {
                        proxyPassword = args[i + 1];
                    }

                    #endregion

                    #region Basic Authentication

                    if (args[i] == "-basic-auth-user")
                    {
                        basicAuthUser = args[i + 1];
                    }

                    if (args[i] == "-basic-auth-pwd")
                    {
                        basicAuthPassword = args[i + 1];
                    }

                    #endregion
                }

                if (args.Length == 0)
                {
                    Console.WriteLine("Usage: gView.Cmd.ElasticSearch fill|remove-catetory [Options]");
                    return(1);
                }


                //gView.Framework.system.SystemVariables.CustomApplicationDirectory =
                //    System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

                Console.WriteLine("Environment");

                Console.WriteLine("Working Directory: " + gView.Framework.system.SystemVariables.StartupDirectory);
                Console.WriteLine("64Bit=" + gView.Framework.system.Wow.Is64BitProcess);

                if (cmd == "fill")
                {
                    #region Fill Index (with Json File)

                    var importConfig = JsonConvert.DeserializeObject <ImportConfig>(File.ReadAllText(jsonFile));

                    if (importConfig?.Connection == null)
                    {
                        throw new Exception("Invalid config. No connection defined");
                    }

                    var httpClientHandler = new HttpClientHandler();
                    if (!String.IsNullOrEmpty(proxyUrl))
                    {
                        httpClientHandler.Proxy = new WebProxy
                        {
                            Address               = new Uri(proxyUrl),
                            BypassProxyOnLocal    = false,
                            UseDefaultCredentials = false,

                            Credentials = new NetworkCredential(proxyUser, proxyPassword)
                        };
                    }

                    var httpClient = new HttpClient(handler: httpClientHandler, disposeHandler: true);
                    if (!String.IsNullOrEmpty(basicAuthUser))
                    {
                        var byteArray = Encoding.ASCII.GetBytes($"{ basicAuthUser }:{ basicAuthPassword }");
                        httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                    }

                    using (var luceneServerClient = new LuceneServerClient(
                               importConfig.Connection.Url,
                               importConfig.Connection.DefaultIndex,
                               httpClient: httpClient))
                    {
                        if (importConfig.Connection.DeleteIndex)
                        {
                            await luceneServerClient.RemoveIndexAsync();
                        }

                        if (!await luceneServerClient.CreateIndexAsync())
                        {
                            throw new Exception($"Can't create elasticsearch index { importConfig.Connection.DefaultIndex }");
                        }
                        if (!await luceneServerClient.MapAsync(new SearchIndexMapping()))
                        {
                            throw new Exception($"Can't map item in elasticsearch index { importConfig.Connection.DefaultIndex }");
                        }

                        ISpatialReference sRefTarget = SpatialReference.FromID("epsg:4326");

                        Console.WriteLine("Target Spatial Reference: " + sRefTarget.Name + " " + String.Join(" ", sRefTarget.Parameters));

                        foreach (var datasetConfig in importConfig.Datasets)
                        {
                            if (datasetConfig.FeatureClasses == null)
                            {
                                continue;
                            }

                            IDataset dataset = new PlugInManager().CreateInstance(datasetConfig.DatasetGuid) as IDataset;
                            if (dataset == null)
                            {
                                throw new ArgumentException("Can't load dataset with guid " + datasetConfig.DatasetGuid.ToString());
                            }

                            await dataset.SetConnectionString(datasetConfig.ConnectionString);

                            await dataset.Open();

                            foreach (var featureClassConfig in datasetConfig.FeatureClasses)
                            {
                                var itemProto = featureClassConfig.IndexItemProto;
                                if (itemProto == null)
                                {
                                    continue;
                                }

                                string metaId = Guid.NewGuid().ToString("N").ToLower();
                                category = featureClassConfig.Category;
                                if (!String.IsNullOrWhiteSpace(category))
                                {
                                    var meta = new Meta()
                                    {
                                        Id         = metaId,
                                        Category   = category,
                                        Descrption = featureClassConfig.Meta?.Descrption,
                                        Sample     = featureClassConfig?.Meta.Sample,
                                        Service    = featureClassConfig?.Meta.Service,
                                        Query      = featureClassConfig?.Meta.Query
                                    };
                                    if (!await luceneServerClient.AddCustomMetadataAsync(metaId, JsonConvert.SerializeObject(meta)))
                                    {
                                        throw new Exception($"Can't index meta item in elasticsearch index { importConfig.Connection.MetaIndex }");
                                    }
                                }

                                bool useGeometry = featureClassConfig.UserGeometry;

                                IDatasetElement dsElement = await dataset.Element(featureClassConfig.Name);

                                if (dsElement == null)
                                {
                                    throw new ArgumentException("Unknown dataset element " + featureClassConfig.Name);
                                }

                                IFeatureClass fc = dsElement.Class as IFeatureClass;
                                if (fc == null)
                                {
                                    throw new ArgumentException("Dataobject is not a featureclass " + featureClassConfig.Name);
                                }

                                Console.WriteLine("Index " + fc.Name);
                                Console.WriteLine("=====================================================================");

                                QueryFilter filter = new QueryFilter();
                                filter.SubFields = "*";
                                if (!String.IsNullOrWhiteSpace(featureClassConfig.Filter))
                                {
                                    filter.WhereClause = featureClassConfig.Filter;
                                    Console.WriteLine("Filter: " + featureClassConfig.Filter);
                                }

                                List <Dictionary <string, object> > items = new List <Dictionary <string, object> >();
                                int count = 0;

                                ISpatialReference sRef = fc.SpatialReference ?? SpatialReference.FromID("epsg:" + featureClassConfig.SRefId);
                                Console.WriteLine("Source Spatial Reference: " + sRef.Name + " " + String.Join(" ", sRef.Parameters));
                                Console.WriteLine("IDField: " + fc.IDFieldName);

                                using (var transformer = GeometricTransformerFactory.Create())
                                {
                                    if (useGeometry)
                                    {
                                        transformer.SetSpatialReferences(sRef, sRefTarget);
                                    }

                                    IFeatureCursor cursor = await fc.GetFeatures(filter);

                                    IFeature feature;
                                    while ((feature = await cursor.NextFeature()) != null)
                                    {
                                        var indexItem = ParseFeature(metaId, category, feature, itemProto, useGeometry, transformer, featureClassConfig);
                                        items.Add(indexItem);
                                        count++;

                                        if (items.Count >= packageSize)
                                        {
                                            if (!await luceneServerClient.IndexDocumentsAsync(items.ToArray()))
                                            {
                                                throw new Exception($"Error on indexing { items.Count } items on elasticsearch index { importConfig.Connection.DefaultIndex }");
                                            }
                                            items.Clear();

                                            Console.Write(count + "...");
                                        }
                                    }

                                    if (items.Count > 0)
                                    {
                                        if (!await luceneServerClient.IndexDocumentsAsync(items.ToArray()))
                                        {
                                            throw new Exception($"Error on indexing { items.Count } items on elasticsearch index { importConfig.Connection.DefaultIndex }");
                                        }
                                        Console.WriteLine(count + "...finish");
                                    }
                                }
                            }
                        }
                    }

                    #endregion
                }
                else if (cmd == "remove-category")
                {
                    #region Remove Category

                    //RemoveCategory(indexUrl, indexName, replace ? Replace(category) : category,
                    //               proxyUrl, proxyUser, proxyPassword,
                    //               basicAuthUser, basicAuthPassword);

                    #endregion
                }

                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);

                return(1);
            }
        }
예제 #10
0
파일: Program.cs 프로젝트: jugstalt/gview5
        async static Task <int> Main(string[] args)
        {
            string cmd = "fill", jsonFile = (args.Length == 1 && args[0] != "fill" ? args[0] : String.Empty), indexUrl = String.Empty, indexName = String.Empty, category = String.Empty;

            string proxyUrl = String.Empty, proxyUser = String.Empty, proxyPassword = String.Empty;
            string basicAuthUser = String.Empty, basicAuthPassword = String.Empty;

            bool replace = false;

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] == "fill" && i < args.Length - 1)
                {
                    cmd      = "fill";
                    jsonFile = args[i + 1];
                    i++;
                }
                if (args[i] == "remove-category")
                {
                    cmd = "remove-category";
                }
                if (args[i] == "-s" && i < args.Length - 1)
                {
                    indexUrl = args[i + 1];
                }

                if (args[i] == "-i" && i < args.Length - 1)
                {
                    indexName = args[i + 1];
                }

                if (args[i] == "-c" && i < args.Length - 1)
                {
                    category = args[i + 1];
                }

                if (args[i] == "-r")
                {
                    replace = true;
                }

                #region Proxy

                if (args[i] == "-proxy")
                {
                    proxyUrl = args[i + 1];
                }
                if (args[i] == "-proxy-user")
                {
                    proxyUser = args[i + 1];
                }
                if (args[i] == "-proxy-pwd")
                {
                    proxyPassword = args[i + 1];
                }

                #endregion

                #region Basic Authentication

                if (args[i] == "-basic-auth-user")
                {
                    basicAuthUser = args[i + 1];
                }

                if (args[i] == "-basic-auth-pwd")
                {
                    basicAuthPassword = args[i + 1];
                }

                #endregion
            }

            if (args.Length == 0)
            {
                Console.WriteLine("Usage: gView.Cmd.ElasticSearch fill|remove-catetory [Options]");
                return(1);
            }

            if (cmd == "fill" && String.IsNullOrEmpty(jsonFile))
            {
                Console.WriteLine("Usage: gView.Cmd.ElasticSearch fill {json-file}");
                return(1);
            }
            else if (cmd == "remove-category" && (String.IsNullOrWhiteSpace(indexUrl) || String.IsNullOrWhiteSpace(category)))
            {
                Console.WriteLine("Usage: gView.cmd.ElasticSearch remove-category -s {index-url} -i {index-name} -c {category} [-r]");
                Console.WriteLine("  -r ... raplace german Umlaute:");
                Console.WriteLine("            _ae_, _oe_, _ue_   =>  ä, ö, ü");
                Console.WriteLine("            _Ae_, _Oe_, _Ue_   =>  Ä, Ö, Ü");
                Console.WriteLine("            _sz_               =>  ß");
                return(1);
            }

            try
            {
                //gView.Framework.system.SystemVariables.CustomApplicationDirectory =
                //    System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

                Console.WriteLine("Environment");

                Console.WriteLine("Working Directory: " + gView.Framework.system.SystemVariables.StartupDirectory);
                Console.WriteLine("64Bit=" + gView.Framework.system.Wow.Is64BitProcess);

                if (cmd == "fill")
                {
                    #region Fill Index (with Json File)

                    var importConfig = JsonConvert.DeserializeObject <ImportConfig>(File.ReadAllText(jsonFile));

                    var searchContext = new ElasticSearchContext(importConfig.Connection.Url,
                                                                 importConfig.Connection.DefaultIndex,
                                                                 proxyUri: proxyUrl, proxyUsername: proxyUser, proxyPassword: proxyPassword,
                                                                 basicAuthUser: basicAuthUser, basicAuthPassword: basicAuthPassword);

                    if (importConfig.Connection.DeleteIndex)
                    {
                        searchContext.DeleteIndex();
                        searchContext.DeleteIndex(importConfig.Connection.MetaIndex);
                    }

                    if (!searchContext.CreateIndex <Item>())
                    {
                        throw new Exception($"Can't create elasticsearch index { importConfig.Connection.DefaultIndex }: { searchContext.LastErrorMessage }");
                    }
                    if (!searchContext.Map <Item>())
                    {
                        throw new Exception($"Can't map item in elasticsearch index { importConfig.Connection.DefaultIndex }: { searchContext.LastErrorMessage }");
                    }
                    if (!searchContext.CreateIndex <Meta>(importConfig.Connection.MetaIndex))
                    {
                        throw new Exception($"Can't create elasticsearch index { importConfig.Connection.MetaIndex }: { searchContext.LastErrorMessage }");
                    }

                    if (!searchContext.Map <Meta>(importConfig.Connection.MetaIndex))
                    {
                        throw new Exception($"Can't map item in elasticsearch index { importConfig.Connection.MetaIndex }: { searchContext.LastErrorMessage }");
                    }

                    ISpatialReference sRefTarget = SpatialReference.FromID("epsg:4326");

                    Console.WriteLine("Target Spatial Reference: " + sRefTarget.Name + " " + String.Join(" ", sRefTarget.Parameters));

                    foreach (var datasetConfig in importConfig.Datasets)
                    {
                        if (datasetConfig.FeatureClasses == null)
                        {
                            continue;
                        }

                        IDataset dataset = new PlugInManager().CreateInstance(datasetConfig.DatasetGuid) as IDataset;
                        if (dataset == null)
                        {
                            throw new ArgumentException("Can't load dataset with guid " + datasetConfig.DatasetGuid.ToString());
                        }

                        await dataset.SetConnectionString(datasetConfig.ConnectionString);

                        await dataset.Open();

                        foreach (var featureClassConfig in datasetConfig.FeatureClasses)
                        {
                            var itemProto = featureClassConfig.IndexItemProto;
                            if (itemProto == null)
                            {
                                continue;
                            }

                            string metaId = Guid.NewGuid().ToString("N").ToLower();
                            category = featureClassConfig.Category;
                            if (!String.IsNullOrWhiteSpace(category))
                            {
                                var meta = new Meta()
                                {
                                    Id         = metaId,
                                    Category   = category,
                                    Descrption = featureClassConfig.Meta?.Descrption,
                                    Sample     = featureClassConfig?.Meta.Sample,
                                    Service    = featureClassConfig?.Meta.Service,
                                    Query      = featureClassConfig?.Meta.Query
                                };
                                if (!searchContext.Index <Meta>(meta, importConfig.Connection.MetaIndex))
                                {
                                    throw new Exception($"Can't index meta item in elasticsearch index { importConfig.Connection.MetaIndex }");
                                }
                            }

                            bool useGeometry = featureClassConfig.UserGeometry;

                            IDatasetElement dsElement = await dataset.Element(featureClassConfig.Name);

                            if (dsElement == null)
                            {
                                throw new ArgumentException("Unknown dataset element " + featureClassConfig.Name);
                            }

                            IFeatureClass fc = dsElement.Class as IFeatureClass;
                            if (fc == null)
                            {
                                throw new ArgumentException("Dataobject is not a featureclass " + featureClassConfig.Name);
                            }

                            Console.WriteLine("Index " + fc.Name);
                            Console.WriteLine("=====================================================================");

                            QueryFilter filter = new QueryFilter();
                            filter.SubFields = "*";
                            if (!String.IsNullOrWhiteSpace(featureClassConfig.Filter))
                            {
                                filter.WhereClause = featureClassConfig.Filter;
                                Console.WriteLine("Filter: " + featureClassConfig.Filter);
                            }

                            List <Item> items = new List <Item>();
                            int         count = 0;

                            ISpatialReference sRef = fc.SpatialReference ?? SpatialReference.FromID("epsg:" + featureClassConfig.SRefId);
                            Console.WriteLine("Source Spatial Reference: " + sRef.Name + " " + String.Join(" ", sRef.Parameters));
                            Console.WriteLine("IDField: " + fc.IDFieldName);

                            using (var transformer = GeometricTransformerFactory.Create())
                            {
                                if (useGeometry)
                                {
                                    transformer.SetSpatialReferences(sRef, sRefTarget);
                                }

                                IFeatureCursor cursor = await fc.GetFeatures(filter);

                                IFeature feature;
                                while ((feature = await cursor.NextFeature()) != null)
                                {
                                    var indexItem = ParseFeature(metaId, category, feature, itemProto, useGeometry, transformer, featureClassConfig);
                                    items.Add(indexItem);
                                    count++;

                                    if (items.Count >= 500)
                                    {
                                        if (!searchContext.IndexManyPro <Item>(items.ToArray()))
                                        {
                                            throw new Exception($"Error on indexing { items.Count } items on elasticsearch index { importConfig.Connection.DefaultIndex }: { searchContext.LastErrorMessage }");
                                        }
                                        items.Clear();

                                        Console.Write(count + "...");
                                    }
                                }

                                if (items.Count > 0)
                                {
                                    if (!searchContext.IndexManyPro <Item>(items.ToArray()))
                                    {
                                        throw new Exception($"Error on indexing { items.Count } items on elasticsearch index { importConfig.Connection.DefaultIndex }: { searchContext.LastErrorMessage }");
                                    }
                                    Console.WriteLine(count + "...finish");
                                }
                            }
                        }
                    }

                    #endregion
                }
                else if (cmd == "remove-category")
                {
                    #region Remove Category

                    RemoveCategory(indexUrl, indexName, replace ? Replace(category) : category,
                                   proxyUrl, proxyUser, proxyPassword,
                                   basicAuthUser, basicAuthPassword);

                    #endregion
                }

                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                return(1);
            }
        }