/// <summary>
        /// This create new method implies that this provider has the priority for creating a new file.
        /// An instance of the dataset should be created and then returned.  By this time, the fileName
        /// will already be checked to see if it exists, and deleted if the user wants to overwrite it.
        /// </summary>
        /// <param name="fileName">The string fileName for the new instance</param>
        /// <param name="featureType">Point, Line, Polygon etc.  Sometimes this will be specified, sometimes it will be "Unspecified"</param>
        /// <param name="inRam">Boolean, true if the dataset should attempt to store data entirely in ram</param>
        /// <param name="progressHandler">An IProgressHandler for status messages.</param>
        /// <returns>An IRaster</returns>
        public virtual IFeatureSet CreateNew(string fileName, FeatureType featureType, bool inRam, IProgressHandler progressHandler)
        {
            if (featureType == FeatureType.Point)
            {
                PointShapefile ps = new PointShapefile();
                ps.Filename = fileName;
                return ps;
            }
            else if (featureType == FeatureType.Line)
            {
                LineShapefile ls = new LineShapefile();
                ls.Filename = fileName;
                return ls;
            }
            else if (featureType == FeatureType.Polygon)
            {
                PolygonShapefile ps = new PolygonShapefile();
                ps.Filename = fileName;
                return ps;
            }
            else if (featureType == FeatureType.MultiPoint)
            {
                MultiPointShapefile mps = new MultiPointShapefile();
                mps.Filename = fileName;
                return mps;
            }

            return null;
        }
 /// <summary>
 /// Opens an existing raster and returns a layer containing it
 /// </summary>
 /// <param name="fileName">The string fileName to open</param>
 /// <param name="inRam">Opens in ram</param>
 /// <param name="container">A container to automatically add this layer to</param>
 /// <param name="progressHandler">Returns progress</param>
 /// <returns>An ILayer</returns>
 public ILayer OpenLayer(string fileName, bool inRam, ICollection<ILayer> container, IProgressHandler progressHandler)
 {
     IRaster raster = Raster.OpenFile(fileName, inRam, progressHandler);
     RasterLayer rl = new RasterLayer(raster, progressHandler);
     container.Add(rl);
     return rl;
 }
Example #3
0
        /// <summary>
        /// Opens a shapefile
        /// </summary>
        /// <param name="fileName">The string fileName of the line shapefile to load</param>
        /// <param name="progressHandler">Any valid implementation of the DotSpatial.Data.IProgressHandler</param>
        public void Open(string fileName, IProgressHandler progressHandler)
        {
            if (!File.Exists(fileName)) return;

            Filename = fileName;
            IndexMode = true;
            Header = new ShapefileHeader(fileName);

            switch (Header.ShapeType)
            {
                case ShapeType.PolyLineM:
                    CoordinateType = CoordinateType.M;
                    break;
                case ShapeType.PolyLineZ:
                    CoordinateType = CoordinateType.Z;
                    break;
                default:
                    CoordinateType = CoordinateType.Regular;
                    break;
            }

            Extent = Header.ToExtent();
            Name = Path.GetFileNameWithoutExtension(fileName);
            Attributes.Open(fileName);

            FillLines(fileName, progressHandler, this, FeatureType.Line);
            ReadProjection();
        }
Example #4
0
        /// <summary>
        /// Opens a shapefile
        /// </summary>
        /// <param name="fileName">The string fileName of the line shapefile to load</param>
        /// <param name="progressHandler">Any valid implementation of the DotSpatial.Data.IProgressHandler</param>
        public void Open(string fileName, IProgressHandler progressHandler)
        {
            if (!File.Exists(fileName))
            {
                Attributes = new AttributeTable();
                Header = new ShapefileHeader { FileLength = 100, ShapeType = ShapeType.PolyLine };
                FeatureType = FeatureType.Line;
                return;
            }

            Filename = fileName;
            FeatureType = FeatureType.Line;
            Header = new ShapefileHeader(fileName);
            CoordinateType = CoordinateType.Regular;
            IndexMode = true;
            if (Header.ShapeType == ShapeType.PolyLineM)
            {
                CoordinateType = CoordinateType.M;
            }
            if (Header.ShapeType == ShapeType.PolyLineZ)
            {
                CoordinateType = CoordinateType.Z;
            }
            MyExtent = Header.ToExtent();
            Name = Path.GetFileNameWithoutExtension(fileName);
            Attributes.Open(fileName);
            FillLines(fileName, progressHandler);
            ReadProjection();
        }
        /// <summary>
        /// Creates a new image given the specified file format
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="inRam">if set to <c>true</c> should load entire file in ram.</param>
        /// <param name="progHandler">The prog handler.</param>
        /// <param name="bandType">Type of the band.</param>
        /// <returns></returns>
        public IImageData Create(string fileName, int width, int height, bool inRam, IProgressHandler progHandler, ImageBandType bandType)
        {
            Gdal.AllRegister();
            Driver d = GetDriverByExtension(fileName);
            if (d == null) return null;
            Dataset ds;
            if (bandType == ImageBandType.ARGB)
            {
                ds = d.Create(fileName, width, height, 4, DataType.GDT_Byte, new string[] { });
            }
            else if (bandType == ImageBandType.RGB)
            {
                ds = d.Create(fileName, width, height, 3, DataType.GDT_Byte, new string[] { });
            }
            else if (bandType == ImageBandType.PalletCoded)
            {
                ds = d.Create(fileName, width, height, 1, DataType.GDT_Byte, new string[] { });
            }
            else
            {
                ds = d.Create(fileName, width, height, 1, DataType.GDT_Byte, new string[] { });
            }

            return new GdalImage(fileName, ds, bandType);
        }
Example #6
0
        /// <summary>
        /// Opens a shapefile
        /// </summary>
        /// <param name="fileName">The string fileName of the point shapefile to load</param>
        /// <param name="progressHandler">Any valid implementation of the DotSpatial.Data.IProgressHandler</param>
        public void Open(string fileName, IProgressHandler progressHandler)
        {
            //JK - handle case when filename doesn't exist
            if (!File.Exists(fileName))
            {
                Attributes = new AttributeTable();
                Header = new ShapefileHeader { FileLength = 100, ShapeType = ShapeType.Point };
                FeatureType = FeatureType.Point;
                return;
            }

            IndexMode = true;
            Filename = fileName;

            Header = new ShapefileHeader(fileName);
            CoordinateType = CoordinateType.Regular;
            if (Header.ShapeType == ShapeType.PointM)
            {
                CoordinateType = CoordinateType.M;
            }
            if (Header.ShapeType == ShapeType.PointZ)
            {
                CoordinateType = CoordinateType.Z;
            }
            MyExtent = Header.ToExtent();
            Name = Path.GetFileNameWithoutExtension(fileName);
            Attributes.Open(fileName);
            FillPoints(fileName, progressHandler);
            ReadProjection();
        }
        /// <summary>
        /// Creates a new instance of BufferedBinaryReader, and specifies where to send progress messages.
        /// </summary>
        /// <param name="fileName">The string path of a file to open using this BufferedBinaryReader.</param>
        /// <param name="progressHandler">Any implementation of IProgressHandler for receiving progress messages.</param>
        public BufferedBinaryReader(string fileName, IProgressHandler progressHandler)
        {
            //Modified 9/22/09 by L. C. Wilson to open as read-only so it is possible to open read-only files
            //Not sure if elsewhere write access is required
            _fileName = fileName;
            _fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            _binaryReader = new BinaryReader(_fileStream);

            FileInfo fi = new FileInfo(fileName);

            _fileLength = fi.Length;
            _fileOffset = 0;

            _readOffset = -1; // There is no buffer loaded.

            _bufferSize = 0;
            _bufferOffset = -1; // -1 means no buffer is loaded.

            _isFinishedBuffering = false;
            _isFinishedReading = false;
            _progressMeter = new ProgressMeter(progressHandler, "Reading from " + Path.GetFileName(fileName), _fileLength);

            if (_fileLength < 10000000) _progressMeter.StepPercent = 5;
            if (_fileLength < 5000000) _progressMeter.StepPercent = 10;
            if (_fileLength < 100000) _progressMeter.StepPercent = 50;
            if (_fileLength < 10000) _progressMeter.StepPercent = 100;
            //long testMax = _fileLength / _progressMeter.StepPercent;
            //if (testMax < (long)9600000) _maxBufferSize = Convert.ToInt32(testMax); // otherwise keep it at 96000000
        }
Example #8
0
 /// <summary>
 /// A progress meter that simply keeps track of progress and is capable of sending progress messages.
 /// </summary>
 /// <param name="progressHandler">Any valid implementation if IProgressHandler that will handle the progress function</param>
 /// <param name="baseMessage">The message without any progress information.</param>
 /// <param name="endValue">Percent should show a range between the MinValue and MaxValue.  MinValue is assumed to be 0.</param>
 public ProgressMeter(IProgressHandler progressHandler, string baseMessage, object endValue)
 {
     _endValue = Convert.ToDouble(endValue);
     _progressHandler = progressHandler;
     Reset();
     _baseMessage = baseMessage;
 }
