public myAOProgressor()
        {
            cancelTracker = new CancelTracker();

            pMouseCursor = new MouseCursorClass();
            pMouseCursor.SetCursor(2);
        }
Ejemplo n.º 2
0
        public void FinishDrawing(IDisplay disp, ICancelTracker cancelTracker)
        {
            if (cancelTracker == null)
            {
                cancelTracker = new CancelTracker();
            }

            if (_actualCartoMethod == CartographicMethod.SymbolOrder && cancelTracker.Continue)
            {
                ISymbolCollection sColl = (ISymbolCollection)_symbol;
                foreach (ISymbolCollectionItem symbolItem in sColl.Symbols)
                {
                    if (symbolItem.Visible == false || symbolItem.Symbol == null)
                    {
                        continue;
                    }

                    ISymbol symbol      = symbolItem.Symbol;
                    bool    isRotatable = symbol is ISymbolRotation;

                    int counter = 0;
                    if (!cancelTracker.Continue)
                    {
                        break;
                    }

                    foreach (IFeature feature in _features)
                    {
                        if (_rotate && isRotatable)
                        {
                            object rot = feature[_symbolRotation.RotationFieldName];
                            if (rot != null && rot != DBNull.Value)
                            {
                                ((ISymbolRotation)symbol).Rotation = (float)_symbolRotation.Convert2DEGAritmetic(Convert.ToDouble(rot));
                            }
                            else
                            {
                                ((ISymbolRotation)symbol).Rotation = 0;
                            }
                        }
                        disp.Draw(symbol, feature.Shape);

                        counter++;
                        if (counter % 100 == 0 && !cancelTracker.Continue)
                        {
                            break;
                        }
                    }
                }
            }

            if (_features != null)
            {
                _features.Clear();
            }
            _features = null;
        }
Ejemplo n.º 3
0
        private void CloneFileList()
        {
            bool itWorked = false;



            int                    cloneCount            = 1; // labeling the processor bar
            ITrackCancel           trackcancel           = new CancelTracker();
            IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass();
            IStepProgressor        stepprogressor        = progressdialogfactory.Create(trackcancel, _application.hWnd);

            stepprogressor.MinRange  = 0;
            stepprogressor.MaxRange  = _fileList.Count;
            stepprogressor.StepValue = 1;
            stepprogressor.Message   = "Copying...";
            IProgressDialog2 progressdialog = (IProgressDialog2)stepprogressor; // Creates and displays

            progressdialog.CancelEnabled = false;
            progressdialog.Description   = "Copying {_fileList.Count} files...";
            progressdialog.Title         = MB_TITLE;
            progressdialog.Animation     = esriProgressAnimationTypes.esriProgressSpiral;


            foreach (KeyValuePair <String, Boolean> file in _fileList)
            {
                if (file.Value)
                {
                    progressdialog.Description = string.Format("Copying File {0} of {1}...", cloneCount, _fileList.Count);
                    if (!itWorked)
                    {
                        SaveFileTypeList(GetExtension());
                    }
                    itWorked = true;

                    try
                    {
                        var sourceFile      = txb_FileWorkspaceSrc.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension();
                        var destinationFile = txb_FileWorkspaceDst.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension();

                        System.IO.File.Copy(sourceFile, destinationFile);
                    }
                    catch (Exception yourBest) // but you don't succeed
                    {
                        yourBest.ToString();
                        // Just So We Get No Crashes ;)
                    }
                    stepprogressor.Step();
                    cloneCount++;
                }
            }
            trackcancel    = null;
            stepprogressor = null;
            progressdialog.HideDialog();
            progressdialog = null;
            //_activeView.Refresh();
        }
Ejemplo n.º 4
0
 public FDBImageDataset(IImageDB fdb, string dsname)
 {
     _fdb    = fdb;
     _dsname = dsname;
     if (_fdb is AccessFDB)
     {
         _conn = ((AccessFDB)_fdb)._conn;
     }
     _cancelTracker = new CancelTracker();
 }
Ejemplo n.º 5
0
        public IFIDSet AppendCadastralXML(ICadastralFabric Fabric, ICadastralJob CadastralJob, IProjectedCoordinateSystem TargetProjectedCoordinateSystem, string CadastralXMLPath)
        {
            try
            {
                string sTempPath = System.IO.Path.GetTempPath();
                string sCopiedCadastralXMLFile = System.IO.Path.Combine(sTempPath, CadastralJob.Name.Replace('/', '_').Replace(':', '_') + ".xml");

                //rename ALL oID tags so that they're ignored
                ReplaceInFile(CadastralXMLPath, sCopiedCadastralXMLFile, "oID>", "old_xxX>");

                //Possible TODO for merge-point workaround: analyze coordinates of incoming file and if any are identical to existing fabric coordinates, then make the oID tag match
                //the oID of the existing point in the target fabric. This will trigger point merging of identical points

                ITrackCancel pTrkCan = new CancelTracker();
                // Create and display the Progress Dialog
                IProgressDialogFactory pProDlgFact = new ProgressDialogFactory();
                IProgressDialog2       pProDlg     = pProDlgFact.Create(pTrkCan, 0) as IProgressDialog2;
                //Set the properties of the Progress Dialog
                pProDlg.CancelEnabled = false;
                pProDlg.Description   = "    ";
                pProDlg.Title         = "Append";
                pProDlg.Animation     = esriProgressAnimationTypes.esriProgressGlobe;

                //        do an extract to set the spatial reference
                ((ICadastralFabric3)Fabric).ExtractCadastralPacket(CadastralJob.Name, TargetProjectedCoordinateSystem, null, true);



                IXMLStream pStream = new XMLStream();
                pStream.LoadFromFile(sCopiedCadastralXMLFile);
                IFIDSet pFIDSet = null;//new FIDSet();

                (Fabric as ICadastralFabric3).PostCadastralPacket(pStream, pTrkCan, esriCadastralPacketSetting.esriCadastralPacketNoSetting, ref pFIDSet);
                //(Fabric as ICadastralFabric3).InsertCadastralPacket(CadastralJob, pStream, pTrkCan, esriCadastralPacketSetting.esriCadastralPacketNoSetting, ref pFIDSet);
                int setCnt = pFIDSet.Count();

                RefreshFabricLayers(ArcMap.Document.ActiveView.FocusMap, Fabric);
                File.Delete(sCopiedCadastralXMLFile);

                if (pProDlg != null)
                {
                    pProDlg.HideDialog();
                }

                return(pFIDSet);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(null);
            }
        }
