static public IGeometry Transform2D(IGeometry geometry, ISpatialReference from, ISpatialReference to)
        {
            if (geometry == null)
            {
                return(null);
            }

            if (from == null || to == null || from.Equals(to))
            {
                return(geometry);
            }

            using (IGeometricTransformer transformer = GeometricTransformerFactory.Create())
            {
                //transformer.FromSpatialReference = from;
                //transformer.ToSpatialReference = to;
                transformer.SetSpatialReferences(from, to);
                IGeometry transformed = transformer.Transform2D(geometry) as IGeometry;
                transformer.Release();

                return(transformed);
            }
        }
Пример #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
        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;
                }
            }
        }
Пример #4
0
        private bool ImportToNewFeatureclass(IFeatureDataset destDS, string fcname, IFeatureClass sourceFC, FieldTranslation fieldTranslation, bool project, List <IQueryFilter> filters, DatasetNameCase namecase)
        {
            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 = destDS[fcname] as IDatasetElement;
                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)
                {
                    fdb.DeleteFeatureClass(fcname);
                }
                int fcID = fdb.CreateFeatureClass(destDS.DatasetName,
                                                  fcname,
                                                  sourceFC,
                                                  (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.lastErrorMsg;
                    destDS.Dispose();
                    return(false);
                }

                destLayer = destDS[fcname] as IDatasetElement;

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

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

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

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

                    if (!_schemaOnly)
                    {
                        result = CopyFeatures(sourceFC, fdb, destFC, fieldTranslation, filters);
                    }
                    if (!result)
                    {
                        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...";
                        return(false);
                    }
                }
                destDS.Dispose();

                if (_cancelTracker.Continue)
                {
                    return(true);
                }
                else
                {
                    fdb.DeleteFeatureClass(fcname);
                    _errMsg = "Import is canceled by the user...";
                    return(false);
                }
            }
            finally
            {
                if (_transformer != null)
                {
                    _transformer.Release();
                    _transformer = null;
                }
            }
        }
Пример #5
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;
            }
        }