Example #9
0
 /// <summary>
 /// Creates a new instance of Smoother
 /// </summary>
 public Smoother(BitmapData inBmpData, byte[] inRgbData, IProgressHandler progHandler)
 {
     _bmpData = inBmpData;
     _rgbData = inRgbData;
     _result = new byte[inRgbData.Length];
     pm = new ProgressMeter(progHandler, "Smoothing Image", inBmpData.Height);
 }
        private int _writeOffset; //

        #endregion

        #region Constructors

        /// <summary>
        /// Creates a new instance of BufferedBinaryReader.
        /// </summary>
        ///<param name="fileName">The string path of a file to open using this BufferedBinaryReader.</param>
        public BufferedBinaryWriter(string fileName)
            : this(fileName, null, 100000)
        {
            // This is just an overload that sends the default null value in for the progressHandler
            _progressHandler = DataManager.DefaultDataManager.ProgressHandler;
            _progressMeter = new ProgressMeter(_progressHandler);
        }
        /// <summary>
        /// This will resample the cells.
        /// If the cell size is zero, this will default to the shorter of the width or height
        /// divided by 256.
        /// </summary>
        /// <param name="input1">Input Raster.</param>
        /// <param name="cellHeight">New Cell Height or Null.</param>
        /// <param name="cellWidth">New Cell Width or Null.</param>
        /// <param name="destFilename">Output Raster Name.</param>
        /// <param name="progressHandler">An interface for handling the progress messages.</param>
        /// <returns>Resampled raster.</returns>
        public static IRaster ReSample(IRaster input1,double cellHeight, double cellWidth, string destFilename, IProgressHandler progressHandler)
        {
            if (input1 == null)
                return null;

            IEnvelope envelope = input1.Bounds.Envelope;

            if (cellHeight == 0)
            {
                cellHeight = envelope.Height / 256;
            }
            if(cellWidth==0)
            {
                cellWidth = envelope.Width / 256;
            }
                
            //Calculate new number of columns and rows
            int noOfCol = Convert.ToInt32(Math.Abs(envelope.Width / cellWidth));
            int noOfRow = Convert.ToInt32(Math.Abs(envelope.Height / cellHeight));


            IRaster output = Raster.Create(destFilename, "", noOfCol, noOfRow, 1, input1.DataType, new[] { "" });
            RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope);
            output.Bounds = bound;

            output.NoDataValue = input1.NoDataValue;

            RcIndex index1;
            int max = (output.Bounds.NumRows);
            ProgressMeter pm = new ProgressMeter(progressHandler, "ReSize Cells", max);
            //Loop throug every cell for new value

            for (int i = 0; i < max; i++)
            {
                for (int j = 0; j < output.Bounds.NumColumns; j++)
                {
                    //Projet the cell position to Map
                    Coordinate cellCenter = output.CellToProj(i, j);
                    index1 = input1.ProjToCell(cellCenter);

                    double val;
                    if (index1.Row <= input1.EndRow && index1.Column <= input1.EndColumn && index1.Row > -1 && index1.Column > -1)
                    {
                        if (input1.Value[index1.Row, index1.Column] == input1.NoDataValue)
                            val = output.NoDataValue;
                        else
                            val = input1.Value[index1.Row, index1.Column];
                    }
                    else
                        val = output.NoDataValue;

                    output.Value[i, j] = val;
                }
                pm.CurrentPercent = i;
            }

            output.Save();
            pm.Reset();
            return output;
        }
        /// <summary>
        /// Creates a new instance of BufferedBinaryWriter, and specifies where to send progress messages.
        /// </summary>
        /// <param name="fileName">The string path of a file to open using this BufferedBinaryReader.</param>
        /// <param name="progressHandler">Any implementation of IProgressHandler for receiving progress messages.</param>
        /// <param name="expectedByteCount">A long specifying the number of bytes that will be written for the purposes of tracking progress</param>
        public BufferedBinaryWriter(string fileName, IProgressHandler progressHandler, long expectedByteCount)
        {
            if (File.Exists(fileName))
            {
                // Imagine we have written a header and want to add more stuff
                _fileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write);
                FileInfo fi = new FileInfo(fileName);
                _fileLength = fi.Length;
                _fileOffset = 0;
            }
            else
            {
                // In this case, we just create the new file from scratch
                _fileStream = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write);
                _fileLength = 0;
                _fileOffset = 0;
            }

            _binaryWriter = new BinaryWriter(_fileStream);
            _buffer = new byte[expectedByteCount];
            _bufferSize = Convert.ToInt32(expectedByteCount);
            _maxBufferSize = _bufferSize;
            _writeOffset = -1; // There is no buffer loaded.
            _bufferOffset = -1; // -1 means no buffer is loaded.

            //report progress
            if (progressHandler != null)
            {
                _progressHandler = progressHandler;
                _progressMeter.Key = "Writing to " + Path.GetFileName(fileName);
                _progressMeter.EndValue = expectedByteCount;
            }
        }
Example #13
0
 /// <summary>
 /// Fills depressions in an image
 /// - Files specified by parameters
 /// - Progress and status messages will be sent back via IProgressHandler
 /// - Frames will be sized to default values
 /// </summary>
 /// <param name="SourceFile">String filename of unfilled DEM</param>
 /// <param name="DestFile">String filename of output file</param>
 /// <param name="progress">The progress.</param>
 /// <remarks>
 /// Images too large to process all at once are broken down into a framework.
 /// A frame represents what will be loaded into memory at any given time.
 /// </remarks>
 public static void Fill(string SourceFile, string DestFile, IProgressHandler progress)
 {
     // 2000 width
     // 1000 height
     //MapWinUtility.Logger.Dbg("Fill(SourceFile: " + SourceFile + ",\n" +
     //                         "     DestFile: " + DestFile + ",\n" +
     //                         "     IProgressHandler");
     File_Fill(SourceFile, DestFile, true, false, 10000, 2000, progress);
 }
 /// <summary>
 /// Creates a new instance of the GeoPluginArgs
 /// </summary>
 /// <param name="map">Each Manager is associated with a single map</param>
 /// <param name="legend">The legend</param>
 /// <param name="mainMenu">The main menu</param>
 /// <param name="mainToolStrip">The main toolstrip</param>
 /// <param name="progressHandler">The progress handler</param>
 /// <param name="plugins">The list of plugins controlled by the manager</param>
 /// <param name="toolStripContainer">The container where any toolstrips should be added</param>
 public GeoPluginArgs(IMap map, ILegend legend, MenuStrip mainMenu, ToolStrip mainToolStrip, IProgressHandler progressHandler, List<IMapPlugin> plugins, ToolStripContainer toolStripContainer)
 {
     _toolStripContainer = toolStripContainer;
     _map = map;
     _legend = legend;
     _mainMenu = mainMenu;
     _mainToolStrip = mainToolStrip;
     _plugins = plugins;
     _progressHandler = progressHandler;
 }
 /// <summary>
 /// Constructor that also accepts a progres handler to show the progress of loading the values into memory.
 /// </summary>
 /// <param name="filename">The filename to open.</param>
 /// <param name="progressHandler">Any valid implementation of the IProgressHandler interface.</param>
 public ShapefileFeatureSet(string filename, IProgressHandler progressHandler)
 {
     //Fields = new Dictionary<string, Field>();
     _columns = new List<Field>();
     DataTable = new System.Data.DataTable();
     Features = new FeatureList(this);
     // Since they have passed a filename go ahead and open it
     Filename = filename;
     FeatureType = FeatureTypes.Unspecified; // this will get set when queried the first time
     Name = Path.GetFileNameWithoutExtension(filename);
     Open(progressHandler);
 }
        /// <summary>
        /// Constructs a Time-Based progress meter that shows progress against an expected time.
        /// </summary>
        /// <param name="progressHandler"></param>
        /// <param name="baseMessage"></param>
        /// <param name="estimatedTime"></param>
        public TimedProgressMeter(IProgressHandler progressHandler, string baseMessage, TimeSpan estimatedTime)
        {
            _progressHandler = progressHandler;
            _baseMessage = baseMessage;
            _timeSpan = estimatedTime;
            _endValue = estimatedTime.TotalSeconds * 1000;

            _timer = new Timer();
            _timer.Interval = Convert.ToInt32(_timeSpan.TotalSeconds * 10); // Attempt to have a tick once during each estimated percentile
            //_timer.Interval = 100;
            _timer.Tick += TimerTick;
            _timer.Start(); // Timers should be on another thread...
        }
        protected override IEnumerable<SeriesDataCart> GetSeriesCatalogForBox(double xMin, double xMax, double yMin, double yMax, string keyword,
            DateTime startDate, DateTime endDate, int[] networkIDs, IProgressHandler bgWorker, long currentTile, long totalTilesCount)
        {
            bgWorker.ReportMessage(string.Format("Executed query to the database. Keyword: {0}. Tile {1}/{2}.", keyword, currentTile, totalTilesCount));

            var dt = _db.GetSeriesDataTableInBox(xMin, xMax, yMin, yMax, new []{keyword}, startDate, endDate, networkIDs);
            var seriesList = new List<SeriesDataCart>(dt.Rows.Count);
            foreach (DataRow row in dt.Rows)
            {
                var series = _db.SeriesDataCartFromRow(row);
                if (series != null)
                {
                    // Update BeginDate/EndDate/ValueCount to the user-specified range
                    SearchHelper.UpdateDataCartToDateInterval(series, startDate, endDate);
                    seriesList.Add(series);
                }
            }
            return seriesList;
        }
 /// <summary>
 /// Opens a shapefile
 /// </summary>
 /// <param name="fileName">The string fileName of the point shapefile to load</param>
 /// <param name="progressHandler">Any valid implementation of the DotSpatial.Data.IProgressHandler</param>
 public void Open(string fileName, IProgressHandler progressHandler)
 {
     IndexMode = true;
     Filename = fileName;
     FeatureType = FeatureType.MultiPoint;
     Header = new ShapefileHeader(fileName);
     CoordinateType = CoordinateType.Regular;
     if (Header.ShapeType == ShapeType.MultiPointM)
     {
         CoordinateType = CoordinateType.M;
     }
     if (Header.ShapeType == ShapeType.MultiPointZ)
     {
         CoordinateType = CoordinateType.Z;
     }
     Name = Path.GetFileNameWithoutExtension(fileName);
     Attributes.Open(fileName);
     FillPoints(fileName, progressHandler);
     ReadProjection();
 }
        /// <summary>
        /// Not Implemented yet
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="featureType"></param>
        /// <param name="inRam"></param>
        /// <param name="container"></param>
        /// <param name="progressHandler"></param>
        /// <returns></returns>
        public IFeatureLayer CreateNew(string fileName, FeatureType featureType, bool inRam, ICollection<ILayer> container, IProgressHandler progressHandler)
        {
            ShapefileDataProvider dp = new ShapefileDataProvider();
            IFeatureSet fs = dp.CreateNew(fileName, featureType, inRam, progressHandler);
            if (progressHandler == null) progressHandler = LayerManager.DefaultLayerManager.ProgressHandler;

            if (fs.FeatureType == FeatureType.Line)
            {
                return new MapLineLayer(fs, container);
            }
            if (fs.FeatureType == FeatureType.Polygon)
            {
                return new MapPolygonLayer(fs, container);
            }
            if (fs.FeatureType == FeatureType.Point || fs.FeatureType == FeatureType.MultiPoint)
            {
                return new MapPointLayer(fs, container);
            }
            return null;
        }
 /// <summary>
 /// Opens a shapefile
 /// </summary>
 /// <param name="filename">The string filename of the line shapefile to load</param>
 /// <param name="progressHandler">Any valid implementation of the MapWindow.Main.IProgressHandler</param>
 public void Open(string filename, IProgressHandler progressHandler)
 {
     Filename = filename;
     FeatureType = FeatureTypes.Line;
     Header = new ShapefileHeader(filename);
     CoordinateType = CoordinateTypes.Regular;
     IndexMode = true;
     if (Header.ShapeType == ShapeTypes.PolyLineM)
     {
         CoordinateType = CoordinateTypes.M;
     }
     if (Header.ShapeType == ShapeTypes.PolyLineZ)
     {
         CoordinateType = CoordinateTypes.Z;
     }
     base.Envelope = Header.ToEnvelope(); 
     Name = Path.GetFileNameWithoutExtension(filename);
     Attributes.Open(filename);
     FillLines(filename, progressHandler);
     ReadProjection();
 }
        /// <summary>
        /// Opens a shapefile, but returns it as a FeatureLayer
        /// </summary>
        /// <param name="fileName">The string fileName</param>
        /// <param name="inRam">Boolean, if this is true it will attempt to open the entire layer in memory.</param>
        /// <param name="container">A container to hold this layer.</param>
        /// <param name="progressHandler">The progress handler that should receive status messages</param>
        /// <returns>An IFeatureLayer</returns>
        public ILayer OpenLayer(string fileName, bool inRam, ICollection<ILayer> container, IProgressHandler progressHandler)
        {
            ShapefileDataProvider dp = new ShapefileDataProvider();
            IFeatureSet fs = dp.Open(fileName);

            if (fs != null)
            {
                if (fs.FeatureType == FeatureType.Line)
                {
                    return new MapLineLayer(fs, container);
                }
                if (fs.FeatureType == FeatureType.Polygon)
                {
                    return new MapPolygonLayer(fs, container);
                }
                if (fs.FeatureType == FeatureType.Point || fs.FeatureType == FeatureType.MultiPoint)
                {
                    return new MapPointLayer(fs, container);
                }
            }
            return null;
        }
        /// <summary>
        /// Creates a new instance of BufferedBinaryWriter, and specifies where to send progress messages.
        /// </summary>
        /// <param name="filename">The string path of a file to open using this BufferedBinaryReader.</param>
        /// <param name="progressHandler">Any implementation of IProgressHandler for receiving progress messages.</param>
        /// <param name="expectedByteCount">A long specifying the number of bytes that will be written for the purposes of tracking progress</param>
        public BufferedBinaryWriter(string filename, IProgressHandler progressHandler, long expectedByteCount)
        {
           
            
            if (File.Exists(filename))
            {
                // Imagine we have written a header and want to add more stuff
                _fileStream = new FileStream(filename, FileMode.Append, FileAccess.Write);
                FileInfo fi = new FileInfo(filename);
                _fileLength = fi.Length;
                _fileOffset = 0;
            }
            else
            {
                // In this case, we just create the new file from scratch
                _fileStream = new FileStream(filename, FileMode.CreateNew, FileAccess.Write);
                _fileLength = 0;
                _fileOffset = 0;
            }
            
            _binaryWriter = new BinaryWriter(_fileStream);
            _buffer = new byte[expectedByteCount];
            _bufferSize = Convert.ToInt32(expectedByteCount);
            _maxBufferSize = _bufferSize;
            _writeOffset = -1; // There is no buffer loaded.
            _bufferOffset = -1; // -1 means no buffer is loaded.

            ProgressHandler = progressHandler;
            ProgressMeter.Key = "Writing to " + System.IO.Path.GetFileName(filename);
            ProgressMeter.EndValue = expectedByteCount;

            //_progressMeter = new ProgressMeter(progressHandler, "Writing to " + System.IO.Path.GetFileName(filename), expectedByteCount);
            //if (expectedByteCount < 1000000) _progressMeter.StepPercent = 5;
            //if (expectedByteCount < 5000000) _progressMeter.StepPercent = 10;
            //if (expectedByteCount < 100000) _progressMeter.StepPercent = 50;
            //long testMax = expectedByteCount / _progressMeter.StepPercent;
            //if (testMax < (long)9600000) _maxBufferSize = Convert.ToInt32(testMax); // otherwise keep it at 96000000
        }
        /// <summary>
        /// Opens a shapefile
        /// </summary>
        /// <param name="fileName">The string fileName of the polygon shapefile to load</param>
        /// <param name="progressHandler">Any valid implementation of the DotSpatial.Data.IProgressHandler</param>
        public void Open(string fileName, IProgressHandler progressHandler)
        {
            //JK - handle case when filename doesn't exist
            if (!File.Exists(fileName)) return;

            IndexMode = true;
            Filename = fileName;
            Header = new ShapefileHeader(fileName);
            CoordinateType = CoordinateType.Regular;
            if (Header.ShapeType == ShapeType.PolygonM)
            {
                CoordinateType = CoordinateType.M;
            }
            if (Header.ShapeType == ShapeType.PolygonZ)
            {
                CoordinateType = CoordinateType.Z;
            }
            Name = Path.GetFileNameWithoutExtension(fileName);
            Attributes.Open(fileName);

            FillPolygons(fileName, progressHandler);
            ReadProjection();
        }