Ejemplo n.º 6
0
        private void PaintWavelet(int x, int y, int wWidth, int wHeight, int iWidth, int iHeight, ICancelTracker cancelTracker)
        {
            if (CancelTracker.Canceled(cancelTracker) || _gDS == null)
            {
                return;
            }
            int pixelSpace = 3;

            _bitmap = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
            BitmapData bitmapData = _bitmap.LockBits(new Rectangle(0, 0, iWidth, iHeight), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            try
            {
                int    stride = bitmapData.Stride;
                IntPtr buf    = bitmapData.Scan0;

                for (int i = 1; i <= (_gDS.RasterCount > 3 ? 3 : _gDS.RasterCount); ++i)
                {
                    using (OSGeo.GDAL.Band band = _gDS.GetRasterBand(i))
                    {
                        int ch = 0;
                        switch ((ColorInterp)band.GetRasterColorInterpretation())
                        {
                        case ColorInterp.BlueBand:
                            ch = 0;
                            break;

                        case ColorInterp.GreenBand:
                            ch = 1;
                            break;

                        case ColorInterp.RedBand:
                            ch = 2;
                            break;
                        }
                        band.ReadRaster(x, y, wWidth, wHeight,
                                        new IntPtr(buf.ToInt64() + ch),
                                        iWidth, iHeight, OSGeo.GDAL.DataType.GDT_Byte, pixelSpace, stride);

                        band.Dispose();
                    }
                }
            }
            finally
            {
                if (_bitmap != null)
                {
                    _bitmap.UnlockBits(bitmapData);
                }
            }
        }
Ejemplo n.º 7
0
        private void ValidateFileList()
        {
            int                    cloneCount            = 1; // labeling the processor bar
            ITrackCancel           trackcancel           = new CancelTracker();
            IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass();
            IStepProgressor        stepprogressor        = progressdialogfactory.Create(trackcancel, _application.hWnd);

            stepprogressor.MinRange  = 0;
            stepprogressor.MaxRange  = _fileList.Count;
            stepprogressor.StepValue = 1;
            stepprogressor.Message   = "Validating...";
            IProgressDialog2 progressdialog = (IProgressDialog2)stepprogressor; // Creates and displays

            progressdialog.CancelEnabled = false;
            progressdialog.Description   = "Validating {_fileList.Count} files...";
            progressdialog.Title         = MB_TITLE;
            progressdialog.Animation     = esriProgressAnimationTypes.esriProgressSpiral;



            IDictionary <String, Boolean> newList = new Dictionary <String, Boolean>();

            foreach (KeyValuePair <String, Boolean> file in _fileList)
            {
                progressdialog.Description = string.Format("Validating {0} of {1}...", cloneCount, _fileList.Count);
                string filePath = txb_FileWorkspaceSrc.Text + "\\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension();
                if (!File.Exists(filePath))
                {
                    newList.Add(file.Key, false);
                }
                else
                {
                    newList.Add(file.Key, file.Value);
                }
                stepprogressor.Step();
                cloneCount++;
            }
            _fileList = newList;



            trackcancel    = null;
            stepprogressor = null;
            progressdialog.HideDialog();
            progressdialog = null;
            //_activeView.Refresh();
        }
Ejemplo n.º 8
0
        public static IRasterDataset TinToRaster(ITinAdvanced itinAdvanced_0,
                                                 esriRasterizationType esriRasterizationType_0, string string_0, string string_1, string string_2,
                                                 rstPixelType rstPixelType_0, double double_0, IEnvelope ienvelope_0, bool bool_0)
        {
            object obj3;
            IPoint lowerLeft = ienvelope_0.LowerLeft;

            lowerLeft.X -= double_0 * 0.5;
            lowerLeft.Y -= double_0 * 0.5;
            int                num              = ((int)Math.Round((double)(ienvelope_0.Width / double_0))) + 1;
            int                num2             = ((int)Math.Round((double)(ienvelope_0.Height / double_0))) + 1;
            IGeoDataset        dataset          = itinAdvanced_0 as IGeoDataset;
            ISpatialReference2 spatialReference = dataset.SpatialReference as ISpatialReference2;
            IRasterDataset     dataset2         = CreateRasterSurf(string_0, string_1, string_2, lowerLeft, num, num2, double_0,
                                                                   double_0, 1, rstPixelType_0, spatialReference, bool_0);
            IRawPixels   rawPixels = GetRawPixels(dataset2, 0);
            object       cache     = rawPixels.AcquireCache();
            ITinSurface  pSurface  = itinAdvanced_0 as ITinSurface;
            IRasterProps o         = rawPixels as IRasterProps;
            double       zMin      = itinAdvanced_0.Extent.ZMin;

            if (rstPixelType_0 == rstPixelType.PT_FLOAT)
            {
                obj3 = (float)(zMin - 1.0);
            }
            else
            {
                obj3 = (int)(zMin - 1.0);
            }
            o.NoDataValue = obj3;
            IPnt tlc  = new DblPnt();
            int  num4 = 2048;

            if (num < 2048)
            {
                num4 = num;
            }
            int num5 = 2048;

            if (num2 < 2048)
            {
                num5 = num2;
            }
            IPnt size = new DblPnt
            {
                X = num4,
                Y = num5
            };
            IPixelBlock3 block  = rawPixels.CreatePixelBlock(size) as IPixelBlock3;
            ITrackCancel cancel = new CancelTracker
            {
                CancelOnClick    = false,
                CancelOnKeyPress = true
            };
            int num6 = (int)(Math.Round((double)((num / num4) + 0.49)) * Math.Round((double)((num2 / num5) + 0.49)));

            if (num6 == 1)
            {
                itinAdvanced_0.TrackCancel = cancel;
            }
            IPoint point2 = new Point();
            object obj4   = block.get_PixelDataByRef(0);

            for (int i = 0; i < num2; i += num5)
            {
                for (int j = 0; j < num; j += num4)
                {
                    if ((num - j) < num4)
                    {
                        size.X = num - j;
                        block  = rawPixels.CreatePixelBlock(size) as IPixelBlock3;
                        obj4   = block.get_PixelDataByRef(0);
                    }
                    point2.X = (lowerLeft.X + (j * double_0)) + (double_0 * 0.5);
                    point2.Y = (lowerLeft.Y + ((num2 - i) * double_0)) - (double_0 * 0.5);
                    IGeoDatabaseBridge2 bridge = new GeoDatabaseHelper() as IGeoDatabaseBridge2;
                    bridge.QueryPixelBlock(pSurface, point2.X, point2.Y, double_0, double_0, esriRasterizationType_0,
                                           obj3, ref obj4);
                    tlc.X = j;
                    tlc.Y = i;
                    block.set_PixelData(0, obj4);
                    rawPixels.Write(tlc, block as IPixelBlock);
                }
                bool flag = false;
                if (size.X != num4)
                {
                    size.X = num4;
                    flag   = true;
                }
                if ((num2 - i) < num5)
                {
                    size.Y = num2 - i;
                    flag   = true;
                }
                if (flag)
                {
                    block = rawPixels.CreatePixelBlock(size) as IPixelBlock3;
                    obj4  = block.get_PixelDataByRef(0);
                }
            }
            rawPixels.ReturnCache(cache);
            Marshal.ReleaseComObject(cache);
            cache = null;
            Marshal.ReleaseComObject(rawPixels);
            rawPixels = null;
            Marshal.ReleaseComObject(block);
            block = null;
            Marshal.ReleaseComObject(o);
            o    = null;
            obj4 = 0;
            GC.Collect();
            return(dataset2);
        }
Ejemplo n.º 9
0
        protected override void OnClick()
        {
            //first check that we are currently editing
            if (ArcMap.Editor.EditState != esriEditState.esriStateEditing)
            {
                MessageBox.Show("Please start editing and try again.", "Sample Code");
                return;
            }

            //get the cadastral editor
            ICadastralEditor pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");

            //get the fabric line layers that belong to the target fabric.
            // **SAMPLE CODE NOTE**
            //This next function allows for more than 1 fabric lines sublayer in the map document, and uses a line layer array
            //However, this sample code assumes just one line fabric sub layer, and works with the first found
            //The function is provided for other expanded uses if needed elsewhere.
            IArray LineLayerArray;

            if (!GetFabricSubLayers(ArcMap.Document.ActiveView.FocusMap, esriCadastralFabricTable.esriCFTLines,
                                    true, pCadEd.CadastralFabric, out LineLayerArray))
            {
                return;
            }

            // get the line selection; this code sample uses first line layer for the target fabric (first element)
            ISelectionSet2 LineSelection =
                GetSelectionFromLayer(LineLayerArray.get_Element(0) as ICadastralFabricSubLayer);

            // check to see if there is only one parcel line selected
            // **SAMPLE CODE NOTE**
            //This sample code ensures one line feature, although it can be easily adapted for use on
            //multiple line selection.
            if (LineSelection.Count != 1)
            {
                MessageBox.Show("Please select only one parcel line from the Target fabric.", "Sample Code");
                return;
            }
            //Get a search cursor from the line selection to get the parcel id
            //We need to get an edit lock on the parcel using the parcel id
            //An edit lock will guarantee the edit will persist in a multi-user environment after a reconcile

            ILongArray pParcelsToLock        = new LongArrayClass();
            IFIDSet    pFIDSetForParcelRegen = new FIDSet();
            ICursor    pCur;

            LineSelection.Search(null, false, out pCur);
            //this cursor returns the selected lines
            // **SAMPLE CODE NOTE**
            //setup for potential use for multiple line selection, even though this sample uses a single line selection

            //get the field indices for line attributes needed.
            int idxParcelID    = pCur.FindField("parcelid");
            int idxToPointID   = pCur.FindField("topointid");
            int idxFromPointID = pCur.FindField("frompointid");
            int idxCenterPtId  = pCur.FindField("centerpointid");
            int idxDistance    = pCur.FindField("distance");
            int idxRadius      = pCur.FindField("radius");
            int idxCategory    = pCur.FindField("category");

            //also need the fabric point table and fields
            IFeatureClass pFabricPointsFC = (IFeatureClass)pCadEd.CadastralFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints);
            int           idxPointX       = pFabricPointsFC.FindField("x");
            int           idxPointY       = pFabricPointsFC.FindField("y");
            int           idxPointCtrPt   = pFabricPointsFC.FindField("centerpoint");

            var ListFromToPairsForRadialLines = new List <int[]>();

            // **SAMPLE CODE NOTE**
            //setup for potential use for multiple line selection, even though this sample uses a single line selection
            //the list declared above is here for potential use in Add-ins that make use of multiple circular arc lines

            int[] ParcelIdCtrPtIdFromId1FromId2;
            IRow  pRow = pCur.NextRow();

            while (pRow != null)
            {
                int iParcelID = (int)pRow.get_Value(idxParcelID);
                pParcelsToLock.Add(iParcelID);        //LongArray for the parcel locks
                pFIDSetForParcelRegen.Add(iParcelID); //FIDSet for the parcel regenerate
                //now check for a center point id on the line; this is for the case of changing the radius of an existing curve

                object value = pRow.get_Value(idxCenterPtId);
                if (value != DBNull.Value)
                {                                                  //collecting information to remove radial lines
                    ParcelIdCtrPtIdFromId1FromId2    = new int[4]; // 4-element array
                    ParcelIdCtrPtIdFromId1FromId2[0] = iParcelID;
                    ParcelIdCtrPtIdFromId1FromId2[1] = (int)value; //center point is always the to point of the radial line
                    ParcelIdCtrPtIdFromId1FromId2[2] = (int)pRow.get_Value(idxFromPointID);
                    ParcelIdCtrPtIdFromId1FromId2[3] = (int)pRow.get_Value(idxToPointID);
                    // **SAMPLE CODE NOTE**
                    //now add the array, to the list to accomodate other add-ins that may use
                    //more than one selected circular arc line
                    ListFromToPairsForRadialLines.Add(ParcelIdCtrPtIdFromId1FromId2);
                }
                Marshal.ReleaseComObject(pRow);
                pRow = pCur.NextRow();
            }
            Marshal.ReleaseComObject(pCur);

            bool IsFileBasedGDB = (ArcMap.Editor.EditWorkspace.WorkspaceFactory.WorkspaceType !=
                                   esriWorkspaceType.esriRemoteDatabaseWorkspace);

            if (!IsFileBasedGDB)
            {
                //for file geodatabase creating a job is optional
                //see if parcel locks can be obtained on the selected parcels. First create a job.
                string NewJobName = "";
                if (!CreateJob(pCadEd.CadastralFabric, "Sample Code change line to curve", out NewJobName))
                {
                    return;
                }

                if (!TestForEditLocks(pCadEd.CadastralFabric, NewJobName, pParcelsToLock))
                {
                    return;
                }
            }

            //if we get this far, an edit lock has been acquired, or this is file geodatabase (no lock required)
            //prompt the user for a new radius value

            string sRadius = Interaction.InputBox("Enter a new Radius:", "Radius");
            //**SAMPLE CODE NOTE** :
            // using the Interaction class from the Microsfot Visual Basic library
            // is a quick and easy way to provide an input dialog in a single line of code for sample purposes,
            // without neeing to add a windows form, dockable window, or other UI elements into this project.

            double dRadius = 0;

            if (!Double.TryParse(sRadius, out dRadius))
            {
                return;
            }
            //we have a valid double value, so we can get ready to edit

            IProgressDialogFactory pProgressorDialogFact = new ProgressDialogFactoryClass();
            ITrackCancel           pTrackCancel          = new CancelTracker();
            IStepProgressor        pStepProgressor       = pProgressorDialogFact.Create(pTrackCancel, ArcMap.Application.hWnd);
            IProgressDialog2       pProgressorDialog     = (IProgressDialog2)pStepProgressor;

            ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadEd.CadastralFabric;

            try
            {                                                                                                     //turn off the read-only flag on the lines table and points table
                pSchemaEd.ReleaseReadOnlyFields(LineSelection.Target, esriCadastralFabricTable.esriCFTLines);     //release read-only
                pSchemaEd.ReleaseReadOnlyFields((ITable)pFabricPointsFC, esriCadastralFabricTable.esriCFTPoints); //release read-only

                //start an edit operation
                ArcMap.Editor.StartOperation();

                //get an update cursor to make the edit on the line(s)
                LineSelection.Update(null, false, out pCur);

                pRow = pCur.NextRow();
                int iChangeCount = 0;
                while (pRow != null)
                {
                    double dChord = (double)pRow.get_Value(idxDistance);
                    if (Math.Abs(dRadius) <= dChord / 2 && dRadius != 0) //minimum allowable radius is half the chord
                    {
                        Marshal.ReleaseComObject(pRow);
                        pRow = pCur.NextRow();
                        continue;
                    }

                    //compute a center point location from new radius, unless it's 0
                    int iNewCtrPtId = 0;
                    if (dRadius != 0)
                    {
                        IFeature pFeat         = pRow as IFeature;
                        IPoint   pCtrPt        = ComputeCenterPointFromRadius(pFeat.Shape as IPolyline, dRadius, true);
                        IFeature pNewPointFeat = pFabricPointsFC.CreateFeature();
                        //**SAMPLE CODE NOTE** :
                        //if adding a large number of points (more than 20) then createfeature is not the fastest approach,
                        //Instead you would pre-allocate points using an insert cursor...
                        //At this point in the code, the normal geodatabase performance considerations apply
                        iNewCtrPtId = pNewPointFeat.OID;
                        pNewPointFeat.set_Value(idxPointX, pCtrPt.X);
                        pNewPointFeat.set_Value(idxPointY, pCtrPt.Y);
                        pNewPointFeat.set_Value(idxPointCtrPt, 1); //1 = true boolean
                        pNewPointFeat.Shape = pCtrPt;
                        pNewPointFeat.Store();
                    }
                    //get the initial radius if the line is a curve (radius is being updated)
                    object obj = pRow.get_Value(idxRadius);
                    bool   bIsChangingFromCurve = (obj != DBNull.Value);                  //there is a radius value
                    obj = pRow.get_Value(idxCenterPtId);
                    bIsChangingFromCurve = bIsChangingFromCurve && (obj != DBNull.Value); //radius value and Ctr Pt ID exist
                    int iExistingCtrPtId = 0;
                    if (bIsChangingFromCurve)
                    {
                        iExistingCtrPtId = (int)obj;
                    }
                    if (dRadius == 0) //user entered value is zero meaning convert to straight line
                    {                 //changing to a straight line so set the center point an radius to null
                        pRow.set_Value(idxRadius, DBNull.Value);
                        pRow.set_Value(idxCenterPtId, DBNull.Value);
                    }
                    else if (!bIsChangingFromCurve) //user entered a new radius, and the existing line is not a curve
                    {                               //changing to a circular arc so set the radius, and set the center point id to the new point's OID
                        pRow.set_Value(idxRadius, dRadius);
                        pRow.set_Value(idxCenterPtId, iNewCtrPtId);
                    }
                    else if (bIsChangingFromCurve) //user entered a radius, and the existing line is a curve

                    {
                        pCur.UpdateRow(pRow);
                    }
                    iChangeCount++;
                    Marshal.ReleaseComObject(pRow);
                    pRow = pCur.NextRow();
                }
                Marshal.ReleaseComObject(pCur);

                if (iChangeCount == 0)
                {//if there are no changes then don't add to the edit operation stack
                    ArcMap.Editor.AbortOperation();
                    return;
                }

                if (ListFromToPairsForRadialLines.Count > 0)
                {
                    IQueryFilter pQuFilter          = new QueryFilter();
                    string       sCat               = LineSelection.Target.Fields.get_Field(idxCategory).Name;
                    string       sToPt              = LineSelection.Target.Fields.get_Field(idxToPointID).Name;
                    string       sFromPt            = LineSelection.Target.Fields.get_Field(idxFromPointID).Name;
                    string       sParcelID          = LineSelection.Target.Fields.get_Field(idxParcelID).Name;
                    string       sInClauseToPts     = "(";
                    string       sInClauseFromPts   = "(";
                    string       sInClauseParcelIds = "(";
                    //**SAMPLE CODE NOTE** :
                    //The following In Clause, when contructed for production environments
                    //should take into account the token limit on Oracle database platforms. (<1000)
                    // the processing of the in clause should be broekn into blocks with the in cluase has no more than 1000 elements
                    foreach (int[] iParcelIdCtrPtIdFromId1FromId2 in ListFromToPairsForRadialLines)
                    {
                        if (sInClauseParcelIds.Length == 1)
                        {
                            sInClauseParcelIds += iParcelIdCtrPtIdFromId1FromId2[0].ToString();
                        }
                        else
                        {
                            sInClauseParcelIds += "," + iParcelIdCtrPtIdFromId1FromId2[0].ToString();
                        }

                        if (sInClauseToPts.Length == 1)
                        {
                            sInClauseToPts += iParcelIdCtrPtIdFromId1FromId2[1].ToString();
                        }
                        else
                        {
                            sInClauseToPts += "," + iParcelIdCtrPtIdFromId1FromId2[1].ToString();
                        }

                        if (sInClauseFromPts.Length == 1)
                        {
                            sInClauseFromPts += iParcelIdCtrPtIdFromId1FromId2[2].ToString();
                            sInClauseFromPts += "," + iParcelIdCtrPtIdFromId1FromId2[3].ToString();
                        }
                        else
                        {
                            sInClauseFromPts += "," + iParcelIdCtrPtIdFromId1FromId2[2].ToString();
                            sInClauseFromPts += "," + iParcelIdCtrPtIdFromId1FromId2[2].ToString();
                        }
                    }

                    pQuFilter.WhereClause = sCat + " = 4 AND " + sParcelID + " IN " + sInClauseParcelIds
                                            + ") AND " + sFromPt + " IN " + sInClauseFromPts
                                            + ") AND " + sToPt + " IN " + sInClauseToPts + ")";
                    LineSelection.Target.DeleteSearchedRows(pQuFilter);
                }

                //with the new information added to the line, the rest of the parcel needs to be updated
                //regenerate the parcel using the parcel fidset

                ICadastralFabricRegeneration pRegenFabric = new CadastralFabricRegenerator();
                #region regenerator enum
                // enum esriCadastralRegeneratorSetting
                // esriCadastralRegenRegenerateGeometries         =   1
                // esriCadastralRegenRegenerateMissingRadials     =   2,
                // esriCadastralRegenRegenerateMissingPoints      =   4,
                // esriCadastralRegenRemoveOrphanPoints           =   8,
                // esriCadastralRegenRemoveInvalidLinePoints      =   16,
                // esriCadastralRegenSnapLinePoints               =   32,
                // esriCadastralRegenRepairLineSequencing         =   64,
                // esriCadastralRegenRepairPartConnectors         =   128

                // By default, the bitmask member is 0 which will only regenerate geometries.
                // (equivalent to passing in regeneratorBitmask = 1)
                #endregion

                pRegenFabric.CadastralFabric    = pCadEd.CadastralFabric;
                pRegenFabric.RegeneratorBitmask = 7;
                pRegenFabric.RegenerateParcels(pFIDSetForParcelRegen, false, pTrackCancel);

                //15 (enum values of 8 means remove orphan points; this only works when doing entire fabric)
                //TODO: remove orphaned center points programmatically
                pStepProgressor.MinRange    = 0;
                pStepProgressor.MaxRange    = iChangeCount;
                pStepProgressor.StepValue   = 1;
                pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral;
                pRegenFabric.RegenerateParcels(pFIDSetForParcelRegen, false, pTrackCancel);

                ArcMap.Editor.StopOperation("Change line radius");
            }
            catch (Exception ex)
            {
                ArcMap.Editor.AbortOperation();
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (pSchemaEd != null)
                {
                    pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints);
                    pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTLines);
                }
                pStepProgressor = null;
                if (!(pProgressorDialog == null))
                {
                    pProgressorDialog.HideDialog();
                }
                pProgressorDialog = null;

                RefreshMap(LineLayerArray);
                ICadastralExtensionManager pCExMan = (ICadastralExtensionManager)pCadEd;
                IParcelPropertiesWindow2   pPropW  = (IParcelPropertiesWindow2)pCExMan.ParcelPropertiesWindow;
                pPropW.RefreshAll();
                //update the TOC
                IMxDocument mxDocument = (ESRI.ArcGIS.ArcMapUI.IMxDocument)(ArcMap.Application.Document);
                for (int i = 0; i < mxDocument.ContentsViewCount; i++)
                {
                    IContentsView pCV = (IContentsView)mxDocument.get_ContentsView(i);
                    pCV.Refresh(null);
                }
            }
        }