Example #24
0
        /// <summary>
        /// Creates a new image given the specified file format
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="inRam">if set to <c>true</c> should load entire file in ram.</param>
        /// <param name="progHandler">The prog handler.</param>
        /// <param name="bandType">Type of the band.</param>
        /// <returns></returns>
        public IImageData Create(string fileName, int width, int height, bool inRam, IProgressHandler progHandler, ImageBandType bandType)
        {
            Driver d = GetDriverByExtension(fileName);
            if (d == null) return null;
            Dataset ds;
            switch (bandType)
            {
                case ImageBandType.ARGB:
                    ds = d.Create(fileName, width, height, 4, DataType.GDT_Byte, new string[] { });
                    break;
                case ImageBandType.RGB:
                    ds = d.Create(fileName, width, height, 3, DataType.GDT_Byte, new string[] { });
                    break;
                case ImageBandType.PalletCoded:
                    ds = d.Create(fileName, width, height, 1, DataType.GDT_Byte, new string[] { });
                    break;
                default:
                    ds = d.Create(fileName, width, height, 1, DataType.GDT_Byte, new string[] { });
                    break;
            }

            return new GdalImage(fileName, ds, bandType);
        }
Example #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Layer"/> class.
 /// </summary>
 /// <param name="progressHandler">The progress handler.</param>
 protected Layer(IProgressHandler progressHandler)
 {
     _progressHandler = progressHandler;
     Configure();
 }
Example #26
0
        // X Y MultiPoints
        // ---------------------------------------------------------
        // Position     Value               Type        Number      Byte Order
        // ---------------------------------------------------------
        // Byte 0       Record Number       Integer     1           Big
        // Byte 4       Content Length      Integer     1           Big
        // Byte 8       Shape Type 8        Integer     1           Little
        // Byte 12      Xmin                Double      1           Little
        // Byte 20      Ymin                Double      1           Little
        // Byte 28      Xmax                Double      1           Little
        // Byte 36      Ymax                Double      1           Little
        // Byte 44      NumPoints           Integer     1           Little
        // Byte 48      Points              Point       NumPoints   Little

        // X Y M MultiPoints
        // ---------------------------------------------------------
        // Position     Value               Type        Number      Byte Order
        // ---------------------------------------------------------
        // Byte 0       Record Number       Integer     1           Big
        // Byte 4       Content Length      Integer     1           Big
        // Byte 8       Shape Type 28       Integer     1           Little
        // Byte 12      Box (Xmin - Ymax)   Double      4           Little
        // Byte 44      NumPoints           Integer     1           Little
        // Byte 48      Points              Point       NumPoints   Little
        // Byte X*      Mmin                Double      1           Little
        // Byte X+8*    Mmax                Double      1           Little
        // Byte X+16*   Marray              Double      NumPoints   Little
        // X = 48 + (16 * NumPoints)
        // * = optional

        // X Y Z M MultiPoints
        // ---------------------------------------------------------
        // Position     Value               Type        Number  Byte Order
        // ---------------------------------------------------------
        // Byte 0       Record Number       Integer     1           Big
        // Byte 4       Content Length      Integer     1           Big
        // Byte 8       Shape Type 18       Integer     1           Little
        // Byte 12      Box                 Double      4           Little
        // Byte 44      NumPoints           Integer     1           Little
        // Byte 48      Points              Point       NumPoints   Little
        // Byte X       Zmin                Double      1           Little
        // Byte X+8     Zmax                Double      1           Little
        // Byte X+16    Zarray              Double      NumPoints   Little
        // Byte Y*      Mmin                Double      1           Little
        // Byte Y+8*    Mmax                Double      1           Little
        // Byte Y+16*   Marray              Double      NumPoints   Little
        // X = 48 + (16 * NumPoints)
        // Y = X + 16 + (8 * NumPoints)
        // * = optional

        /// <summary>
        /// Obtains a typed list of MultiPoint structures with double values associated with the various coordinates.
        /// </summary>
        /// <param name="fileName">Name of the file that gets loaded.</param>
        /// <param name="progressHandler">Progress handler</param>
        private void FillPoints(string fileName, IProgressHandler progressHandler)
        {
            // Check whether file is empty or not all parameters are set correctly.
            if (!CanBeRead(fileName, this, ShapeType.MultiPoint, ShapeType.MultiPointM, ShapeType.MultiPointZ))
            {
                return;
            }

            // Reading the headers gives us an easier way to track the number of shapes and their overall length etc.
            List <ShapeHeader> shapeHeaders = ReadIndexFile(fileName);
            int numShapes = shapeHeaders.Count;

            bool isM = Header.ShapeType == ShapeType.MultiPointZ || Header.ShapeType == ShapeType.MultiPointM;
            bool isZ = Header.ShapeType == ShapeType.MultiPointZ;

            int totalPointsCount = 0;
            int totalPartsCount  = 0;
            var shapeIndices     = new List <ShapeRange>(numShapes);

            var progressMeter = new ProgressMeter(progressHandler, "Reading from " + Path.GetFileName(fileName))
            {
                StepPercent = 5
            };

            using (var reader = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 65536))
            {
                var boundsBytes = new byte[4 * 8];
                var bounds      = new double[4];
                for (int shp = 0; shp < numShapes; shp++)
                {
                    progressMeter.CurrentPercent = (int)(shp * 50.0 / numShapes);

                    // Read from the index file because some deleted records might still exist in the .shp file.
                    long offset = shapeHeaders[shp].ByteOffset;
                    reader.Seek(offset, SeekOrigin.Begin);

                    var shape = new ShapeRange(FeatureType.MultiPoint, CoordinateType)
                    {
                        RecordNumber  = reader.ReadInt32(Endian.BigEndian),
                        ContentLength = reader.ReadInt32(Endian.BigEndian),
                        ShapeType     = (ShapeType)reader.ReadInt32(),
                        StartIndex    = totalPointsCount,
                        NumParts      = 1
                    };
                    Debug.Assert(shape.RecordNumber == shp + 1, "shape.RecordNumber == shp + 1");

                    if (shape.ShapeType != ShapeType.NullShape)
                    {
                        // Bounds
                        reader.Read(boundsBytes, 0, boundsBytes.Length);
                        Buffer.BlockCopy(boundsBytes, 0, bounds, 0, boundsBytes.Length);
                        shape.Extent.MinX = bounds[0];
                        shape.Extent.MinY = bounds[1];
                        shape.Extent.MaxX = bounds[2];
                        shape.Extent.MaxY = bounds[3];

                        //// Num Parts
                        totalPartsCount += 1;

                        // Num Points
                        shape.NumPoints   = reader.ReadInt32();
                        totalPointsCount += shape.NumPoints;
                    }

                    shapeIndices.Add(shape);
                }

                var vert    = new double[totalPointsCount * 2];
                var vertInd = 0;

                var parts = new int[totalPartsCount];

                int      mArrayInd = 0, zArrayInd = 0;
                double[] mArray = null, zArray = null;
                if (isM)
                {
                    mArray = new double[totalPointsCount];
                }
                if (isZ)
                {
                    zArray = new double[totalPointsCount];
                }

                int partsOffset = 0;
                for (int shp = 0; shp < numShapes; shp++)
                {
                    progressMeter.CurrentPercent = (int)(50 + shp * 50.0 / numShapes);

                    var shape = shapeIndices[shp];
                    if (shape.ShapeType == ShapeType.NullShape)
                    {
                        continue;
                    }

                    reader.Seek(shapeHeaders[shp].ByteOffset, SeekOrigin.Begin);
                    reader.Seek(3 * 4 + 32 + 4, SeekOrigin.Current); // Skip first bytes (Record Number, Content Length, Shapetype + BoundingBox + NumPoints)

                    // Read points
                    var pointsBytes = reader.ReadBytes(8 * 2 * shape.NumPoints); // Numpoints * Point (X(8) + Y(8))
                    Buffer.BlockCopy(pointsBytes, 0, vert, vertInd, pointsBytes.Length);
                    vertInd += 8 * 2 * shape.NumPoints;

                    // Fill parts
                    shape.Parts.Capacity = shape.NumParts;
                    for (int p = 0; p < shape.NumParts; p++)
                    {
                        int endIndex   = shape.NumPoints + shape.StartIndex;
                        int startIndex = parts[partsOffset + p] + shape.StartIndex;
                        if (p < shape.NumParts - 1)
                        {
                            endIndex = parts[partsOffset + p + 1] + shape.StartIndex;
                        }

                        int count = endIndex - startIndex;
                        var part  = new PartRange(vert, shape.StartIndex, parts[partsOffset + p], FeatureType.MultiPoint)
                        {
                            NumVertices = count
                        };
                        shape.Parts.Add(part);
                    }

                    partsOffset += shape.NumParts;

                    // Fill M and Z arrays
                    switch (Header.ShapeType)
                    {
                    case ShapeType.MultiPointM:
                        if (shape.ContentLength * 2 > 44 + 4 * shape.NumParts + 16 * shape.NumPoints)
                        {
                            var mExt = (IExtentM)shape.Extent;
                            mExt.MinM = reader.ReadDouble();
                            mExt.MaxM = reader.ReadDouble();

                            var mBytes = reader.ReadBytes(8 * shape.NumPoints);
                            Buffer.BlockCopy(mBytes, 0, mArray, mArrayInd, mBytes.Length);
                            mArrayInd += 8 * shape.NumPoints;
                        }

                        break;

                    case ShapeType.MultiPointZ:
                        var zExt = (IExtentZ)shape.Extent;
                        zExt.MinZ = reader.ReadDouble();
                        zExt.MaxZ = reader.ReadDouble();

                        var zBytes = reader.ReadBytes(8 * shape.NumPoints);
                        Buffer.BlockCopy(zBytes, 0, zArray, zArrayInd, zBytes.Length);
                        zArrayInd += 8 * shape.NumPoints;

                        // These are listed as "optional" but there isn't a good indicator of how to
                        // determine if they were added.
                        // To handle the "optional" M values, check the contentLength for the feature.
                        // The content length does not include the 8-byte record header and is listed in 16-bit words.
                        if (shape.ContentLength * 2 > 60 + 4 * shape.NumParts + 24 * shape.NumPoints)
                        {
                            goto case ShapeType.MultiPointM;
                        }

                        break;
                    }
                }

                if (isM)
                {
                    M = mArray;
                }
                if (isZ)
                {
                    Z = zArray;
                }
                ShapeIndices = shapeIndices;
                Vertex       = vert;
            }

            progressMeter.Reset();
        }
Example #27
0
 /// <summary>
 /// Opens a fileName using the default layer provider and returns a new layer. The layer will not automatically have a container or be added to a map.
 /// </summary>
 /// <param name="fileName">The string fileName of the layer to open</param>
 /// <param name="progressHandler">An IProgresshandler that overrides the Default Layer Manager's progress handler</param>
 /// <returns>An ILayer interface with the new layer.</returns>
 public static ILayer OpenFile(string fileName, IProgressHandler progressHandler)
 {
     return(File.Exists(fileName) == false ? null : LayerManager.DefaultLayerManager.OpenLayer(fileName, progressHandler));
 }
Example #28
0
 /// <summary>
 /// Constructor that also shows progress.
 /// </summary>
 /// <param name="inFeatureSet">A featureset that contains lines.</param>
 /// <param name="container">An IContainer that the line layer should be created in.</param>
 /// <param name="progressHandler">An IProgressHandler for receiving status messages.</param>
 /// <exception cref="LineFeatureTypeException">Thrown if a non-line featureSet is supplied.</exception>
 public LineLayer(IFeatureSet inFeatureSet, ICollection <ILayer> container, IProgressHandler progressHandler)
     : base(inFeatureSet, container, progressHandler)
 {
     Configure(inFeatureSet);
 }
Example #29
0
 /// <summary>
 /// Creates a new instance of the ImageLayer by opening the specified fileName, relaying progress to the
 /// specified handler, and automatically adds the new layer to the specified container.
 /// </summary>
 /// <param name="fileName">The fileName to open</param>
 /// <param name="progressHandler">A ProgressHandler that can receive progress updates</param>
 /// <param name="container">The layer list that should contain this image layer</param>
 public ImageLayer(string fileName, IProgressHandler progressHandler, ICollection <ILayer> container)
     : base(container)
 {
     Symbolizer = new ImageSymbolizer();
     DataSet    = DataManager.DefaultDataManager.OpenImage(fileName, progressHandler);
 }
Example #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TimedProgressMeter"/> class that simply keeps track of progress and is capable of sending progress messages.
 /// This assumes a MaxValue of 100 unless it is changed later.
 /// </summary>
 /// <param name="progressHandler">Any valid IProgressHandler that will display progress messages.</param>
 /// <param name="baseMessage">A base message to use as the basic status for this progress handler.</param>
 public TimedProgressMeter(IProgressHandler progressHandler, string baseMessage)
     : this(progressHandler, baseMessage, 100)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskHandler"/> class.
 /// </summary>
 /// <param name="progressHandler">The progress handler.</param>
 public TaskHandler(IProgressHandler progressHandler)
 {
     this.progressHandler = progressHandler;
 }
Example #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MapLayerCollection"/> class that is blank.
 /// This is especially useful for tracking layers that can draw themselves. This does not concern itself with
 /// view extents like a dataframe, but rather is a grouping of layers that is itself also an IMapLayer.
 /// </summary>
 /// <param name="containerFrame">The map frame.</param>
 /// <param name="progressHandler">The progress handler.</param>
 public MapLayerCollection(IMapFrame containerFrame, IProgressHandler progressHandler)
 {
     base.MapFrame    = containerFrame;
     base.ParentGroup = containerFrame;
     ProgressHandler  = progressHandler;
 }
Example #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MapLayerCollection"/> class in the situation
 /// where the map frame is not the immediate parent, but rather the group is the immediate parent,
 /// while frame is the ultimate map frame that contains this geo layer collection.
 /// </summary>
 /// <param name="frame">The map frame.</param>
 /// <param name="group">The parent of this.</param>
 /// <param name="progressHandler">The progress handler.</param>
 public MapLayerCollection(IMapFrame frame, IMapGroup group, IProgressHandler progressHandler)
 {
     base.MapFrame   = frame;
     ParentGroup     = group;
     ProgressHandler = progressHandler;
 }
Example #34
0
 /// <summary>
 /// This allows overriding layers to handle any memory cleanup.
 /// </summary>
 /// <param name="disposeManagedResources">True if managed resources should be set to null.</param>
 protected virtual void Dispose(bool disposeManagedResources)
 {
     if (_isDisposed)
     {
         return;
     }
     if (disposeManagedResources)
     {
         LayerSelected = null;
         ZoomToLayer = null;
         ShowProperties = null;
         FinishedLoading = null;
         SelectionChanged = null;
         base.ContextMenuItems = null;
         MyExtent = null;
         base.LegendText = null;
         _progressHandler = null;
         _progressMeter = null;
         _invalidatedRegion = null;
         _mapFrame = null;
         _propertyDialogProvider = null;
     }
     // Since the InnerDataset likely contains unmanaged memory constructs, dispose of it here.
     if (_dataSet != null)
     {
         _dataSet.UnlockDispose();
         if (!_dataSet.IsDisposeLocked)
         {
             _dataSet.Dispose();
         }
     }
     if (_editCopy != null) _editCopy.Dispose();
     _isDisposed = true;
 }
Example #35
0
 /// <summary>
 /// Causes the raster to calculate a hillshade using the specified progress handler
 /// </summary>
 /// <param name="progressHandler">The progress handler to use</param>
 public void CreateHillShade(IProgressHandler progressHandler)
 {
     _hillshade = Raster.CreateHillShade(_shadedRelief, progressHandler);
 }
Example #36
0
 /// <summary>
 /// Opens a fileName using the default layer provider and returns a new layer.  The layer will not automatically have a container or be added to a map.
 /// </summary>
 /// <param name="fileName">The string fileName of the layer to open</param>
 /// <param name="progressHandler">An IProgresshandler that overrides the Default Layer Manager's progress handler</param>
 /// <returns>An ILayer interface with the new layer.</returns>
 public static ILayer OpenFile(string fileName, IProgressHandler progressHandler)
 {
     return File.Exists(fileName) == false ? null : LayerManager.DefaultLayerManager.OpenLayer(fileName, progressHandler);
 }