Ejemplo n.º 10
0
        public static void ConvertLabels2Anno(IMap imap_0, IGeoFeatureLayer igeoFeatureLayer_0, string string_0,
                                              double double_0)
        {
            int i;
            IAnnotateLayerProperties igeoFeatureLayer0;
            IElementCollection       elementCollection;
            IElementCollection       elementCollection1;
            IElementCollection       elementCollection2;
            IElement    element;
            int         num;
            IActiveView imap0 = imap_0 as IActiveView;
            int         j     = 0;
            int         count = 0;
            IAnnotateLayerPropertiesCollection annotateLayerPropertiesCollectionClass =
                new AnnotateLayerPropertiesCollection();
            IAnnotateLayerPropertiesCollection annotationProperties = igeoFeatureLayer_0.AnnotationProperties;

            for (i = 0; i < annotationProperties.Count; i++)
            {
                annotationProperties.QueryItem(i, out igeoFeatureLayer0, out elementCollection, out elementCollection1);
                if (igeoFeatureLayer0 != null)
                {
                    annotateLayerPropertiesCollectionClass.Add(
                        (igeoFeatureLayer0 as IClone).Clone() as IAnnotateLayerProperties);
                }
            }
            igeoFeatureLayer0 = null;
            IOverposterProperties overposterProperties = (imap_0 as IMapOverposter).OverposterProperties;
            IGraphicsLayer        double0 = (imap_0.BasicGraphicsLayer as ICompositeGraphicsLayer).AddLayer(string_0,
                                                                                                            igeoFeatureLayer_0);

            (double0 as IGraphicsLayerScale).ReferenceScale = double_0;
            double0.Activate(imap0.ScreenDisplay);
            for (i = 0; i < annotateLayerPropertiesCollectionClass.Count; i++)
            {
                annotateLayerPropertiesCollectionClass.QueryItem(i, out igeoFeatureLayer0, out elementCollection,
                                                                 out elementCollection1);
                if (igeoFeatureLayer0 != null)
                {
                    igeoFeatureLayer0.FeatureLayer      = igeoFeatureLayer_0;
                    igeoFeatureLayer0.GraphicsContainer = double0 as IGraphicsContainer;
                    igeoFeatureLayer0.AddUnplacedToGraphicsContainer = false;
                    igeoFeatureLayer0.CreateUnplacedElements         = true;
                    igeoFeatureLayer0.DisplayAnnotation  = true;
                    igeoFeatureLayer0.FeatureLinked      = false;
                    igeoFeatureLayer0.LabelWhichFeatures = esriLabelWhichFeatures.esriAllFeatures;
                    igeoFeatureLayer0.UseOutput          = true;
                    ((igeoFeatureLayer0 as ILabelEngineLayerProperties2).OverposterLayerProperties as
                     IOverposterLayerProperties2).TagUnplaced = true;
                }
            }
            annotateLayerPropertiesCollectionClass.Sort();
            IAnnotateMapProperties annotateMapPropertiesClass = new AnnotateMapProperties()
            {
                AnnotateLayerPropertiesCollection = annotateLayerPropertiesCollectionClass
            };
            ITrackCancel cancelTrackerClass = new CancelTracker();

            (imap_0.AnnotationEngine as IAnnotateMap2).Label(overposterProperties, annotateMapPropertiesClass, imap_0,
                                                             cancelTrackerClass);
            for (i = 0; i < annotateLayerPropertiesCollectionClass.Count; i++)
            {
                annotateLayerPropertiesCollectionClass.QueryItem(i, out igeoFeatureLayer0, out elementCollection,
                                                                 out elementCollection2);
                if (igeoFeatureLayer0 != null)
                {
                    count = count + elementCollection2.Count;
                    if (elementCollection2.Count > 0)
                    {
                        IOverflowGraphicsContainer overflowGraphicsContainer = double0 as IOverflowGraphicsContainer;
                        for (j = 0; j < elementCollection2.Count; j++)
                        {
                            elementCollection2.QueryItem(j, out element, out num);
                            overflowGraphicsContainer.AddOverflowElement(element);
                        }
                    }
                    igeoFeatureLayer0.FeatureLayer = null;
                }
            }
            igeoFeatureLayer_0.DisplayAnnotation = false;
            imap0.ContentsChanged();
            imap0.Refresh();
        }
Ejemplo n.º 11
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;
            }
        }
Ejemplo n.º 12
0
 public SimpleActivity()
 {
     _sourceData.DirtyEvent += new EventHandler(_sourceData_DirtyEvent);
     _targetData.DirtyEvent += new EventHandler(_targetData_DirtyEvent);
     _cancelTracker          = new CancelTracker();
 }