Example #37
0
 /// <summary>
 /// Creates a new layer with only a progress handler
 /// </summary>
 /// <param name="progressHandler"></param>
 protected Layer(IProgressHandler progressHandler)
 {
     _progressHandler = progressHandler;
     Configure();
 }
Example #38
0
        /// <summary>
        /// Attempts to create a new GeoPointLayer using the specified file.  If the filetype is not
        /// does not generate a point layer, an exception will be thrown.
        /// </summary>
        /// <param name="fileName">A string fileName to create a point layer for.</param>
        /// <param name="progressHandler">Any valid implementation of IProgressHandler for receiving progress messages</param>
        /// <returns>A GeoPointLayer created from the specified fileName.</returns>
        public static new MapPointLayer OpenFile(string fileName, IProgressHandler progressHandler)
        {
            ILayer fl = LayerManager.DefaultLayerManager.OpenLayer(fileName, progressHandler);

            return(fl as MapPointLayer);
        }
Example #39
0
        /// <summary>
        /// Attempts to call the open fileName method for any ILayerProvider plugin
        /// that matches the extension on the string.
        /// </summary>
        /// <param name="fileName">A String fileName to attempt to open.</param>
        /// <param name="inRam">A boolean value that if true will attempt to force a load of the data into memory. This value overrides the property on this LayerManager.</param>
        /// <param name="container">A container to open this layer in</param>
        /// <param name="progressHandler">Specifies the progressHandler to receive progress messages. This value overrides the property on this LayerManager.</param>
        /// <returns>An ILayer</returns>
        public virtual ILayer OpenLayer(string fileName, bool inRam, ICollection <ILayer> container, IProgressHandler progressHandler)
        {
            if (File.Exists(fileName) == false)
            {
                return(null);
            }

            var dm = LayerManager.DefaultLayerManager;

            return(dm.OpenLayer(fileName, inRam, container, progressHandler));
        }
Example #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Layer"/> class.
 /// </summary>
 /// <param name="container">The container this layer should be a member of</param>
 /// <param name="progressHandler">A progress handler for handling progress messages</param>
 protected Layer(ICollection <ILayer> container, IProgressHandler progressHandler)
 {
     _progressHandler = progressHandler;
     container?.Add(this);
     Configure();
 }
Example #41
0
        // X Y MultiPoints: Total Length = 28 Bytes
        // ---------------------------------------------------------
        // Position     Value               Type        Number      Byte Order
        // ---------------------------------------------------------
        // Byte 0       Record Number       Integer     1           Big
        // Byte 4       Content Length      Integer     1           Big
        // Byte 8       Shape Type 8        Integer     1           Little
        // Byte 12      Xmin                Double      1           Little
        // Byte 20      Ymin                Double      1           Little
        // Byte 28      Xmax                Double      1           Little
        // Byte 36      Ymax                Double      1           Little
        // Byte 48      NumPoints           Integer     1           Little
        // Byte X       Points              Point       NumPoints   Little

        // X Y M MultiPoints: Total Length = 34 Bytes
        // ---------------------------------------------------------
        // Position     Value               Type        Number      Byte Order
        // ---------------------------------------------------------
        // Byte 0       Record Number       Integer     1           Big
        // Byte 4       Content Length      Integer     1           Big
        // Byte 8       Shape Type 28       Integer     1           Little
        // Byte 12      Box                 Double      4           Little
        // Byte 44      NumPoints           Integer     1           Little
        // Byte X       Points              Point       NumPoints   Little
        // Byte Y*      Mmin                Double      1           Little
        // Byte Y + 8*  Mmax                Double      1           Little
        // Byte Y + 16* Marray              Double      NumPoints   Little

        // X Y Z M MultiPoints: Total Length = 44 Bytes
        // ---------------------------------------------------------
        // Position     Value               Type        Number  Byte Order
        // ---------------------------------------------------------
        // Byte 0       Record Number       Integer     1           Big
        // Byte 4       Content Length      Integer     1           Big
        // Byte 8       Shape Type 18       Integer     1           Little
        // Byte 12      Box                 Double      4           Little
        // Byte 44      NumPoints           Integer     1           Little
        // Byte X       Points              Point       NumPoints   Little
        // Byte Y       Zmin                Double      1           Little
        // Byte Y + 8   Zmax                Double      1           Little
        // Byte Y + 16  Zarray              Double      NumPoints   Little
        // Byte Z*      Mmin                Double      1           Little
        // Byte Z+8*    Mmax                Double      1           Little
        // Byte Z+16*   Marray              Double      NumPoints   Little

        private void FillPoints(string fileName, IProgressHandler progressHandler)
        {
            // Check to ensure the fileName is not null
            if (fileName == null)
            {
                throw new NullReferenceException(DataStrings.ArgumentNull_S.Replace("%S", "fileName"));
            }

            if (File.Exists(fileName) == false)
            {
                throw new FileNotFoundException(DataStrings.FileNotFound_S.Replace("%S", fileName));
            }

            // Get the basic header information.
            ShapefileHeader header = new ShapefileHeader(fileName);

            Extent = new Extent(new[] { header.Xmin, header.Ymin, header.Xmax, header.Ymax });
            // Check to ensure that the fileName is the correct shape type
            if (header.ShapeType != ShapeType.MultiPoint &&
                header.ShapeType != ShapeType.MultiPointM &&
                header.ShapeType != ShapeType.MultiPointZ)
            {
                throw new ArgumentException(DataStrings.FileNotLines_S.Replace("%S", fileName));
            }

            // Reading the headers gives us an easier way to track the number of shapes and their overall length etc.
            List <ShapeHeader> shapeHeaders = ReadIndexFile(fileName);

            // This will set up a reader so that we can read values in huge chunks, which is much faster than one value at a time.
            BufferedBinaryReader bbReader = new BufferedBinaryReader(fileName, progressHandler);

            if (bbReader.FileLength == 100)
            {
                // The shapefile is empty so we can simply return here
                bbReader.Close();
                return;
            }

            // Skip the shapefile header by skipping the first 100 bytes in the shapefile
            bbReader.Seek(100, SeekOrigin.Begin);

            int numShapes = shapeHeaders.Count;

            byte[] bigEndians = new byte[numShapes * 8];
            byte[] allBounds  = new byte[numShapes * 32];

            ByteBlock allCoords = new ByteBlock(BLOCKSIZE);
            bool      isM       = (header.ShapeType == ShapeType.MultiPointZ || header.ShapeType == ShapeType.MultiPointM);
            bool      isZ       = (header.ShapeType == ShapeType.PolyLineZ);
            ByteBlock allZ      = null;
            ByteBlock allM      = null;

            if (isZ)
            {
                allZ = new ByteBlock(BLOCKSIZE);
            }
            if (isM)
            {
                allM = new ByteBlock(BLOCKSIZE);
            }
            int pointOffset = 0;

            for (int shp = 0; shp < numShapes; shp++)
            {
                // Read from the index file because some deleted records
                // might still exist in the .shp file.
                long offset = (shapeHeaders[shp].ByteOffset);
                bbReader.Seek(offset, SeekOrigin.Begin);

                // time: 200 ms
                ShapeRange shape = new ShapeRange(FeatureType.MultiPoint)
                {
                    RecordNumber  = bbReader.ReadInt32(false),
                    ContentLength = bbReader.ReadInt32(false),
                    ShapeType     = (ShapeType)bbReader.ReadInt32(),
                    StartIndex    = pointOffset
                };

                //bbReader.Read(bigEndians, shp * 8, 8);
                if (shape.ShapeType == ShapeType.NullShape)
                {
                    continue;
                }
                bbReader.Read(allBounds, shp * 32, 32);
                shape.NumParts  = 1;
                shape.NumPoints = bbReader.ReadInt32();
                allCoords.Read(shape.NumPoints * 16, bbReader);
                pointOffset += shape.NumPoints;

                if (header.ShapeType == ShapeType.MultiPointM)
                {
                    // These are listed as "optional" but there isn't a good indicator of
                    // how to determine if they were added.
                    // To handle the "optional" M values, check the contentLength for the feature.
                    // The content length does not include the 8-byte record header and is listed in 16-bit words.
                    if (shape.ContentLength * 2 > 44 + 4 * shape.NumParts + 16 * shape.NumPoints)
                    {
                        IExtentM mExt = (IExtentM)MyExtent;
                        mExt.MinM = bbReader.ReadDouble();
                        mExt.MaxM = bbReader.ReadDouble();
                        if (allM != null)
                        {
                            allM.Read(shape.NumPoints * 8, bbReader);
                        }
                    }
                }
                if (header.ShapeType == ShapeType.MultiPointZ)
                {
                    bool     hasM = shape.ContentLength * 2 > 60 + 4 * shape.NumParts + 24 * shape.NumPoints;
                    IExtentZ zExt = (IExtentZ)MyExtent;
                    zExt.MinZ = bbReader.ReadDouble();
                    zExt.MaxZ = bbReader.ReadDouble();
                    // For Z shapefiles, the Z part is not optional.
                    if (allZ != null)
                    {
                        allZ.Read(shape.NumPoints * 8, bbReader);
                    }

                    // These are listed as "optional" but there isn't a good indicator of
                    // how to determine if they were added.
                    // To handle the "optional" M values, check the contentLength for the feature.
                    // The content length does not include the 8-byte record header and is listed in 16-bit words.
                    if (hasM)
                    {
                        IExtentM mExt = (IExtentM)MyExtent;
                        mExt.MinM = bbReader.ReadDouble();
                        mExt.MaxM = bbReader.ReadDouble();
                        if (allM != null)
                        {
                            allM.Read(shape.NumPoints * 8, bbReader);
                        }
                    }
                }
                // Now that we have read all the values, create the geometries from the points and parts arrays.
                ShapeIndices.Add(shape);
            }
            double[] vert = allCoords.ToDoubleArray();
            Vertex = vert;
            if (isM)
            {
                M = allM.ToDoubleArray();
            }
            if (isZ)
            {
                Z = allZ.ToDoubleArray();
            }
            Array.Reverse(bigEndians);
            List <ShapeRange> shapes = ShapeIndices;

            double[] bounds = new double[numShapes * 4];
            Buffer.BlockCopy(allBounds, 0, bounds, 0, allBounds.Length);
            for (int shp = 0; shp < numShapes; shp++)
            {
                ShapeRange shape = shapes[shp];
                shape.Extent = new Extent(bounds, shp * 4);
                int       endIndex   = shape.NumPoints + shape.StartIndex;
                int       startIndex = shape.StartIndex;
                int       count      = endIndex - startIndex;
                PartRange partR      = new PartRange(vert, shape.StartIndex, 0, FeatureType.MultiPoint)
                {
                    NumVertices = count
                };
                shape.Parts.Add(partR);
            }

            bbReader.Dispose();
        }
        protected override IEnumerable <SeriesDataCart> GetSeriesCatalogForBox(double xMin, double xMax, double yMin,
                                                                               double yMax, string keyword,
                                                                               DateTime startDate, DateTime endDate,
                                                                               int[] networkIDs,
                                                                               IProgressHandler bgWorker, long currentTile, long totalTilesCount)
        {
            var url = new StringBuilder();

            url.Append(_hisCentralUrl);
            url.Append("/GetSeriesCatalogForBox2");
            url.Append("?xmin=");
            url.Append(Uri.EscapeDataString(xMin.ToString(_invariantCulture)));
            url.Append("&xmax=");
            url.Append(Uri.EscapeDataString(xMax.ToString(_invariantCulture)));
            url.Append("&ymin=");
            url.Append(Uri.EscapeDataString(yMin.ToString(_invariantCulture)));
            url.Append("&ymax=");
            url.Append(Uri.EscapeDataString(yMax.ToString(_invariantCulture)));

            //to append the keyword
            url.Append("&conceptKeyword=");
            if (!String.IsNullOrEmpty(keyword))
            {
                url.Append(Uri.EscapeDataString(keyword));
            }

            //to append the list of networkIDs separated by comma
            url.Append("&networkIDs=");
            if (networkIDs != null)
            {
                var serviceParam = new StringBuilder();
                for (int i = 0; i < networkIDs.Length - 1; i++)
                {
                    serviceParam.Append(networkIDs[i]);
                    serviceParam.Append(",");
                }
                if (networkIDs.Length > 0)
                {
                    serviceParam.Append(networkIDs[networkIDs.Length - 1]);
                }
                url.Append(Uri.EscapeDataString(serviceParam.ToString()));
            }

            //to append the start and end date
            url.Append("&beginDate=");
            url.Append(Uri.EscapeDataString(startDate.ToString("MM/dd/yyyy")));
            url.Append("&endDate=");
            url.Append(Uri.EscapeDataString(endDate.ToString("MM/dd/yyyy")));

            var keywordDesc = string.Format("[{0}. Tile {1}/{2}]",
                                            String.IsNullOrEmpty(keyword) ? "All" : keyword, currentTile,
                                            totalTilesCount);

            // Try to send request several times (in case, when server returns timeout)
            const int tryCount = 5;

            for (int i = 0; i < tryCount; i++)
            {
                try
                {
                    bgWorker.CheckForCancel();
                    bgWorker.ReportMessage(i == 0
                                               ? string.Format("Sent request: {0}", keywordDesc)
                                               : string.Format("Timeout has occurred for {0}. New Attempt ({1} of {2})...",
                                                               keywordDesc, i + 1, tryCount));

                    var request = WebRequest.Create(url.ToString());
                    request.Timeout = 30 * 1000;
                    using (var response = request.GetResponse())
                        using (var reader = XmlReader.Create(response.GetResponseStream()))
                        {
                            bgWorker.ReportMessage(string.Format("Data received for {0}", keywordDesc));
                            return(ParseSeries(reader, startDate, endDate));
                        }
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.Timeout)
                    {
                        continue;
                    }
                    throw;
                }
            }
            throw new WebException("Timeout. Try to decrease Search Area, or Select another Keywords.", WebExceptionStatus.Timeout);
        }