Ejemplo n.º 13
0
        protected override void OnClick()
        {
            //go get a traverse file
            // Display .Net dialog for File selection.
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // Set File Filter
            openFileDialog.Filter = "Cadastral XML file (*.xml)|*.xml";
            // Enable multi-select
            openFileDialog.Multiselect = true;
            // Don't need to Show Help
            openFileDialog.ShowHelp = false;
            // Set Dialog Title
            openFileDialog.Title       = "Append Cadastral XML files";
            openFileDialog.FilterIndex = 2;
            // Display Open File Dialog
            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                openFileDialog = null;
                return;
            }

            //Get the cadastral editor
            ICadastralEditor pCadEd     = (ICadastralEditor)ArcMap.Application.FindExtensionByName("esriCadastralUI.CadastralEditorExtension");
            ICadastralFabric pCadFabric = pCadEd.CadastralFabric;
            IEditor          pEd        = ArcMap.Editor;

            ITrackCancel pTrkCan = new CancelTracker();
            // Create and display the Progress Dialog
            IProgressDialogFactory pProDlgFact = new ProgressDialogFactory();
            IProgressDialog2       pProDlg     = pProDlgFact.Create(pTrkCan, 0) as IProgressDialog2;

            //Set the properties of the Progress Dialog
            pProDlg.CancelEnabled = true;
            pProDlg.Description   = "    ";
            pProDlg.Title         = "Append";
            pProDlg.Animation     = esriProgressAnimationTypes.esriProgressGlobe;
            string sCopiedCadastralXMLFile = "";

            try
            {
                ICadastralJob CadaJob;
                bool          bJobExists = false; //used to trap for the special error message condition of existing job
                pEd.StartOperation();

                #region workaround for setting Projection
                ICadastralJob CadaJobTemp;
                bJobExists = false;
                if (!CreateCadastralJob(pCadFabric, "TEMPJOB", out CadaJobTemp, true, ref bJobExists))
                {
                    if (!bJobExists) // if the create job failed for some other reason than it already exists, then bail out.
                    {
                        MessageBox.Show("Job could not be created.");
                        return;
                    }
                }
                //do an extract to set the spatial reference: bug workaround
                ((ICadastralFabric3)pCadFabric).ExtractCadastralPacket(CadaJobTemp.Name, ArcMap.Document.ActiveView.FocusMap.SpatialReference as IProjectedCoordinateSystem, null, true);
                #endregion

                //make a temporary file for the edited cadastral XML that is used for the fabric update
                string sTempPath = System.IO.Path.GetTempPath();
                sCopiedCadastralXMLFile = System.IO.Path.Combine(sTempPath, "LastUpdatedCadastralXMLAppendedFromBatch.xml");
                int iFileCount  = 0;
                int iTotalFiles = openFileDialog.FileNames.GetLength(0);

                List <string> lstPlans = new List <string>();
                #region get all plan names for all files
                foreach (String CadastralXMLPath in openFileDialog.FileNames)
                {
                    TextReader tr = null;
                    try
                    {
                        tr = new StreamReader(CadastralXMLPath);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return;
                    }

                    //          string[] sFileLine = new string[0]; //define as dynamic array
                    string sLine       = "";
                    int    iCount      = 0;
                    bool   bInPlanData = false;
                    bool   bInParcel   = false;

                    //fill the array with the lines from the file
                    while (sLine != null)
                    {
                        sLine = tr.ReadLine();
                        try
                        {
                            if (sLine.Trim().Length >= 1) //test for empty lines
                            {
                                if (!bInParcel && !bInPlanData)
                                {
                                    bInPlanData = sLine.Contains("<plan>");
                                }

                                if (bInPlanData && sLine.Contains("<name>") && sLine.Contains("</name>"))
                                {
                                    string sPlanName = sLine.Replace("<name>", "").Replace("</name>", "").Replace("\t", "").Trim();
                                    if (!lstPlans.Contains(sPlanName))
                                    {
                                        lstPlans.Add(sPlanName);
                                    }
                                    bInPlanData = false;
                                }
                            }
                            iCount++;
                        }
                        catch { }
                    }
                    tr.Close(); //close the file and release resources
                }
                string sInClause = "";
                foreach (string sPlan in lstPlans)
                {
                    sInClause += "'" + sPlan + "'" + ",";
                }

                sInClause = sInClause.Remove(sInClause.LastIndexOf(","), 1);

                ITable       pPlansTable = pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans);
                int          iNameFld    = pPlansTable.FindField("Name");
                IQueryFilter pQuFilter   = new QueryFilterClass();
                pQuFilter.WhereClause = "NAME IN (" + sInClause + ")";
                ICursor       pCur           = pPlansTable.Search(pQuFilter, false);
                List <string> lstPlanReplace = new List <string>();

                IRow pPlan = pCur.NextRow();
                while (pPlan != null)
                {
                    lstPlanReplace.Add("<name>" + (string)pPlan.Value[iNameFld] + "</name>\n\t\t<oID>" + pPlan.OID.ToString() + "</oID>");
                    Marshal.ReleaseComObject(pPlan);
                    pPlan = pCur.NextRow();
                }
                Marshal.ReleaseComObject(pCur);

                #endregion

                foreach (String CadastralXMLPath in openFileDialog.FileNames)
                {
                    if (!pTrkCan.Continue())
                    {
                        pEd.AbortOperation();
                        return;
                    }

                    //rename ALL oID tags so that they're ignored. This indicates that these are to be treated as NEW parcels coming in.
                    ReplaceInFile(CadastralXMLPath, sCopiedCadastralXMLFile, "oID>", "old_xxX>");

                    foreach (string sPlanTag in lstPlanReplace)
                    {
                        string sFirstPart = sPlanTag.Substring(0, sPlanTag.IndexOf("\n"));
                        ReplaceInFile(sCopiedCadastralXMLFile, sCopiedCadastralXMLFile, sFirstPart, sPlanTag);
                    }

                    //TEST ONLY
                    //ReplaceInFile(CadastralXMLPath, sCopiedCadastralXMLFile, "oID>", "oID>");

                    //IF using PostCadastralPacket the points are not all merged. If using PostCadastralPacket, then a merge-point workaround would be to analyze coordinates
                    //of incoming file and if any are identical to existing fabric coordinates, then make the oID tag match
                    //the oID of the existing point in the target fabric. This will trigger point merging of identical points when using PostCadastralPacket.
                    //code below uses InsertCadastralPacket and so point merging is handled.

                    IXMLStream pStream = new XMLStream();
                    pStream.LoadFromFile(sCopiedCadastralXMLFile);
                    IFIDSet pFIDSet = null;//new FIDSet();

                    DateTime localNow = DateTime.Now;
                    string   sJobName = Convert.ToString(localNow) + "_" + (iFileCount++).ToString();
                    // note the create option is to NOT write job to fabric and is in-memory only initially, and then the InsertCadastralPacket will create and store the job in the fabric
                    // IF using PostCadastralPacket, then this option should be set to true, so that the job already exists in the fabric.
                    // Also, when using PostCadastralPacket, you can continue to use the same Target job, and a new one is not needed for each iteration.
                    // With InsertCadastralPacket a job is created for each call when new parcels are being created.
                    if (!CreateCadastralJob(pCadFabric, sJobName, out CadaJob, false, ref bJobExists))
                    {
                        pEd.AbortOperation();
                        return;
                    }

                    pProDlg.Description = "File: " + System.IO.Path.GetFileName(CadastralXMLPath) + " (" + iFileCount.ToString() + " of " + iTotalFiles.ToString() + ")";
                    //(pCadFabric as ICadastralFabric3).PostCadastralPacket(pStream, pTrkCan, esriCadastralPacketSetting.esriCadastralPacketNoSetting, ref pFIDSet);
                    (pCadFabric as ICadastralFabric3).InsertCadastralPacket(CadaJob, pStream, pTrkCan, esriCadastralPacketSetting.esriCadastralPacketNoSetting, ref pFIDSet);
                    //int setCnt = pFIDSet.Count();
                }
                RefreshFabricLayers(ArcMap.Document.ActiveView.FocusMap, pCadFabric);
                pEd.StopOperation("Append " + iFileCount.ToString() + " cadastral XML files");
            }
            catch (Exception ex)
            {
                pEd.AbortOperation();
                COMException c_Ex;
                int          errorCode = 0;
                if (ex is COMException)
                {
                    c_Ex      = (COMException)ex;
                    errorCode = c_Ex.ErrorCode;
                }
                if (errorCodeDict.ContainsKey(errorCode))
                {
                    MessageBox.Show(errorCodeDict[errorCode], "Append files");
                }
                else
                {
                    MessageBox.Show("Error: " + ex.Message + Environment.NewLine + ex.HResult.ToString(), "Append files");
                }
            }
            finally
            {
                if (sCopiedCadastralXMLFile != string.Empty)
                {
                    File.Delete(sCopiedCadastralXMLFile);
                }
                if (pProDlg != null)
                {
                    pProDlg.HideDialog();
                }
            }
        }
Ejemplo n.º 14
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);
        }
        protected override void OnMouseDown(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg)
        {
            int X = arg.X;
            int Y = arg.Y;
            IMxApplication pMxApp = null;
            IMxDocument pMxDoc = null;
            pMxApp = (IMxApplication)ArcMap.Application;
            pMxDoc = (IMxDocument)ArcMap.Application.Document;

            // calculate tolerance rectangle to identify features inside it
            int Tolerance = 0;
            Tolerance = pMxDoc.SearchTolerancePixels;

            IDisplayTransformation pDispTrans = null;
            pDispTrans = pMxApp.Display.DisplayTransformation;
            tagRECT pToleranceRect = new tagRECT();
            pToleranceRect.left = X - Tolerance;
            pToleranceRect.right = X + Tolerance;
            pToleranceRect.top = Y - Tolerance;
            pToleranceRect.bottom = Y + Tolerance;

            IEnvelope pSearchEnvelope = null;
            pSearchEnvelope = new EnvelopeClass();
            pDispTrans.TransformRect(pSearchEnvelope, ref pToleranceRect, (int)(esriDisplayTransformationEnum.esriTransformPosition | esriDisplayTransformationEnum.esriTransformToMap));

            // identify feature points of measurement
            IBasicDocument pBasicDoc = null;
            pBasicDoc = (IBasicDocument)ArcMap.Application.Document;
            pSearchEnvelope.SpatialReference = pMxDoc.ActiveView.FocusMap.SpatialReference;

            IIdentify pIdentify = null;
            pIdentify = (IIdentify)pMxDoc.FocusMap.get_Layer(0);
            if (pIdentify == null)
            {
                MessageBox.Show("No layer");
                return;
            }

            IArray pIDArray = null;
            pIDArray = pIdentify.Identify(pSearchEnvelope);

            // get object from feature point
            IIdentifyObj pIDObj = null;
            if (pIDArray != null)
                pIDObj = (IIdentifyObj)pIDArray.get_Element(0);

            if (pIDObj == null)
            {
                MessageBox.Show("No feature was identified");
                return;
            }

            // get the name of the layer containing feature points
            ILayer pLayer = null;
            pLayer = pMxDoc.FocusMap.get_Layer(0);

            string layerName = null;
            layerName = pLayer.Name;

            // get primary display field for measurement values and set names of a date/time field and gage ID field
            IFeatureLayer pFeatLayer = null;
            pFeatLayer = (IFeatureLayer)pLayer;
            string dataFldName = null;
            string timefldName = null;
            string gageIDFldName = null;
            dataFldName = "TSValue";
            timefldName = "TSDateTime"; // substitute data/time field name for different dataset
            gageIDFldName = "Name"; // substitute gage ID field name for different dataset

            // get display table from layer
            ITable pTable = null;
            IDisplayTable pDisplayTable = null;
            pDisplayTable = (IDisplayTable)pLayer;
            if (pDisplayTable != null)
            {
                pTable = pDisplayTable.DisplayTable;
                if (pTable == null)
                    goto THEEND;
            }

            // get fields from display table
            IFields pFields = null;
            pFields = pTable.Fields;
            long fldCount = 0;
            fldCount = pFields.FieldCount;

            // create WHERE clause from identified objects of measurement points
            int gageIDFldIdx = 0;
            gageIDFldIdx = pFields.FindField(gageIDFldName);

            IRowIdentifyObject pRowIDObj = null;
            pRowIDObj = (IRowIdentifyObject)pIDObj;

            string gageID = null;
            gageID = (string)pRowIDObj.Row.get_Value(gageIDFldIdx);

            IFeatureLayerDefinition pFeatureLayerDef = null;
            pFeatureLayerDef = (IFeatureLayerDefinition)pLayer;
            string definitionExpression = null;
            definitionExpression = pFeatureLayerDef.DefinitionExpression;

            string whereClause = null;
            if (definitionExpression == "")
                whereClause = "[" + gageIDFldName + "] = '" + gageID + "'";
            else
                whereClause = "[" + gageIDFldName + "] = '" + gageID + "' AND " + definitionExpression;

            //find color for the identified object from feature layer's renderer
            IGeoFeatureLayer pGeoFeatureLayer = null;
            pGeoFeatureLayer = (IGeoFeatureLayer)pLayer;

            ILookupSymbol pLookupSymbol = null;
            pLookupSymbol = (ILookupSymbol)pGeoFeatureLayer.Renderer;

            IFeature pFeature = null;
            pFeature = (IFeature)pRowIDObj.Row;

            IMarkerSymbol pSymbol = null;
            pSymbol = (IMarkerSymbol)pLookupSymbol.LookupSymbol(false, pFeature);

            // Find an opened GraphWindow
            IDataGraphBase pDataGraphBase = null;
            IDataGraphT pDataGraphT = null;
            IDataGraphWindow2 pDGWin = null;

            IDataGraphCollection pDataGraphs = null;
            pDataGraphs = (IDataGraphCollection)pMxDoc;
            int grfCount = 0;
            grfCount = pDataGraphs.DataGraphCount;
            for (int i = 0; i < grfCount; i++)
            {
                pDataGraphBase = pDataGraphs.get_DataGraph(i);
                pDGWin = FindGraphWindow(ref pDataGraphBase);
                if (pDGWin != null)
                    break;
            }

            // if there is not an opened graph window - create a new graph for
            if (pDGWin == null)
            {
                // create graph
                pDataGraphT = new DataGraphTClass();
                pDataGraphBase = (IDataGraphBase)pDataGraphT;

                // load template from <ARCGISHOME>\GraphTemplates\
                string strPath = null;
                strPath = Environment.GetEnvironmentVariable("ARCGISHOME");
                try
                {
                    pDataGraphT.LoadTemplate(strPath + @"GraphTemplates\timeseries.tee");
                }
                catch
                { }

                // graph, axis and legend titles. Substitute them for different input layer
                pDataGraphT.GeneralProperties.Title = "Daily Streamflow for Guadalupe Basin in 1999";
                pDataGraphT.LegendProperties.Title = "Monitoring Point";
                pDataGraphT.get_AxisProperties(0).Title = "Streamflow (cfs)";
                pDataGraphT.get_AxisProperties(0).Logarithmic = true;
                pDataGraphT.get_AxisProperties(2).Title = "Date";
                pDataGraphBase.Name = layerName;
            }
            else // get graph from the opened window
                pDataGraphT = (IDataGraphT)pDataGraphBase;

            // create vertical line series for all measurements for the identified gage
            ISeriesProperties pSP = null;
            pSP = pDataGraphT.AddSeries("line:vertical");
            pSP.ColorType = esriGraphColorType.esriGraphColorCustomAll;
            pSP.CustomColor = pSymbol.Color.RGB;
            pSP.WhereClause = whereClause;
            pSP.InLegend = true;
            pSP.Name = gageID;

            pSP.SourceData = pLayer;
            pSP.SetField(0, timefldName);
            pSP.SetField(1, dataFldName);
            IDataSortSeriesProperties pSortFlds = null;
            pSortFlds = (IDataSortSeriesProperties)pSP;
            int idx = 0;
            pSortFlds.AddSortingField(timefldName, true, ref idx);


            pDataGraphBase.UseSelectedSet = true;

            ITrackCancel pCancelTracker = null;
            pCancelTracker = new CancelTracker();
            pDataGraphT.Update(pCancelTracker);

            // create data graph window if there is not any opened one
            if (pDGWin == null)
            {
                pDGWin = new DataGraphWindowClass();
                pDGWin.DataGraphBase = pDataGraphBase;
                pDGWin.Application = ArcMap.Application;
                pDGWin.Show(true);

                pDataGraphs.AddDataGraph(pDataGraphBase);
            }

        THEEND:
            return;

            //base.OnMouseDown(arg);
        }