Example #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TimedProgressMeter"/> class.
 /// A progress meter can't actually do anything without a progressHandler, which actually displays the status.
 /// </summary>
 /// <param name="progressHandler">An IProgressHandler that will actually handle the status messages sent by this meter.</param>
 public TimedProgressMeter(IProgressHandler progressHandler)
     : this(progressHandler, "Calculating values.", 100)
 {
 }
Example #44
0
 /// <summary>
 /// Creates a new instance of the image layer by opening the specified fileName and
 /// relaying progress to the specified handler.
 /// </summary>
 /// <param name="fileName">The fileName to open</param>
 /// <param name="progressHandler">The progressHandler</param>
 public ImageLayer(string fileName, IProgressHandler progressHandler)
 {
     Symbolizer = new ImageSymbolizer();
     DataSet    = DataManager.DefaultDataManager.OpenImage(fileName, progressHandler);
 }
Example #45
0
 /// <summary>
 /// This launches an open file dialog and attempts to load the specified file.
 /// </summary>
 /// <param name="fileName">A String fileName to attempt to open.</param>
 /// <param name="progressHandler">Specifies the progressHandler to receive progress messages.  This value overrides the property on this DataManager.</param>
 /// <returns>A Layer</returns>
 public virtual ILayer OpenLayer(string fileName, IProgressHandler progressHandler)
 {
     return(OpenLayer(fileName, LoadInRam, null, progressHandler));
 }
Example #46
0
 /// <summary>
 /// Constructor that also shows progress
 /// </summary>
 /// <param name="inFeatureSet">A featureset that contains lines</param>
 /// <param name="progressHandler">An IProgressHandler for receiving status messages</param>
 /// <exception cref="LineFeatureTypeException">Thrown if a non-line featureSet is supplied</exception>
 public LineLayer(IFeatureSet inFeatureSet, IProgressHandler progressHandler)
     : base(inFeatureSet, null, progressHandler)
 {
     Configure(inFeatureSet);
 }
Example #47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MapGroup"/> class that sits in a layer list and uses the specified progress handler.
 /// </summary>
 /// <param name="container">the layer list</param>
 /// <param name="frame">The map frame.</param>
 /// <param name="progressHandler">the progress handler</param>
 public MapGroup(ICollection <IMapLayer> container, IMapFrame frame, IProgressHandler progressHandler)
     : base(frame, progressHandler)
 {
     Layers = new MapLayerCollection(frame, this, progressHandler);
     container.Add(this);
 }
Example #48
0
        /// <summary>
        /// Attempts to call the open fileName method for any ILayerProvider plugin
        /// that matches the extension on the string.
        /// </summary>
        /// <param name="fileName">A String fileName to attempt to open.</param>
        /// <param name="inRam">A boolean value that if true will attempt to force a load of the data into memory.  This value overrides the property on this LayerManager.</param>
        /// <param name="container">A container to open this layer in</param>
        /// <param name="progressHandler">Specifies the progressHandler to receive progress messages.  This value overrides the property on this LayerManager.</param>
        /// <returns>An ILayer</returns>
        public virtual ILayer OpenLayer(string fileName, bool inRam, ICollection <ILayer> container, IProgressHandler progressHandler)
        {
            // To Do: Add Customization that allows users to specify which plugins to use in priority order.

            // First check for the extension in the preferred plugins list

            string ext = Path.GetExtension(fileName);

            if (ext != null)
            {
                ILayer result;
                if (_preferredProviders.ContainsKey(ext))
                {
                    result = _preferredProviders[ext].OpenLayer(fileName, inRam, container, progressHandler);
                    if (result != null)
                    {
                        return(result);
                    }
                    // if we get here, we found the provider, but it did not succeed in opening the file.
                }

                // Then check the general list of developer specified providers... but not the directory providers

                foreach (ILayerProvider dp in _layerProviders)
                {
                    if (GetSupportedExtensions(dp.DialogReadFilter).Contains(ext))
                    {
                        // attempt to open with the fileName.
                        result = dp.OpenLayer(fileName, inRam, container, progressHandler);
                        if (result != null)
                        {
                            return(result);
                        }
                    }
                }
            }

            throw new ApplicationException(SymbologyMessageStrings.LayerManager_FileTypeNotSupported);
        }
Example #49
0
 /// <summary>
 /// This launches an open file dialog and attempts to load the specified file.
 /// </summary>
 /// <param name="progressHandler">Specifies the progressHandler to receive progress messages. This value overrides the property on this DataManager.</param>
 /// <returns>A Layer</returns>
 public virtual ILayer OpenLayer(IProgressHandler progressHandler)
 {
     throw new NotImplementedException();
 }
Example #50
0
        /// <summary>
        /// Creates a new raster with the specified cell size.  If the cell size
        /// is zero, this will default to the shorter of the width or height
        /// divided by 256.  If the cell size produces a raster that is greater
        /// than 8, 000 pixels in either dimension, it will be re-sized to
        /// create an 8, 000 length or width raster.
        /// </summary>
        /// <param name="fs">The featureset to convert to a raster.</param>
        /// <param name="extent">Force the raster to this specified extent.</param>
        /// <param name="cellSize">The double extent of the cell.</param>
        /// <param name="fieldName">The integer field index of the file.</param>
        /// <param name="outputFileName">The fileName of the raster to create.</param>
        /// <param name="driverCode">The optional GDAL driver code to use if using GDAL
        /// for a format that is not discernable from the file extension.  An empty string
        ///  is usually perfectly acceptable here.</param>
        /// <param name="options">For GDAL rasters, they can be created with optional parameters
        ///  passed in as a string array.  In most cases an empty string is perfectly acceptable.</param>
        /// <param name="progressHandler">An interface for handling the progress messages.</param>
        /// <returns>Generates a raster from the vectors.</returns>
        public static IRaster ToRaster(IFeatureSet fs, Extent extent, double cellSize, string fieldName,
                                       string outputFileName,
                                       string driverCode, string[] options, IProgressHandler progressHandler)
        {
            Extent env = extent;

            if (cellSize == 0)
            {
                if (env.Width < env.Height)
                {
                    cellSize = env.Width / 256;
                }
                else
                {
                    cellSize = env.Height / 256;
                }
            }
            int w = (int)Math.Ceiling(env.Width / cellSize);

            if (w > 8000)
            {
                w        = 8000;
                cellSize = env.Width / 8000;
            }
            int h = (int)Math.Ceiling(env.Height / cellSize);

            if (h > 8000)
            {
                h = 8000;
            }
            Bitmap   bmp = new Bitmap(w, h);
            Graphics g   = Graphics.FromImage(bmp);

            g.Clear(Color.Transparent);
            g.SmoothingMode     = SmoothingMode.None;
            g.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
            g.InterpolationMode = InterpolationMode.NearestNeighbor;
            Hashtable colorTable;
            MapArgs   args = new MapArgs(new Rectangle(0, 0, w, h), env, g);

            switch (fs.FeatureType)
            {
            case FeatureType.Polygon:
            {
                MapPolygonLayer mpl = new MapPolygonLayer(fs);
                PolygonScheme   ps  = new PolygonScheme();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    });
            }
            break;

            case FeatureType.Line:
            {
                MapLineLayer mpl = new MapLineLayer(fs);
                LineScheme   ps  = new LineScheme();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    });
            }
            break;

            default:
            {
                MapPointLayer mpl = new MapPointLayer(fs);
                PointScheme   ps  = new PointScheme();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    });
            }
            break;
            }
            Type tp = fieldName == "FID" ? typeof(int) : fs.DataTable.Columns[fieldName].DataType;

            // We will try to convert to double if it is a string
            if (tp == typeof(string))
            {
                tp = typeof(double);
            }
            InRamImageData image = new InRamImageData(bmp, env);
            ProgressMeter  pm    = new ProgressMeter(progressHandler, "Converting To Raster Cells", h);

            IRaster output;

            output        = Raster.Create(outputFileName, driverCode, w, h, 1, tp, options);
            output.Bounds = new RasterBounds(h, w, env);

            double dtMax       = Convert.ToDouble(fs.DataTable.Compute("Max(" + fieldName + ")", ""));
            double dtMin       = Convert.ToDouble(fs.DataTable.Compute("Min(" + fieldName + ")", ""));
            double noDataValue = output.NoDataValue;

            if (dtMin <= noDataValue && dtMax >= noDataValue)
            {
                if (dtMax != GetFieldValue(tp, "MaxValue"))
                {
                    output.NoDataValue = noDataValue;
                }
                else if (dtMin != GetFieldValue(tp, "MinValue"))
                {
                    output.NoDataValue = noDataValue;
                }
            }

            List <RcIndex> locations   = new List <RcIndex>();
            List <string>  failureList = new List <string>();

            for (int row = 0; row < h; row++)
            {
                for (int col = 0; col < w; col++)
                {
                    Color c = image.GetColor(row, col);
                    if (c.A == 0)
                    {
                        output.Value[row, col] = output.NoDataValue;
                    }
                    else
                    {
                        if (colorTable.ContainsKey(c) == false)
                        {
                            if (c.A < 125)
                            {
                                output.Value[row, col] = output.NoDataValue;
                                continue;
                            }

                            // Use a color matching distance to pick the closest member
                            object val = GetCellValue(w, h, row, col, image, c, colorTable, locations);

                            output.Value[row, col] = GetDouble(val, failureList);
                        }
                        else
                        {
                            output.Value[row, col] = GetDouble(colorTable[c], failureList);
                        }
                    }
                }
                pm.CurrentValue = row;
            }
            const int maxIterations = 5;
            int       iteration     = 0;

            while (locations.Count > 0)
            {
                List <RcIndex> newLocations = new List <RcIndex>();
                foreach (RcIndex location in locations)
                {
                    object val = GetCellValue(w, h, location.Row, location.Column, image,
                                              image.GetColor(location.Row, location.Column), colorTable, newLocations);
                    output.Value[location.Row, location.Column] = GetDouble(val, failureList);
                }
                locations = newLocations;
                iteration++;
                if (iteration > maxIterations)
                {
                    break;
                }
            }

            pm.Reset();
            return(output);
        }
Example #51
0
 /// <summary>
 /// Creates a new raster with the specified cell size.  If the cell size
 /// is zero, this will default to the shorter of the width or height
 /// divided by 256.  If the cell size produces a raster that is greater
 /// than 8, 000 pixels in either dimension, it will be re-sized to
 /// create an 8, 000 length or width raster.
 /// </summary>
 /// <param name="fs">The featureset to convert to a raster.</param>
 /// <param name="cellSize">The double extent of the cell.</param>
 /// <param name="fieldName">The integer field index of the file.</param>
 /// <param name="outputFileName">The fileName of the raster to create.</param>
 /// <param name="driverCode">The optional GDAL driver code to use if using GDAL
 /// for a format that is not discernable from the file extension.  An empty string
 ///  is usually perfectly acceptable here.</param>
 /// <param name="options">For GDAL rasters, they can be created with optional parameters
 ///  passed in as a string array.  In most cases an empty string is perfectly acceptable.</param>
 /// <param name="progressHandler">An interface for handling the progress messages.</param>
 /// <returns>Generates a raster from the vectors.</returns>
 public static IRaster ToRaster(IFeatureSet fs, double cellSize, string fieldName, string outputFileName,
                                string driverCode, string[] options, IProgressHandler progressHandler)
 {
     return(ToRaster(fs, fs.Extent, cellSize, fieldName, outputFileName, driverCode, options, progressHandler));
 }
Example #52
0
        /// <summary>
        /// Loads the shapes from the given file into the given shapefile.
        /// </summary>
        /// <param name="fileName">Name of the file whose shapes should get loaded.</param>
        /// <param name="progressHandler">ProgressHandler that shows the progress.</param>
        /// <param name="shapefile">Shapefile the shapes are loaded into.</param>
        /// <param name="featureType">FeatureType that should be inside the file.</param>
        /// <exception cref="ArgumentNullException">Throws an ArgumentNullException, if the shapefile is null.</exception>
        /// <exception cref="ArgumentException">Throws an ArgumentException, if the FeatureType is Line but the files doesn't contain lines or the FeatureType is Polygon and the file doesn't contain polygons.</exception>
        /// <exception cref="NotSupportedException">Throws a NotSupportedException, if a FeatureType other than Line or Polygon is passed.</exception>
        /// <exception cref="FileNotFoundException">Throws a FileNotFoundException, if the file whith the path from fileName doesn't exist.</exception>
        /// <exception cref="NullReferenceException">Throws a NullReferenceException, if the fileName is null.</exception>
        internal static void FillLines(string fileName, IProgressHandler progressHandler, Shapefile shapefile, FeatureType featureType)
        {
            // Check to ensure the fileName is not null
            if (fileName == null)
            {
                throw new NullReferenceException(DataStrings.ArgumentNull_S.Replace("%S", "fileName"));
            }
            if (shapefile == null)
            {
                throw new ArgumentNullException(nameof(shapefile));
            }

            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException(DataStrings.FileNotFound_S.Replace("%S", fileName));
            }

            if (featureType != FeatureType.Line && featureType != FeatureType.Polygon)
            {
                throw new NotSupportedException();
            }

            var header = shapefile.Header;

            // Check to ensure that the fileName is the correct shape type
            switch (featureType)
            {
            case FeatureType.Line:
                if (header.ShapeType != ShapeType.PolyLine &&
                    header.ShapeType != ShapeType.PolyLineM &&
                    header.ShapeType != ShapeType.PolyLineZ)
                {
                    throw new ArgumentException(DataStrings.FileNotLines_S.Replace("%S", fileName));
                }
                break;

            case FeatureType.Polygon:
                if (header.ShapeType != ShapeType.Polygon &&
                    header.ShapeType != ShapeType.PolygonM &&
                    header.ShapeType != ShapeType.PolygonZ)
                {
                    throw new ArgumentException(DataStrings.FileNotLines_S.Replace("%S", fileName));
                }
                break;
            }

            if (new FileInfo(fileName).Length == 100)
            {
                // the file is empty so we are done reading
                return;
            }

            // Reading the headers gives us an easier way to track the number of shapes and their overall length etc.
            var shapeHeaders = shapefile.ReadIndexFile(fileName);
            int numShapes    = shapeHeaders.Count;

            bool isM = false, isZ = false;

            switch (header.ShapeType)
            {
            case ShapeType.PolyLineM:
            case ShapeType.PolygonM:
                isM = true;
                break;

            case ShapeType.PolyLineZ:
            case ShapeType.PolygonZ:
                isZ = true;
                isM = true;
                break;
            }

            int totalPointsCount = 0;
            int totalPartsCount  = 0;
            var shapeIndices     = new List <ShapeRange>(numShapes);

            var progressMeter = new ProgressMeter(progressHandler, "Reading from " + Path.GetFileName(fileName))
            {
                StepPercent = 5
            };

            using (var reader = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 65536))
            {
                var boundsBytes = new byte[4 * 8];
                var bounds      = new double[4];
                for (int shp = 0; shp < numShapes; shp++)
                {
                    progressMeter.CurrentPercent = (int)(shp * 50.0 / numShapes);

                    // Read from the index file because some deleted records
                    // might still exist in the .shp file.
                    long offset = shapeHeaders[shp].ByteOffset;
                    reader.Seek(offset, SeekOrigin.Begin);

                    var shape = new ShapeRange(featureType, shapefile.CoordinateType)
                    {
                        RecordNumber  = reader.ReadInt32(Endian.BigEndian),
                        ContentLength = reader.ReadInt32(Endian.BigEndian),
                        ShapeType     = (ShapeType)reader.ReadInt32(),
                        StartIndex    = totalPointsCount
                    };
                    Debug.Assert(shape.RecordNumber == shp + 1);

                    if (shape.ShapeType != ShapeType.NullShape)
                    {
                        // Bounds
                        reader.Read(boundsBytes, 0, boundsBytes.Length);
                        Buffer.BlockCopy(boundsBytes, 0, bounds, 0, boundsBytes.Length);
                        shape.Extent.MinX = bounds[0];
                        shape.Extent.MinY = bounds[1];
                        shape.Extent.MaxX = bounds[2];
                        shape.Extent.MaxY = bounds[3];

                        // Num Parts
                        shape.NumParts   = reader.ReadInt32();
                        totalPartsCount += shape.NumParts;

                        // Num Points
                        shape.NumPoints   = reader.ReadInt32();
                        totalPointsCount += shape.NumPoints;
                    }

                    shapeIndices.Add(shape);
                }

                var vert    = new double[totalPointsCount * 2];
                var vertInd = 0;

                var parts    = new int[totalPartsCount];
                var partsInd = 0;

                double[] mArray = null, zArray = null;
                if (isM)
                {
                    mArray = new double[totalPointsCount];
                }
                int mArrayInd = 0;
                if (isZ)
                {
                    zArray = new double[totalPointsCount];
                }
                int zArrayInd = 0;

                int partsOffset = 0;
                for (int shp = 0; shp < numShapes; shp++)
                {
                    progressMeter.CurrentPercent = (int)(50 + shp * 50.0 / numShapes);

                    var shape = shapeIndices[shp];
                    if (shape.ShapeType == ShapeType.NullShape)
                    {
                        continue;
                    }
                    reader.Seek(shapeHeaders[shp].ByteOffset, SeekOrigin.Begin);
                    reader.Seek(3 * 4 + 32 + 2 * 4, SeekOrigin.Current); // Skip first bytes (Record Number, Content Length, Shapetype + BoundingBox + NumParts, NumPoints)

                    // Read parts
                    var partsBytes = reader.ReadBytes(4 * shape.NumParts); //Numparts * Integer(4) = existing Parts
                    Buffer.BlockCopy(partsBytes, 0, parts, partsInd, partsBytes.Length);
                    partsInd += 4 * shape.NumParts;

                    // Read points
                    var pointsBytes = reader.ReadBytes(8 * 2 * shape.NumPoints); //Numpoints * Point (X(8) + Y(8))
                    Buffer.BlockCopy(pointsBytes, 0, vert, vertInd, pointsBytes.Length);
                    vertInd += 8 * 2 * shape.NumPoints;

                    // Fill parts
                    shape.Parts.Capacity = shape.NumParts;
                    for (int part = 0; part < shape.NumParts; part++)
                    {
                        int endIndex   = shape.NumPoints + shape.StartIndex;
                        int startIndex = parts[partsOffset + part] + shape.StartIndex;
                        if (part < shape.NumParts - 1)
                        {
                            endIndex = parts[partsOffset + part + 1] + shape.StartIndex;
                        }
                        int count = endIndex - startIndex;
                        var partR = new PartRange(vert, shape.StartIndex, parts[partsOffset + part], featureType)
                        {
                            NumVertices = count
                        };
                        shape.Parts.Add(partR);
                    }
                    partsOffset += shape.NumParts;

                    // Fill M and Z arrays
                    switch (header.ShapeType)
                    {
                    case ShapeType.PolyLineM:
                    case ShapeType.PolygonM:
                        if (shape.ContentLength * 2 > 44 + 4 * shape.NumParts + 16 * shape.NumPoints)
                        {
                            var mExt = (IExtentM)shape.Extent;
                            mExt.MinM = reader.ReadDouble();
                            mExt.MaxM = reader.ReadDouble();

                            var mBytes = reader.ReadBytes(8 * shape.NumPoints);
                            Buffer.BlockCopy(mBytes, 0, mArray, mArrayInd, mBytes.Length);
                            mArrayInd += 8 * shape.NumPoints;
                        }
                        break;

                    case ShapeType.PolyLineZ:
                    case ShapeType.PolygonZ:
                        var zExt = (IExtentZ)shape.Extent;
                        zExt.MinZ = reader.ReadDouble();
                        zExt.MaxZ = reader.ReadDouble();

                        var zBytes = reader.ReadBytes(8 * shape.NumPoints);
                        Buffer.BlockCopy(zBytes, 0, zArray, zArrayInd, zBytes.Length);
                        zArrayInd += 8 * shape.NumPoints;


                        // These are listed as "optional" but there isn't a good indicator of how to determine if they were added.
                        // To handle the "optional" M values, check the contentLength for the feature.
                        // The content length does not include the 8-byte record header and is listed in 16-bit words.
                        if (shape.ContentLength * 2 > 60 + 4 * shape.NumParts + 24 * shape.NumPoints)
                        {
                            goto case ShapeType.PolyLineM;
                        }

                        break;
                    }
                }

                if (isM)
                {
                    shapefile.M = mArray;
                }
                if (isZ)
                {
                    shapefile.Z = zArray;
                }
                shapefile.ShapeIndices = shapeIndices;
                shapefile.Vertex       = vert;
            }

            progressMeter.Reset();
        }