Ejemplo n.º 16
0
        public void FinishDrawing(IDisplay disp, ICancelTracker cancelTracker)
        {
            if (cancelTracker == null)
            {
                cancelTracker = new CancelTracker();
            }

            try
            {
                if (cancelTracker.Continue)
                {
                    // also draw empty aggregates (a MUST for PoygonMask!!)
                    if (_aggregateGeometry == null)
                    {
                        _aggregateGeometry = new AggregateGeometry();
                    }

                    if (_symbol is ISymbolCollection)
                    {
                        ISymbolCollection sColl = (ISymbolCollection)_symbol;
                        foreach (ISymbolCollectionItem symbolItem in sColl.Symbols)
                        {
                            if (symbolItem.Visible == false || symbolItem.Symbol == null)
                            {
                                continue;
                            }

                            ISymbol symbol = symbolItem.Symbol;

                            if (symbol.SupportsGeometryType(geometryType.Aggregate))
                            {
                                disp.Draw(symbol, _aggregateGeometry);
                            }
                            else
                            {
                                for (int g = 0; g < _aggregateGeometry.GeometryCount; g++)
                                {
                                    disp.Draw(symbol, _aggregateGeometry[g]);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (_symbol.SupportsGeometryType(geometryType.Aggregate))
                        {
                            disp.Draw(_symbol, _aggregateGeometry);
                        }
                        else
                        {
                            for (int g = 0; g < _aggregateGeometry.GeometryCount; g++)
                            {
                                disp.Draw(_symbol, _aggregateGeometry[g]);
                            }
                        }
                    }
                }
            }
            finally
            {
                _aggregateGeometry = null;
            }
        }
Ejemplo n.º 17
0
        public static void ConvertLabels2StandardAnno(IMap imap_0, ILayer ilayer_0, string string_0)
        {
            int i;
            IAnnotateLayerProperties     annotateLayerProperty;
            IElementCollection           elementCollection;
            IElementCollection           elementCollection1;
            ILabelEngineLayerProperties2 d;
            ISymbolIdentifier2           symbolIdentifier2;
            IActiveView imap0 = imap_0 as IActiveView;

            if (ilayer_0 is IGeoFeatureLayer)
            {
                IGeoFeatureLayer ilayer0   = ilayer_0 as IGeoFeatureLayer;
                IWorkspace       workspace = (ilayer0 as IDataset).Workspace;
                if (workspace.Type != esriWorkspaceType.esriFileSystemWorkspace)
                {
                    IFeatureClass           featureClass = ilayer0.FeatureClass;
                    IGeoDataset             geoDataset   = featureClass as IGeoDataset;
                    IAnnotationLayerFactory fDOGraphicsLayerFactoryClass =
                        new FDOGraphicsLayerFactory() as IAnnotationLayerFactory;
                    ISymbolCollection2 symbolCollectionClass = new SymbolCollection() as ISymbolCollection2;
                    IAnnotateLayerPropertiesCollection annotateLayerPropertiesCollectionClass =
                        new AnnotateLayerPropertiesCollection();
                    IAnnotateLayerPropertiesCollection annotationProperties = ilayer0.AnnotationProperties;
                    for (i = 0; i < annotationProperties.Count; i++)
                    {
                        annotationProperties.QueryItem(i, out annotateLayerProperty, out elementCollection,
                                                       out elementCollection1);
                        if (annotateLayerProperty != null)
                        {
                            annotateLayerPropertiesCollectionClass.Add(annotateLayerProperty);
                            d = annotateLayerProperty as ILabelEngineLayerProperties2;
                            IClone symbol = d.Symbol as IClone;
                            symbolCollectionClass.AddSymbol(symbol.Clone() as ISymbol,
                                                            string.Concat(annotateLayerProperty.Class, " ", i.ToString()), out symbolIdentifier2);
                            d.SymbolID = symbolIdentifier2.ID;
                        }
                    }
                    annotateLayerProperty = null;
                    d = null;
                    IGraphicsLayerScale graphicsLayerScaleClass = new GraphicsLayerScale();
                    if (imap_0.ReferenceScale != 0)
                    {
                        graphicsLayerScaleClass.ReferenceScale = imap_0.ReferenceScale;
                    }
                    else
                    {
                        try
                        {
                            graphicsLayerScaleClass.ReferenceScale = imap_0.MapScale;
                        }
                        catch (Exception exception)
                        {
                            Logger.Current.Error("", exception, null);
                        }
                    }
                    graphicsLayerScaleClass.Units = imap_0.MapUnits;
                    IFeatureClassDescription annotationFeatureClassDescriptionClass =
                        new AnnotationFeatureClassDescription() as IFeatureClassDescription;
                    IFields requiredFields =
                        (annotationFeatureClassDescriptionClass as IObjectClassDescription).RequiredFields;
                    IField field =
                        requiredFields.Field[
                            requiredFields.FindField(annotationFeatureClassDescriptionClass.ShapeFieldName)];
                    IGeometryDefEdit geometryDef = field.GeometryDef as IGeometryDefEdit;
                    geometryDef.SpatialReference_2 = geoDataset.SpatialReference;
                    IOverposterProperties overposterProperties = (imap_0 as IMapOverposter).OverposterProperties;
                    IAnnotationLayer      annotationLayer      =
                        fDOGraphicsLayerFactoryClass.CreateAnnotationLayer(workspace as IFeatureWorkspace,
                                                                           featureClass.FeatureDataset, string_0, geometryDef, null,
                                                                           annotateLayerPropertiesCollectionClass, graphicsLayerScaleClass,
                                                                           symbolCollectionClass as ISymbolCollection, true, true, false, true, overposterProperties,
                                                                           "");
                    (annotationLayer as IGraphicsLayer).Activate(imap0.ScreenDisplay);
                    for (i = 0; i < annotateLayerPropertiesCollectionClass.Count; i++)
                    {
                        annotateLayerPropertiesCollectionClass.QueryItem(i, out annotateLayerProperty,
                                                                         out elementCollection, out elementCollection1);
                        if (annotateLayerProperty != null)
                        {
                            annotateLayerProperty.FeatureLayer      = ilayer0;
                            annotateLayerProperty.GraphicsContainer = annotationLayer as IGraphicsContainer;
                            annotateLayerProperty.AddUnplacedToGraphicsContainer = true;
                            annotateLayerProperty.CreateUnplacedElements         = true;
                            annotateLayerProperty.DisplayAnnotation  = true;
                            annotateLayerProperty.FeatureLinked      = true;
                            annotateLayerProperty.LabelWhichFeatures = esriLabelWhichFeatures.esriAllFeatures;
                            annotateLayerProperty.UseOutput          = true;
                            d                   = annotateLayerProperty as ILabelEngineLayerProperties2;
                            d.SymbolID          = i;
                            d.AnnotationClassID = i;
                            (d.OverposterLayerProperties as IOverposterLayerProperties2).TagUnplaced = true;
                        }
                    }
                    annotateLayerPropertiesCollectionClass.Sort();
                    IAnnotateMapProperties annotateMapPropertiesClass = new AnnotateMapProperties()
                    {
                        AnnotateLayerPropertiesCollection = annotateLayerPropertiesCollectionClass
                    };
                    ITrackCancel cancelTrackerClass = new CancelTracker();
                    (imap_0.AnnotationEngine as IAnnotateMap2).Label(overposterProperties, annotateMapPropertiesClass,
                                                                     imap_0, cancelTrackerClass);
                    for (i = 0; i < annotateLayerPropertiesCollectionClass.Count; i++)
                    {
                        annotateLayerPropertiesCollectionClass.QueryItem(i, out annotateLayerProperty,
                                                                         out elementCollection, out elementCollection1);
                        if (annotateLayerProperty != null)
                        {
                            annotateLayerProperty.FeatureLayer = null;
                        }
                    }
                    imap_0.AddLayer(annotationLayer as ILayer);
                    ilayer0.DisplayAnnotation = false;
                    imap0.Refresh();
                }
            }
        }
Ejemplo n.º 18
0
        private void CreateBatchFile()
        {
            string path             = "";
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                path = fbd.SelectedPath;
            }

            if (!Directory.Exists(path))
            {
                Utilities_MessageBox.ErrorBox("Path Does Not Exist", MB_TITLE);
                return;
            }

            int    versionCount = 1; // This is used to make mutiple files so the batch file don't overwrite on another.
            string filePath     = path + string.Format(@"\{0}_{1}_{2}.bat", cbo_TileIndex.Text, "CopyFiles", versionCount);

            while (File.Exists(filePath))
            {
                versionCount++;
                filePath = path + string.Format(@"\{0}_{1}_{2}.bat", cbo_TileIndex.Text, "CopyFiles", versionCount);
            }



            bool itWorked = false;



            int                    cloneCount            = 1; // labeling the processor bar
            ITrackCancel           trackcancel           = new CancelTracker();
            IProgressDialogFactory progressdialogfactory = new ProgressDialogFactoryClass();
            IStepProgressor        stepprogressor        = progressdialogfactory.Create(trackcancel, _application.hWnd);

            stepprogressor.MinRange  = 0;
            stepprogressor.MaxRange  = _fileList.Count;
            stepprogressor.StepValue = 1;
            stepprogressor.Message   = "Generating...";
            IProgressDialog2 progressdialog = (IProgressDialog2)stepprogressor; // Creates and displays

            progressdialog.CancelEnabled = false;
            progressdialog.Description   = "Prepping {_fileList.Count} files...";
            progressdialog.Title         = MB_TITLE;
            progressdialog.Animation     = esriProgressAnimationTypes.esriProgressSpiral;


            foreach (KeyValuePair <String, Boolean> file in _fileList)
            {
                if (file.Value)
                {
                    progressdialog.Description = string.Format("Adding File {0} of {1}...", cloneCount, _fileList.Count);
                    if (!itWorked)
                    {
                        SaveFileTypeList(GetExtension());
                    }
                    itWorked = true;

                    try
                    {
                        var sourceFile      = txb_FileWorkspaceSrc.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension();
                        var destinationFile = txb_FileWorkspaceDst.Text + @"\" + Utilities_General.AddPrefixAndSuffixToFileName(file.Key, txb_Prefix.Text, txb_Suffix.Text) + GetExtension();

                        using (System.IO.StreamWriter sw = File.AppendText(filePath))
                        {
                            sw.WriteLine(String.Format("copy {0} {1}", sourceFile, destinationFile));
                        }
                    }
                    catch (Exception yourBest) // but you don't succeed
                    {
                        yourBest.ToString();
                        // Just So We Get No Crashes ;)
                    }
                    stepprogressor.Step();
                    cloneCount++;
                }
            }
            trackcancel    = null;
            stepprogressor = null;
            progressdialog.HideDialog();
            progressdialog = null;
            //_activeView.Refresh();
        }
Ejemplo n.º 19
0
 public SpatialIndexShrinker()
 {
     _cancelTracker = new CancelTracker();
 }
Ejemplo n.º 20
0
        private IRasterPaintContext PaintImage(int x, int y, int wWidth, int wHeight, int iWidth, int iHeight, ICancelTracker cancelTracker)
        {
            if (CancelTracker.Canceled(cancelTracker) || _gDS == null)
            {
                return(null);
            }

            int pixelSpace = 3;
            var bitmap     = Current.Engine.CreateBitmap(iWidth, iHeight, GraphicsEngine.PixelFormat.Rgb24);
            var bitmapData = bitmap.LockBitmapPixelData(BitmapLockMode.WriteOnly, GraphicsEngine.PixelFormat.Rgb24);

            try
            {
                int    stride = bitmapData.Stride;
                IntPtr buf    = bitmapData.Scan0;

                List <ArgbColor> colors = new List <ArgbColor>();
                for (int i = 1; i <= (_gDS.RasterCount > 3 ? 3 : _gDS.RasterCount); ++i)
                {
                    using (OSGeo_v1.GDAL.Band band = _gDS.GetRasterBand(i))
                    {
                        int ch = 0;
                        switch ((ColorInterp)band.GetRasterColorInterpretation())
                        {
                        case ColorInterp.BlueBand:
                            ch = 0;
                            break;

                        case ColorInterp.GreenBand:
                            ch = 1;
                            break;

                        case ColorInterp.RedBand:
                            ch = 2;
                            break;

                        case ColorInterp.GrayIndex:
                            for (int iColor = 0; iColor < 256; iColor++)
                            {
                                colors.Add(ArgbColor.FromArgb(255, iColor, iColor, iColor));
                            }
                            break;

                        case ColorInterp.PaletteIndex:
                            OSGeo_v1.GDAL.ColorTable colTable = band.GetRasterColorTable();
                            if (colTable == null)
                            {
                                break;
                            }

                            int colCount = colTable.GetCount();
                            for (int iColor = 0; iColor < colCount; iColor++)
                            {
                                OSGeo_v1.GDAL.ColorEntry colEntry = colTable.GetColorEntry(iColor);
                                colors.Add(ArgbColor.FromArgb(
                                               colEntry.c4, colEntry.c1, colEntry.c2, colEntry.c3));
                            }

                            break;
                        }
                        band.ReadRaster(x, y, wWidth, wHeight,
                                        new IntPtr(buf.ToInt64() + ch),
                                        iWidth, iHeight, OSGeo_v1.GDAL.DataType.GDT_Byte, pixelSpace, stride);
                    }
                }
                if (colors.Count > 0)
                {
                    unsafe
                    {
                        byte *ptr = (byte *)(bitmapData.Scan0);
                        for (int i = 0; i < bitmapData.Height; i++)
                        {
                            if (CancelTracker.Canceled(cancelTracker))
                            {
                                return(null);
                            }

                            for (int j = 0; j < bitmapData.Width; j++)
                            {
                                // write the logic implementation here
                                byte      c   = ptr[0];
                                ArgbColor col = colors[c];
                                ptr[0] = col.B;
                                ptr[1] = col.G;
                                ptr[2] = col.R;
                                ptr   += pixelSpace;
                            }
                            ptr += bitmapData.Stride - bitmapData.Width * pixelSpace;
                        }
                    }
                }

                return(new RasterPaintContext(bitmap));
            }
            catch (Exception ex)
            {
                if (bitmap != null && bitmapData != null)
                {
                    bitmap.UnlockBitmapPixelData(bitmapData);
                    bitmapData = null;
                    bitmap.Dispose();
                    bitmap = null;
                }

                throw ex;
            }
            finally
            {
                if (bitmap != null && bitmapData != null)
                {
                    bitmap.UnlockBitmapPixelData(bitmapData);
                }
            }
        }
Ejemplo n.º 21
0
        private IRasterPaintContext PaintWavelet(int x, int y, int wWidth, int wHeight, int iWidth, int iHeight, ICancelTracker cancelTracker)
        {
            if (CancelTracker.Canceled(cancelTracker) || _gDS == null)
            {
                return(null);
            }

            int pixelSpace = 4;
            var bitmap     = Current.Engine.CreateBitmap(iWidth, iHeight, GraphicsEngine.PixelFormat.Rgba32);
            var bitmapData = bitmap.LockBitmapPixelData(BitmapLockMode.ReadWrite, GraphicsEngine.PixelFormat.Rgba32);

            try
            {
                int    stride = bitmapData.Stride;
                IntPtr buf    = bitmapData.Scan0;

                for (int i = 1; i <= (_gDS.RasterCount > 3 ? 3 : _gDS.RasterCount); ++i)
                {
                    using (OSGeo_v1.GDAL.Band band = _gDS.GetRasterBand(i))
                    {
                        int ch = 0;
                        switch ((ColorInterp)band.GetRasterColorInterpretation())
                        {
                        case ColorInterp.BlueBand:
                            ch = 0;
                            break;

                        case ColorInterp.GreenBand:
                            ch = 1;
                            break;

                        case ColorInterp.RedBand:
                            ch = 2;
                            break;
                        }
                        band.ReadRaster(x, y, wWidth, wHeight,
                                        new IntPtr(buf.ToInt64() + ch),
                                        iWidth, iHeight, OSGeo_v1.GDAL.DataType.GDT_Byte, pixelSpace, stride);
                    }
                }

                return(new RasterPaintContext(bitmap));
            }
            catch (Exception ex)
            {
                if (bitmap != null && bitmapData != null)
                {
                    bitmap.UnlockBitmapPixelData(bitmapData);
                    bitmapData = null;
                    bitmap.Dispose();
                    bitmap = null;
                }

                throw ex;
            }
            finally
            {
                if (bitmap != null && bitmapData != null)
                {
                    bitmap.UnlockBitmapPixelData(bitmapData);
                }
            }
        }
Ejemplo n.º 22
0
        private IRasterPaintContext PaintHillShade(int x, int y, int wWidth, int wHeight, int iWidth, int iHeight, double mag, ICancelTracker cancelTracker)
        {
            if (CancelTracker.Canceled(cancelTracker) || _gDS == null)
            {
                return(null);
            }

            int pixelSpace = 4;

            using (var bitmap = GraphicsEngine.Current.Engine.CreateBitmap(iWidth, iHeight + 100, GraphicsEngine.PixelFormat.Rgba32))
            {
                var bitmapData          = bitmap.LockBitmapPixelData(GraphicsEngine.BitmapLockMode.ReadWrite, GraphicsEngine.PixelFormat.Rgba32);
                OSGeo_v1.GDAL.Band band = null;

                try
                {
                    int    stride = bitmapData.Stride;
                    IntPtr buf    = bitmapData.Scan0;

                    List <ArgbColor> colors = new List <ArgbColor>();
                    using (band = _gDS.GetRasterBand(1))
                    {
                        band.ReadRaster(x, y, wWidth, wHeight,
                                        buf,
                                        iWidth, iHeight, OSGeo_v1.GDAL.DataType.GDT_CFloat32, pixelSpace, stride);

                        band.Dispose();
                    }

                    double cx = _tfw.cellX / mag;
                    double cy = _tfw.cellY / mag;

                    Vector3d sun = new Vector3d(_hillShade);
                    sun.Normalize();
                    int rowStride = stride / pixelSpace;

                    ArgbColor col = ArgbColor.White;
                    unsafe
                    {
                        byte * ptr = (byte *)(bitmapData.Scan0);
                        float *v   = (float *)(bitmapData.Scan0);

                        float floatNodata = (float)_nodata;

                        for (int i = 0; i < iHeight; i++)
                        {
                            if (CancelTracker.Canceled(cancelTracker))
                            {
                                return(null);
                            }

                            for (int j = 0; j < iWidth; j++)
                            {
                                if ((_hasNoDataVal == 1 && *v == floatNodata) ||
                                    (_useIgnoreValue && *v == _ignoreValue))
                                {
                                    ptr[0] = ptr[1] = ptr[2] = ptr[3] = 0;
                                }
                                else
                                {
                                    double c = *v;

                                    col = GridColorClass.FindColor(c, _colorClasses);
                                    if (!_useHillShade)
                                    {
                                        ptr[0] = col.B; ptr[1] = col.G; ptr[2] = col.R;
                                        ptr[3] = col.A; // alpha
                                    }
                                    else
                                    {
                                        double c1 = (j < iWidth - 1) ? (*(v + 1)) : c;
                                        double c2 = (i < iHeight - 1) ? (*(v + rowStride)) : c;
                                        c1 = ((_hasNoDataVal != 0 && c1 == floatNodata) ||
                                              (_useIgnoreValue && c1 == _ignoreValue)) ? c : c1;
                                        c2 = ((_hasNoDataVal != 0 && c2 == floatNodata) ||
                                              (_useIgnoreValue && c2 == _ignoreValue)) ? c : c2;

                                        Vector3d v1 = new Vector3d(cx, 0.0, c1 - c); v1.Normalize();
                                        Vector3d v2 = new Vector3d(0.0, -cy, c2 - c); v2.Normalize();
                                        Vector3d vs = v2 % v1; vs.Normalize();
                                        double   h  = Math.Min(Math.Max(0.0, sun * vs), 1.0);
                                        //double h = Math.Abs(sun * vs);

                                        double a = col.A;
                                        double r = col.R * h;
                                        double g = col.G * h;
                                        double b = col.B * h;
                                        ptr[0] = (byte)b; ptr[1] = (byte)g; ptr[2] = (byte)r;
                                        ptr[3] = (byte)a; // alpha
                                    }
                                }
                                ptr += pixelSpace;
                                v++;
                            }
                            ptr += bitmapData.Stride - (bitmapData.Width) * pixelSpace;
                            v    = (float *)ptr;
                        }
                    }
                    if (bitmap != null)
                    {
                        bitmap.UnlockBitmapPixelData(bitmapData);
                        bitmapData = null;
                    }

                    var contextBitmap = GraphicsEngine.Current.Engine.CreateBitmap(iWidth, iHeight, GraphicsEngine.PixelFormat.Rgba32);
                    using (var gr = contextBitmap.CreateCanvas())
                    {
                        gr.DrawBitmap(bitmap, new GraphicsEngine.CanvasPoint(0, 0));
                    }

                    return(new RasterPaintContext(contextBitmap));
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (bitmap != null && bitmapData != null)
                    {
                        bitmap.UnlockBitmapPixelData(bitmapData);
                    }
                }
            }
        }
Ejemplo n.º 23
0
        public void FinishDrawing(IDisplay disp, ICancelTracker cancelTracker)
        {
            if (cancelTracker == null)
            {
                cancelTracker = new CancelTracker();
            }

            if (_cartoMethod == LegendGroupCartographicMethod.LegendAndSymbolOrdering && cancelTracker.Continue)
            {
                int symbolIndex = 0;

                List <string> keys = new List <string>();
                foreach (string key in _symbolTable.Keys)
                {
                    keys.Insert(0, key);
                }

                if (_features != null)
                {
                    while (true)
                    {
                        bool loop = false;
                        foreach (string key in keys)
                        {
                            if (!_features.ContainsKey(key) || _features[key] == null)
                            {
                                continue;
                            }
                            if (!cancelTracker.Continue)
                            {
                                break;
                            }

                            ISymbol symbol = _symbolTable.ContainsKey(key) ? (ISymbol)_symbolTable[key] : null;
                            if (symbol == null)
                            {
                                continue;
                            }

                            if (symbol is ISymbolCollection)
                            {
                                ISymbolCollection symbolCol = (ISymbolCollection)symbol;
                                if (symbolIndex >= symbolCol.Symbols.Count)
                                {
                                    continue;
                                }

                                if (symbolCol.Symbols.Count > symbolIndex + 1)
                                {
                                    loop = true;
                                }

                                ISymbolCollectionItem symbolItem = symbolCol.Symbols[symbolIndex];
                                if (symbolItem.Visible == false || symbolItem.Symbol == null)
                                {
                                    continue;
                                }
                                symbol = symbolItem.Symbol;
                            }
                            else if (symbolIndex > 0)
                            {
                                continue;
                            }

                            List <IFeature> features    = _features[key];
                            bool            isRotatable = symbol is ISymbolRotation;

                            if (!cancelTracker.Continue)
                            {
                                break;
                            }
                            int counter = 0;
                            foreach (IFeature feature in features)
                            {
                                if (isRotatable && !String.IsNullOrEmpty(_symbolRotation.RotationFieldName))
                                {
                                    object rot = feature[_symbolRotation.RotationFieldName];
                                    if (rot != null && rot != DBNull.Value)
                                    {
                                        ((ISymbolRotation)symbol).Rotation = (float)_symbolRotation.Convert2DEGAritmetic(Convert.ToDouble(rot));
                                    }
                                    else
                                    {
                                        ((ISymbolRotation)symbol).Rotation = 0;
                                    }
                                }
                                symbol.Draw(disp, feature.Shape);

                                counter++;
                                if (counter % 100 == 0 && !cancelTracker.Continue)
                                {
                                    break;
                                }
                            }
                        }

                        if (!loop)
                        {
                            break;
                        }
                        symbolIndex++;
                    }
                }
            }
            else if (_cartoMethod == LegendGroupCartographicMethod.LegendOrdering && cancelTracker.Continue)
            {
                List <string> keys = new List <string>();
                foreach (string key in _symbolTable.Keys)
                {
                    keys.Insert(0, key);
                }

                foreach (string key in keys)
                {
                    if (!_features.ContainsKey(key) || _features[key] == null)
                    {
                        continue;
                    }
                    if (!cancelTracker.Continue)
                    {
                        break;
                    }

                    ISymbol symbol = _symbolTable.ContainsKey(key) ? (ISymbol)_symbolTable[key] : null;
                    if (symbol == null)
                    {
                        continue;
                    }

                    List <IFeature> features    = _features[key];
                    bool            isRotatable = symbol is ISymbolRotation;

                    int counter = 0;
                    foreach (IFeature feature in features)
                    {
                        if (isRotatable && !String.IsNullOrEmpty(_symbolRotation.RotationFieldName))
                        {
                            object rot = feature[_symbolRotation.RotationFieldName];
                            if (rot != null && rot != DBNull.Value)
                            {
                                ((ISymbolRotation)symbol).Rotation = (float)_symbolRotation.Convert2DEGAritmetic(Convert.ToDouble(rot));
                            }
                            else
                            {
                                ((ISymbolRotation)symbol).Rotation = 0;
                            }
                        }
                        symbol.Draw(disp, feature.Shape);

                        counter++;
                        if (counter % 100 == 0 && !cancelTracker.Continue)
                        {
                            break;
                        }
                    }
                }
            }

            if (_features != null)
            {
                _features.Clear();
                _features = null;
            }
        }
Ejemplo n.º 24
0
        protected override void OnMouseDown(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg)
        {
            int            X      = arg.X;
            int            Y      = arg.Y;
            IMxApplication pMxApp = null;
            IMxDocument    pMxDoc = null;

            pMxApp = (IMxApplication)ArcMap.Application;
            pMxDoc = (IMxDocument)ArcMap.Application.Document;

            // calculate tolerance rectangle to identify features inside it
            int Tolerance = 0;

            Tolerance = pMxDoc.SearchTolerancePixels;

            IDisplayTransformation pDispTrans = null;

            pDispTrans = pMxApp.Display.DisplayTransformation;
            tagRECT pToleranceRect = new tagRECT();

            pToleranceRect.left   = X - Tolerance;
            pToleranceRect.right  = X + Tolerance;
            pToleranceRect.top    = Y - Tolerance;
            pToleranceRect.bottom = Y + Tolerance;

            IEnvelope pSearchEnvelope = null;

            pSearchEnvelope = new EnvelopeClass();
            pDispTrans.TransformRect(pSearchEnvelope, ref pToleranceRect, (int)(esriDisplayTransformationEnum.esriTransformPosition | esriDisplayTransformationEnum.esriTransformToMap));

            // identify feature points of measurement
            IBasicDocument pBasicDoc = null;

            pBasicDoc = (IBasicDocument)ArcMap.Application.Document;
            pSearchEnvelope.SpatialReference = pMxDoc.ActiveView.FocusMap.SpatialReference;

            IIdentify pIdentify = null;

            pIdentify = (IIdentify)pMxDoc.FocusMap.get_Layer(0);
            if (pIdentify == null)
            {
                MessageBox.Show("No layer");
                return;
            }

            IArray pIDArray = null;

            pIDArray = pIdentify.Identify(pSearchEnvelope);

            // get object from feature point
            IIdentifyObj pIDObj = null;

            if (pIDArray != null)
            {
                pIDObj = (IIdentifyObj)pIDArray.get_Element(0);
            }

            if (pIDObj == null)
            {
                MessageBox.Show("No feature was identified");
                return;
            }

            // get the name of the layer containing feature points
            ILayer pLayer = null;

            pLayer = pMxDoc.FocusMap.get_Layer(0);

            string layerName = null;

            layerName = pLayer.Name;

            // get primary display field for measurement values and set names of a date/time field and gage ID field
            IFeatureLayer pFeatLayer = null;

            pFeatLayer = (IFeatureLayer)pLayer;
            string dataFldName   = null;
            string timefldName   = null;
            string gageIDFldName = null;

            dataFldName   = "TSValue";
            timefldName   = "TSDateTime"; // substitute data/time field name for different dataset
            gageIDFldName = "Name";       // substitute gage ID field name for different dataset

            // get display table from layer
            ITable        pTable        = null;
            IDisplayTable pDisplayTable = null;

            pDisplayTable = (IDisplayTable)pLayer;
            if (pDisplayTable != null)
            {
                pTable = pDisplayTable.DisplayTable;
                if (pTable == null)
                {
                    goto THEEND;
                }
            }

            // get fields from display table
            IFields pFields = null;

            pFields = pTable.Fields;
            long fldCount = 0;

            fldCount = pFields.FieldCount;

            // create WHERE clause from identified objects of measurement points
            int gageIDFldIdx = 0;

            gageIDFldIdx = pFields.FindField(gageIDFldName);

            IRowIdentifyObject pRowIDObj = null;

            pRowIDObj = (IRowIdentifyObject)pIDObj;

            string gageID = null;

            gageID = (string)pRowIDObj.Row.get_Value(gageIDFldIdx);

            IFeatureLayerDefinition pFeatureLayerDef = null;

            pFeatureLayerDef = (IFeatureLayerDefinition)pLayer;
            string definitionExpression = null;

            definitionExpression = pFeatureLayerDef.DefinitionExpression;

            string whereClause = null;

            if (definitionExpression == "")
            {
                whereClause = "[" + gageIDFldName + "] = '" + gageID + "'";
            }
            else
            {
                whereClause = "[" + gageIDFldName + "] = '" + gageID + "' AND " + definitionExpression;
            }

            //find color for the identified object from feature layer's renderer
            IGeoFeatureLayer pGeoFeatureLayer = null;

            pGeoFeatureLayer = (IGeoFeatureLayer)pLayer;

            ILookupSymbol pLookupSymbol = null;

            pLookupSymbol = (ILookupSymbol)pGeoFeatureLayer.Renderer;

            IFeature pFeature = null;

            pFeature = (IFeature)pRowIDObj.Row;

            IMarkerSymbol pSymbol = null;

            pSymbol = (IMarkerSymbol)pLookupSymbol.LookupSymbol(false, pFeature);

            // Find an opened GraphWindow
            IDataGraphBase    pDataGraphBase = null;
            IDataGraphT       pDataGraphT    = null;
            IDataGraphWindow2 pDGWin         = null;

            IDataGraphCollection pDataGraphs = null;

            pDataGraphs = (IDataGraphCollection)pMxDoc;
            int grfCount = 0;

            grfCount = pDataGraphs.DataGraphCount;
            for (int i = 0; i < grfCount; i++)
            {
                pDataGraphBase = pDataGraphs.get_DataGraph(i);
                pDGWin         = FindGraphWindow(ref pDataGraphBase);
                if (pDGWin != null)
                {
                    break;
                }
            }

            // if there is not an opened graph window - create a new graph for
            if (pDGWin == null)
            {
                // create graph
                pDataGraphT    = new DataGraphTClass();
                pDataGraphBase = (IDataGraphBase)pDataGraphT;

                // load template from <ARCGISHOME>\GraphTemplates\
                string strPath = null;
                strPath = Environment.GetEnvironmentVariable("ARCGISHOME");
                try
                {
                    pDataGraphT.LoadTemplate(strPath + @"GraphTemplates\timeseries.tee");
                }
                catch
                { }

                // graph, axis and legend titles. Substitute them for different input layer
                pDataGraphT.GeneralProperties.Title           = "Daily Streamflow for Guadalupe Basin in 1999";
                pDataGraphT.LegendProperties.Title            = "Monitoring Point";
                pDataGraphT.get_AxisProperties(0).Title       = "Streamflow (cfs)";
                pDataGraphT.get_AxisProperties(0).Logarithmic = true;
                pDataGraphT.get_AxisProperties(2).Title       = "Date";
                pDataGraphBase.Name = layerName;
            }
            else // get graph from the opened window
            {
                pDataGraphT = (IDataGraphT)pDataGraphBase;
            }

            // create vertical line series for all measurements for the identified gage
            ISeriesProperties pSP = null;

            pSP             = pDataGraphT.AddSeries("line:vertical");
            pSP.ColorType   = esriGraphColorType.esriGraphColorCustomAll;
            pSP.CustomColor = pSymbol.Color.RGB;
            pSP.WhereClause = whereClause;
            pSP.InLegend    = true;
            pSP.Name        = gageID;

            pSP.SourceData = pLayer;
            pSP.SetField(0, timefldName);
            pSP.SetField(1, dataFldName);
            IDataSortSeriesProperties pSortFlds = null;

            pSortFlds = (IDataSortSeriesProperties)pSP;
            int idx = 0;

            pSortFlds.AddSortingField(timefldName, true, ref idx);


            pDataGraphBase.UseSelectedSet = true;

            ITrackCancel pCancelTracker = null;

            pCancelTracker = new CancelTracker();
            pDataGraphT.Update(pCancelTracker);

            // create data graph window if there is not any opened one
            if (pDGWin == null)
            {
                pDGWin = new DataGraphWindowClass();
                pDGWin.DataGraphBase = pDataGraphBase;
                pDGWin.Application   = ArcMap.Application;
                pDGWin.Show(true);

                pDataGraphs.AddDataGraph(pDataGraphBase);
            }

THEEND:
            return;

            //base.OnMouseDown(arg);
        }
Ejemplo n.º 25
0
        private void PaintImage(int x, int y, int wWidth, int wHeight, int iWidth, int iHeight, ICancelTracker cancelTracker)
        {
            if (CancelTracker.Canceled(cancelTracker) || _gDS == null)
            {
                return;
            }
            int pixelSpace = 3;

            _bitmap = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
            BitmapData bitmapData = _bitmap.LockBits(new Rectangle(0, 0, iWidth, iHeight), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            try
            {
                int    stride = bitmapData.Stride;
                IntPtr buf    = bitmapData.Scan0;

                List <Color> colors = new List <Color>();
                for (int i = 1; i <= (_gDS.RasterCount > 3 ? 3 : _gDS.RasterCount); ++i)
                {
                    using (OSGeo.GDAL.Band band = _gDS.GetRasterBand(i))
                    {
                        int ch = 0;
                        switch ((ColorInterp)band.GetRasterColorInterpretation())
                        {
                        case ColorInterp.BlueBand:
                            ch = 0;
                            break;

                        case ColorInterp.GreenBand:
                            ch = 1;
                            break;

                        case ColorInterp.RedBand:
                            ch = 2;
                            break;

                        case ColorInterp.GrayIndex:
                            for (int iColor = 0; iColor < 256; iColor++)
                            {
                                colors.Add(Color.FromArgb(255, iColor, iColor, iColor));
                            }
                            break;

                        case ColorInterp.PaletteIndex:
                            OSGeo.GDAL.ColorTable colTable = band.GetRasterColorTable();
                            if (colTable == null)
                            {
                                break;
                            }
                            int colCount = colTable.GetCount();
                            for (int iColor = 0; iColor < colCount; iColor++)
                            {
                                OSGeo.GDAL.ColorEntry colEntry = colTable.GetColorEntry(iColor);
                                colors.Add(Color.FromArgb(
                                               colEntry.c4, colEntry.c1, colEntry.c2, colEntry.c3));
                            }

                            break;
                        }
                        band.ReadRaster(x, y, wWidth, wHeight,
                                        new IntPtr(buf.ToInt64() + ch),
                                        iWidth, iHeight, OSGeo.GDAL.DataType.GDT_Byte, pixelSpace, stride);

                        band.Dispose();
                    }
                }
                if (colors.Count > 0)
                {
                    unsafe
                    {
                        byte *ptr = (byte *)(bitmapData.Scan0);
                        for (int i = 0; i < bitmapData.Height; i++)
                        {
                            if (CancelTracker.Canceled(cancelTracker))
                            {
                                return;
                            }
                            for (int j = 0; j < bitmapData.Width; j++)
                            {
                                // write the logic implementation here
                                byte  c   = ptr[0];
                                Color col = colors[(int)c];
                                ptr[0] = col.B;
                                ptr[1] = col.G;
                                ptr[2] = col.R;
                                ptr   += pixelSpace;
                            }
                            ptr += bitmapData.Stride - bitmapData.Width * pixelSpace;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
            finally
            {
                if (_bitmap != null)
                {
                    _bitmap.UnlockBits(bitmapData);
                }
            }
        }
Ejemplo n.º 26
0
        public static void ConvertLabels2StandardAnno(IMap imap_0, ILayer ilayer_0, string string_0, double double_0,
                                                      IWorkspace iworkspace_0, bool bool_0, bool bool_1, esriLabelWhichFeatures esriLabelWhichFeatures_0)
        {
            int i;
            IAnnotateLayerProperties     bool0;
            IElementCollection           elementCollection;
            IElementCollection           elementCollection1;
            ILabelEngineLayerProperties2 d;
            ISymbolIdentifier2           symbolIdentifier2;
            IAnnotationLayer             annotationLayer;

            if (iworkspace_0.Type != esriWorkspaceType.esriFileSystemWorkspace && ilayer_0 is IGeoFeatureLayer)
            {
                IGeoFeatureLayer        ilayer0      = ilayer_0 as IGeoFeatureLayer;
                IFeatureClass           featureClass = ilayer0.FeatureClass;
                IAnnotationLayerFactory fDOGraphicsLayerFactoryClass =
                    new FDOGraphicsLayerFactory() as IAnnotationLayerFactory;
                ISymbolCollection2 symbolCollectionClass = new SymbolCollection() as ISymbolCollection2;
                IAnnotateLayerPropertiesCollection annotateLayerPropertiesCollectionClass =
                    new AnnotateLayerPropertiesCollection();
                IAnnotateLayerPropertiesCollection annotationProperties = ilayer0.AnnotationProperties;
                for (i = 0; i < annotationProperties.Count; i++)
                {
                    annotationProperties.QueryItem(i, out bool0, out elementCollection, out elementCollection1);
                    if (bool0 != null)
                    {
                        annotateLayerPropertiesCollectionClass.Add(bool0);
                        d = bool0 as ILabelEngineLayerProperties2;
                        IClone symbol = d.Symbol as IClone;
                        symbolCollectionClass.AddSymbol(symbol.Clone() as ISymbol,
                                                        string.Concat(bool0.Class, " ", i.ToString()), out symbolIdentifier2);
                        d.SymbolID = symbolIdentifier2.ID;
                    }
                }
                bool0 = null;
                d     = null;
                IGraphicsLayerScale graphicsLayerScaleClass = new GraphicsLayerScale()
                {
                    ReferenceScale = double_0,
                    Units          = imap_0.MapUnits
                };
                IFeatureClassDescription annotationFeatureClassDescriptionClass =
                    new AnnotationFeatureClassDescription() as IFeatureClassDescription;
                IFields requiredFields =
                    (annotationFeatureClassDescriptionClass as IObjectClassDescription).RequiredFields;
                IField field =
                    requiredFields.Field[requiredFields.FindField(annotationFeatureClassDescriptionClass.ShapeFieldName)
                    ];
                (field.GeometryDef as IGeometryDefEdit).SpatialReference_2 =
                    (featureClass as IGeoDataset).SpatialReference;
                IOverposterProperties overposterProperties = (imap_0 as IMapOverposter).OverposterProperties;
                if (!bool_1)
                {
                    LayerOp.CreateAnnoFeatureClass(iworkspace_0 as IFeatureWorkspaceAnno, featureClass.FeatureDataset,
                                                   null, graphicsLayerScaleClass.ReferenceScale, graphicsLayerScaleClass.Units,
                                                   annotateLayerPropertiesCollectionClass, symbolCollectionClass as ISymbolCollection, string_0);
                    annotationLayer = fDOGraphicsLayerFactoryClass.OpenAnnotationLayer(
                        iworkspace_0 as IFeatureWorkspace, featureClass.FeatureDataset, string_0);
                }
                else
                {
                    LayerOp.CreateAnnoFeatureClass(iworkspace_0 as IFeatureWorkspaceAnno, featureClass.FeatureDataset,
                                                   featureClass, graphicsLayerScaleClass.ReferenceScale, graphicsLayerScaleClass.Units,
                                                   annotateLayerPropertiesCollectionClass, symbolCollectionClass as ISymbolCollection, string_0);
                    annotationLayer = fDOGraphicsLayerFactoryClass.OpenAnnotationLayer(
                        iworkspace_0 as IFeatureWorkspace, featureClass.FeatureDataset, string_0);
                }
                IActiveView imap0 = imap_0 as IActiveView;
                (annotationLayer as IGraphicsLayer).Activate(imap0.ScreenDisplay);
                for (i = 0; i < annotateLayerPropertiesCollectionClass.Count; i++)
                {
                    annotateLayerPropertiesCollectionClass.QueryItem(i, out bool0, out elementCollection,
                                                                     out elementCollection1);
                    if (bool0 != null)
                    {
                        bool0.FeatureLayer      = ilayer0;
                        bool0.GraphicsContainer = annotationLayer as IGraphicsContainer;
                        bool0.AddUnplacedToGraphicsContainer = bool_0;
                        bool0.CreateUnplacedElements         = true;
                        bool0.DisplayAnnotation  = true;
                        bool0.FeatureLinked      = bool_1;
                        bool0.LabelWhichFeatures = esriLabelWhichFeatures_0;
                        bool0.UseOutput          = true;
                        d                   = bool0 as ILabelEngineLayerProperties2;
                        d.SymbolID          = i;
                        d.AnnotationClassID = i;
                        (d.OverposterLayerProperties as IOverposterLayerProperties2).TagUnplaced = true;
                    }
                }
                annotateLayerPropertiesCollectionClass.Sort();
                IAnnotateMapProperties annotateMapPropertiesClass = new AnnotateMapProperties()
                {
                    AnnotateLayerPropertiesCollection = annotateLayerPropertiesCollectionClass
                };
                ITrackCancel cancelTrackerClass = new CancelTracker();
                (imap_0.AnnotationEngine as IAnnotateMap2).Label(overposterProperties, annotateMapPropertiesClass,
                                                                 imap_0, cancelTrackerClass);
                for (i = 0; i < annotateLayerPropertiesCollectionClass.Count; i++)
                {
                    annotateLayerPropertiesCollectionClass.QueryItem(i, out bool0, out elementCollection,
                                                                     out elementCollection1);
                    if (bool0 != null)
                    {
                        bool0.FeatureLayer = null;
                    }
                }
                imap_0.AddLayer(annotationLayer as ILayer);
                ilayer0.DisplayAnnotation = false;
                imap0.Refresh();
            }
        }
Ejemplo n.º 27
0
        private void PaintHillShade(int x, int y, int wWidth, int wHeight, int iWidth, int iHeight, double mag, ICancelTracker cancelTracker)
        {
            if (CancelTracker.Canceled(cancelTracker) || _gDS == null)
            {
                return;
            }

            int        pixelSpace = 4;
            Bitmap     bitmap     = new Bitmap(iWidth, iHeight + 100, PixelFormat.Format32bppArgb);
            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, iWidth, iHeight + 100), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            OSGeo.GDAL.Band band = null;

            try
            {
                int    stride = bitmapData.Stride;
                IntPtr buf    = bitmapData.Scan0;

                List <Color> colors = new List <Color>();
                using (band = _gDS.GetRasterBand(1))
                {
                    band.ReadRaster(x, y, wWidth, wHeight,
                                    buf,
                                    iWidth, iHeight, OSGeo.GDAL.DataType.GDT_CFloat32, pixelSpace, stride);

                    band.Dispose();
                }

                double cx = _tfw.cellX / mag;
                double cy = _tfw.cellY / mag;

                Vector3d sun = new Vector3d(_hillShade);
                sun.Normalize();
                int rowStride = stride / pixelSpace;

                Color col = Color.White;
                unsafe
                {
                    byte * ptr = (byte *)(bitmapData.Scan0);
                    float *v   = (float *)(bitmapData.Scan0);

                    for (int i = 0; i < iHeight; i++)
                    {
                        if (CancelTracker.Canceled(cancelTracker))
                        {
                            return;
                        }
                        for (int j = 0; j < iWidth; j++)
                        {
                            if ((_hasNoDataVal == 1 && *v == _nodata) ||
                                (_useIgnoreValue && *v == _ignoreValue))
                            {
                                ptr[0] = ptr[1] = ptr[2] = ptr[3] = 0;
                            }
                            else
                            {
                                double c = *v;

                                col = GridColorClass.FindColor(c, _colorClasses);
                                if (!_useHillShade)
                                {
                                    ptr[0] = (byte)col.B; ptr[1] = (byte)col.G; ptr[2] = (byte)col.R;
                                    ptr[3] = (byte)col.A; // alpha
                                }
                                else
                                {
                                    double c1 = (j < iWidth - 1) ? (*(v + 1)) : c;
                                    double c2 = (i < iHeight - 1) ? (*(v + rowStride)) : c;
                                    c1 = ((_hasNoDataVal != 0 && c1 == _nodata) ||
                                          (_useIgnoreValue && c1 == _ignoreValue)) ? c : c1;
                                    c2 = ((_hasNoDataVal != 0 && c2 == _nodata) ||
                                          (_useIgnoreValue && c2 == _ignoreValue)) ? c : c2;

                                    Vector3d v1 = new Vector3d(cx, 0.0, c1 - c); v1.Normalize();
                                    Vector3d v2 = new Vector3d(0.0, -cy, c2 - c); v2.Normalize();
                                    Vector3d vs = v2 % v1; vs.Normalize();
                                    double   h  = Math.Min(Math.Max(0.0, sun * vs), 1.0);
                                    //double h = Math.Abs(sun * vs);

                                    double a = col.A;
                                    double r = col.R * h;
                                    double g = col.G * h;
                                    double b = col.B * h;
                                    ptr[0] = (byte)b; ptr[1] = (byte)g; ptr[2] = (byte)r;
                                    ptr[3] = (byte)a; // alpha
                                }
                            }
                            ptr += pixelSpace;
                            v++;
                        }
                        ptr += bitmapData.Stride - (bitmapData.Width) * pixelSpace;
                        v    = (float *)ptr;
                    }
                }
                if (bitmap != null)
                {
                    bitmap.UnlockBits(bitmapData);
                }

                _bitmap = new Bitmap(iWidth, iHeight, PixelFormat.Format32bppArgb);
                using (Graphics gr = Graphics.FromImage(_bitmap))
                {
                    gr.DrawImage(bitmap, 0, 0);
                }
            }
            catch { }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
            }
        }
Ejemplo n.º 28
0
        private void miOutput_Click(object sender, EventArgs e)
        {
            SaveFileDialog m_save = new SaveFileDialog();

            m_save.Filter = "jpeg图片(*.jpg)|*.jpg|tiff图片(*.tif)|*.tif|bmp图片(*.bmp)|*.bmp|emf图片(*.emf)|*.emf|png图片(*.png)|*.png|gif图片(*.gif)|*.gif";
            m_save.ShowDialog();
            string Outpath = m_save.FileName;

            if (Outpath != "")
            {
                //分辨率
                //double resulotion = axMapControl1.ActiveView.ScreenDisplay.DisplayTransformation.Resolution;
                double  resulotion = axPageLayoutControl1.ActiveView.ScreenDisplay.DisplayTransformation.Resolution;
                IExport m_export   = null;
                if (Outpath.EndsWith(".jpg"))
                {
                    m_export = new ExportJPEG() as IExport;
                }
                else if (Outpath.EndsWith(".tig"))
                {
                    m_export = new ExportTIFF() as IExport;
                }
                else if (Outpath.EndsWith(".bmp"))
                {
                    m_export = new ExportBMP() as IExport;
                }
                else if (Outpath.EndsWith(".emf"))
                {
                    m_export = new ExportEMF() as IExport;
                }
                else if (Outpath.EndsWith(".png"))
                {
                    m_export = new ExportPNG() as IExport;
                }
                else if (Outpath.EndsWith(".gif"))
                {
                    m_export = new ExportGIF() as IExport;
                }
                //设置输出的路径
                m_export.ExportFileName = Outpath;
                //设置输出的分辨率
                m_export.Resolution = resulotion;
                tagRECT piexPound;
                //piexPound = axMapControl1.ActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame();
                piexPound = axPageLayoutControl1.ActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame();
                IEnvelope m_envelope = new Envelope() as IEnvelope;
                m_envelope.PutCoords(piexPound.left, piexPound.bottom, piexPound.right, piexPound.top);
                //设置输出的IEnvelope
                m_export.PixelBounds = m_envelope;

                ITrackCancel m_trackCancel = new CancelTracker();
                //输出的方法
                // axMapControl1.ActiveView.Output(m_export.StartExporting(), (short)resulotion, ref piexPound, axMapControl1.ActiveView.Extent, m_trackCancel);
                axPageLayoutControl1.ActiveView.Output(m_export.StartExporting(), (short)resulotion, ref piexPound, axPageLayoutControl1.ActiveView.Extent, m_trackCancel);
                m_export.FinishExporting();
            }
            else
            {
                MessageBox.Show("输出图像名称不能为空!");
            }
        }