Example #53
0
 protected override void XukInChild(XmlReader source, IProgressHandler handler)
 {
     //nothing new here
     base.XukInChild(source, handler);
 }
Example #54
0
        /// <summary>
        /// Creates a bitmap based on the specified RasterSymbolizer
        /// </summary>
        /// <param name="bitmap"> the bitmap to paint to</param>
        /// <param name="progressHandler">The progress handler</param>
        public void PaintShadingToBitmap(Bitmap bitmap, IProgressHandler progressHandler)
        {
            BitmapData bmpData;

            if (_hillshade == null)
            {
                return;
            }

            // Create a new Bitmap and use LockBits combined with Marshal.Copy to get an array of bytes to work with.

            Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

            try
            {
                bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            }
            catch (ArgumentException ex)
            {
                if (ex.ParamName == "format")
                {
                    throw new BitmapFormatException();
                }
                throw;
            }
            int numBytes = bmpData.Stride * bmpData.Height;

            byte[] rgbData = new byte[numBytes];
            Marshal.Copy(bmpData.Scan0, rgbData, 0, numBytes);

            float[][] hillshade = _hillshade;

            ProgressMeter pm = new ProgressMeter(progressHandler, SymbologyMessageStrings.DesktopRasterExt_PaintingHillshade, bitmap.Height);

            if (bitmap.Width * bitmap.Height < 100000)
            {
                pm.StepPercent = 50;
            }
            if (bitmap.Width * bitmap.Height < 500000)
            {
                pm.StepPercent = 10;
            }
            if (bitmap.Width * bitmap.Height < 1000000)
            {
                pm.StepPercent = 5;
            }
            for (int row = 0; row < bitmap.Height; row++)
            {
                for (int col = 0; col < bitmap.Width; col++)
                {
                    int  offset = row * bmpData.Stride + col * 4;
                    byte b      = rgbData[offset];
                    byte g      = rgbData[offset + 1];
                    byte r      = rgbData[offset + 2];

                    //  rgbData[offset + 3] = a; don't worry about alpha

                    int red   = Convert.ToInt32(r * hillshade[row][col]);
                    int green = Convert.ToInt32(g * hillshade[row][col]);
                    int blue  = Convert.ToInt32(b * hillshade[row][col]);
                    if (red > 255)
                    {
                        red = 255;
                    }
                    if (green > 255)
                    {
                        green = 255;
                    }
                    if (blue > 255)
                    {
                        blue = 255;
                    }
                    if (red < 0)
                    {
                        red = 0;
                    }
                    if (green < 0)
                    {
                        green = 0;
                    }
                    if (blue < 0)
                    {
                        blue = 0;
                    }
                    b = (byte)blue;
                    r = (byte)red;
                    g = (byte)green;

                    rgbData[offset]     = b;
                    rgbData[offset + 1] = g;
                    rgbData[offset + 2] = r;
                }
                pm.CurrentValue = row;
            }
            pm.Reset();
            // Copy the values back into the bitmap
            Marshal.Copy(rgbData, 0, bmpData.Scan0, numBytes);
            bitmap.UnlockBits(bmpData);

            return;
        }
Example #55
0
 /// <summary>
 /// Creates a new Layer, but this should be done from the derived classes
 /// </summary>
 /// <param name="container">The container this layer should be a member of</param>
 /// <param name="progressHandler">A progress handler for handling progress messages</param>
 protected Layer(ICollection<ILayer> container, IProgressHandler progressHandler)
 {
     _progressHandler = progressHandler;
     if (container != null) container.Add(this);
     Configure();
 }
Example #56
0
 protected override void XukOutChildren(XmlWriter destination, Uri baseUri, IProgressHandler handler)
 {
     //nothing new here
     base.XukOutChildren(destination, baseUri, handler);
 }
Example #57
0
 /// <summary>
 /// Attempts to call the open fileName method for any ILayerProvider plugin
 /// that matches the extension on the string.
 /// </summary>
 /// <param name="fileName">A String fileName to attempt to open.</param>
 /// <param name="inRam">A boolean value that if true will attempt to force a load of the data into memory.  This value overrides the property on this LayerManager.</param>
 /// <param name="container">A container to open this layer in</param>
 /// <param name="progressHandler">Specifies the progressHandler to receive progress messages.  This value overrides the property on this LayerManager.</param>
 /// <returns>An ILayer</returns>
 public virtual ILayer OpenLayer(string fileName, bool inRam, ICollection<ILayer> container, IProgressHandler progressHandler)
 {
     if (File.Exists(fileName) == false) return null;
     ILayerManager dm = LayerManager.DefaultLayerManager;
     return dm.OpenLayer(fileName, inRam, container, progressHandler);
 }
Example #58
0
        /// <summary>
        /// Not Implemented yet
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="featureType"></param>
        /// <param name="inRam"></param>
        /// <param name="container"></param>
        /// <param name="progressHandler"></param>
        /// <returns></returns>
        public IFeatureLayer CreateNew(string fileName, FeatureType featureType, bool inRam, ICollection <ILayer> container, IProgressHandler progressHandler)
        {
            ShapefileDataProvider dp = new ShapefileDataProvider();
            IFeatureSet           fs = dp.CreateNew(fileName, featureType, inRam, progressHandler);

            if (progressHandler == null)
            {
                progressHandler = LayerManager.DefaultLayerManager.ProgressHandler;
            }

            if (fs.FeatureType == FeatureType.Line)
            {
                return(new MapLineLayer(fs, container));
            }
            if (fs.FeatureType == FeatureType.Polygon)
            {
                return(new MapPolygonLayer(fs, container));
            }
            if (fs.FeatureType == FeatureType.Point || fs.FeatureType == FeatureType.MultiPoint)
            {
                return(new MapPointLayer(fs, container));
            }
            return(null);
        }
Example #59
0
 /// <summary>
 /// Creates a new instance of an attribute Table with no file reference
 /// </summary>
 public AttributeTable()
 {
     _deletedRows = new List<int>();
     _fileType = 0x03;
     _progressHandler = DataManager.DefaultDataManager.ProgressHandler;
     _progressMeter = new ProgressMeter(_progressHandler);
     _dataTable = new DataTable();
     _columns = new List<Field>();
 }
Example #60
0
        /// <summary>
        /// Opens a shapefile, but returns it as a FeatureLayer
        /// </summary>
        /// <param name="fileName">The string fileName</param>
        /// <param name="inRam">Boolean, if this is true it will attempt to open the entire layer in memory.</param>
        /// <param name="container">A container to hold this layer.</param>
        /// <param name="progressHandler">The progress handler that should receive status messages</param>
        /// <returns>An IFeatureLayer</returns>
        public ILayer OpenLayer(string fileName, bool inRam, ICollection <ILayer> container, IProgressHandler progressHandler)
        {
            ShapefileDataProvider dp = new ShapefileDataProvider();
            IFeatureSet           fs = dp.Open(fileName);

            if (fs != null)
            {
                if (fs.FeatureType == FeatureType.Line)
                {
                    return(new MapLineLayer(fs, container));
                }
                if (fs.FeatureType == FeatureType.Polygon)
                {
                    return(new MapPolygonLayer(fs, container));
                }
                if (fs.FeatureType == FeatureType.Point || fs.FeatureType == FeatureType.MultiPoint)
                {
                    return(new MapPointLayer(fs, container));
                }
            }
            return(null);
        }