예제 #1
0
 public void Dispose()
 {
     if (!fsWorldCountries.IsDisposed)
     {
         fsWorldCountries.Close();
         fsWorldCountries.Dispose();
     }
 }
예제 #2
0
 public void Clear()
 {
     if (_buffer != null)
     {
         _buffer.Close();
         _buffer = null;
     }
 }
예제 #3
0
        /// <summary>
        /// Finds the average slope in the given polygons.
        /// </summary>
        /// <param name="ras">The dem Raster(Grid file).</param>
        /// <param name="zFactor">The scaler factor</param>
        /// <param name="poly">The flow poly shapefile path.</param>
        /// <param name="output">The resulting DEM of slopes</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        public bool Execute(
            IRaster ras,
            double zFactor,
            IFeatureSet poly,
            IFeatureSet output,
            ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (ras == null || poly == null || output == null)
            {
                return(false);
            }

            output.FeatureType = poly.FeatureType;
            foreach (IFeature f in poly.Features)
            {
                output.Features.Add(f);
            }

            output.DataTable.Columns.Add("FID", typeof(int));
            output.DataTable.Columns.Add(TextStrings.AveSlope, typeof(Double));

            IRaster slopeGrid = new Raster {
                DataType = ras.DataType, Bounds = ras.Bounds
            };

            // FeatureSet polyShape = new FeatureSet();
            int previous = 0;

            if (Slope(ref ras, zFactor, false, ref slopeGrid, cancelProgressHandler) == false)
            {
                return(false);
            }

            int shapeCount = output.Features.Count;

            int[]    areaCount = new int[shapeCount];
            double[] areaTotal = new double[shapeCount];
            double[] areaAve   = new double[shapeCount];
            double   dxHalf    = slopeGrid.CellWidth / 2;
            double   dyHalf    = slopeGrid.CellHeight / 2;

            // check whether those two envelope are intersect
            if (ras.Extent.Intersects(output.Extent) == false)
            {
                return(false);
            }

            RcIndex start = slopeGrid.ProjToCell(output.Extent.MinX, output.Extent.MaxY);
            RcIndex stop  = slopeGrid.ProjToCell(output.Extent.MaxX, output.Extent.MinY);

            int rowStart = start.Row;
            int colStart = start.Column;
            int rowStop  = stop.Row;
            int colStop  = stop.Column;

            for (int row = rowStart - 1; row < rowStop + 1; row++)
            {
                int current = Convert.ToInt32((row - rowStart + 1) * 100.0 / (rowStop + 1 - rowStart + 1));

                // only update when increment in percentage
                if (current > previous + 5)
                {
                    cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted);
                    previous = current;
                }

                for (int col = colStart - 1; col < colStop + 1; col++)
                {
                    Coordinate cent  = slopeGrid.CellToProj(row, col);
                    double     xCent = cent.X;
                    double     yCent = cent.Y;
                    for (int shpindx = 0; shpindx < output.Features.Count; shpindx++)
                    {
                        IFeature tempFeat = output.Features[shpindx];
                        Point    pt1      = new Point(xCent, yCent);
                        Point    pt2      = new Point(xCent - dxHalf, yCent - dyHalf);
                        Point    pt3      = new Point(xCent + dxHalf, yCent - dyHalf);
                        Point    pt4      = new Point(xCent + dxHalf, yCent + dyHalf);
                        Point    pt5      = new Point(xCent - dxHalf, yCent + dyHalf);
                        if ((((!tempFeat.Covers(pt1) && !tempFeat.Covers(pt2)) && !tempFeat.Covers(pt3)) &&
                             !tempFeat.Covers(pt4)) && !tempFeat.Covers(pt5))
                        {
                            continue;
                        }

                        areaCount[shpindx]++;
                        areaTotal[shpindx] += slopeGrid.Value[row, col] / 100;

                        if (cancelProgressHandler.Cancel)
                        {
                            return(false);
                        }
                    }
                }
            }

            for (int shpindx = 0; shpindx < output.Features.Count; shpindx++)
            {
                if (areaCount[shpindx] == 0)
                {
                    areaAve[shpindx] = 0;
                }
                else
                {
                    areaAve[shpindx] = areaTotal[shpindx] / areaCount[shpindx];
                }

                output.Features[shpindx].DataRow["FID"] = shpindx;
                output.Features[shpindx].DataRow[TextStrings.AveSlope] = areaAve[shpindx];
            }

            poly.Close();
            slopeGrid.Close();
            output.SaveAs(output.Filename, true);
            return(true);
        }
예제 #4
0
        /// <summary>
        /// Finds the average slope in the given polygons.
        /// </summary>
        /// <param name="ras">The dem Raster(Grid file).</param>
        /// <param name="zFactor">The scaler factor</param>
        /// <param name="poly">The flow poly shapefile path.</param>
        /// <param name="output">The resulting DEM of slopes</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        public bool Execute(
            IRaster ras,
            double zFactor,
            IFeatureSet poly,
            IFeatureSet output,
            ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (ras == null || poly == null || output == null)
            {
                return false;
            }

            output.FeatureType = poly.FeatureType;
            foreach (IFeature f in poly.Features)
            {
                output.Features.Add(f);
            }

            output.DataTable.Columns.Add("FID", typeof(int));
            output.DataTable.Columns.Add(TextStrings.AveSlope, typeof(Double));

            IRaster slopeGrid = new Raster { DataType = ras.DataType, Bounds = ras.Bounds };

            // FeatureSet polyShape = new FeatureSet();
            int previous = 0;

            if (Slope(ref ras, zFactor, false, ref slopeGrid, cancelProgressHandler) == false)
            {
                return false;
            }

            int shapeCount = output.Features.Count;
            int[] areaCount = new int[shapeCount];
            double[] areaTotal = new double[shapeCount];
            double[] areaAve = new double[shapeCount];
            double dxHalf = slopeGrid.CellWidth / 2;
            double dyHalf = slopeGrid.CellHeight / 2;

            // check whether those two envelope are intersect
            if (ras.Extent.Intersects(output.Extent) == false)
            {
                return false;
            }

            RcIndex start = slopeGrid.ProjToCell(output.Extent.MinX, output.Extent.MaxY);
            RcIndex stop = slopeGrid.ProjToCell(output.Extent.MaxX, output.Extent.MinY);

            int rowStart = start.Row;
            int colStart = start.Column;
            int rowStop = stop.Row;
            int colStop = stop.Column;
            for (int row = rowStart - 1; row < rowStop + 1; row++)
            {
                int current = Convert.ToInt32((row - rowStart + 1) * 100.0 / (rowStop + 1 - rowStart + 1));

                // only update when increment in percentage
                if (current > previous + 5)
                {
                    cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted);
                    previous = current;
                }

                for (int col = colStart - 1; col < colStop + 1; col++)
                {
                    Coordinate cent = slopeGrid.CellToProj(row, col);
                    double xCent = cent.X;
                    double yCent = cent.Y;
                    for (int shpindx = 0; shpindx < output.Features.Count; shpindx++)
                    {
                        IFeature tempFeat = output.Features[shpindx];
                        Point pt1 = new Point(xCent, yCent);
                        Point pt2 = new Point(xCent - dxHalf, yCent - dyHalf);
                        Point pt3 = new Point(xCent + dxHalf, yCent - dyHalf);
                        Point pt4 = new Point(xCent + dxHalf, yCent + dyHalf);
                        Point pt5 = new Point(xCent - dxHalf, yCent + dyHalf);
                        if ((((!tempFeat.Covers(pt1) && !tempFeat.Covers(pt2)) && !tempFeat.Covers(pt3))
                             && !tempFeat.Covers(pt4)) && !tempFeat.Covers(pt5))
                        {
                            continue;
                        }

                        areaCount[shpindx]++;
                        areaTotal[shpindx] += slopeGrid.Value[row, col] / 100;

                        if (cancelProgressHandler.Cancel)
                        {
                            return false;
                        }
                    }
                }
            }

            for (int shpindx = 0; shpindx < output.Features.Count; shpindx++)
            {
                if (areaCount[shpindx] == 0)
                {
                    areaAve[shpindx] = 0;
                }
                else
                {
                    areaAve[shpindx] = areaTotal[shpindx] / areaCount[shpindx];
                }

                output.Features[shpindx].DataRow["FID"] = shpindx;
                output.Features[shpindx].DataRow[TextStrings.AveSlope] = areaAve[shpindx];
            }

            poly.Close();
            slopeGrid.Close();
            output.SaveAs(output.Filename, true);
            return true;
        }
        /// <summary>
        /// Finds the average slope in the given polygons.
        /// </summary>
        /// <param name="gridIn">The Polygon Raster(Grid file).</param>
        /// <param name="polyOut">The Polygon shapefile path.</param>
        /// <param name="progress">The progress handler.</param>
        public bool Execute(IRaster gridIn, IFeatureSet polyOut, ICancelProgressHandler cancelProgressHandler)
        {
            //Validates the input and output data
            if (gridIn == null || polyOut == null)
            {
                return false;
            }
            int maxX, maxY;
            int current = 0;
            int previous = 0;
            double noData, currVal, currTrack;
            string strTrackPath;
            IRaster gridTrack = new Raster();


            maxX = gridIn.NumRows - 1;
            maxY = gridIn.NumColumns - 1;
            noData = gridIn.NoDataValue;

            //strTrackPath = System.IO.Path.GetDirectoryName(strInRast) + "\\" + System.IO.Path.GetFileNameWithoutExtension(strInRast) + "_track.bgd";
            gridTrack = Raster.Create("gridTrack.bgd", "", gridIn.NumColumns, gridIn.NumRows, 1, gridIn.DataType, new string[] { "" });
            //gridTrack.CreateNew("gridTrack", "", gridIn.NumColumns, gridIn.NumRows, 1, gridIn.DataType, new string[] { "" });
            gridTrack.Bounds = gridIn.Bounds;
            gridTrack.NoDataValue = gridIn.NoDataValue;

            polyOut.DataTable.Columns.Add("Value", typeof(int));
            polyOut.DataTable.Columns.Add("Zone", typeof(string));
            polyOut.DataTable.Columns.Add("Area", typeof(double));
            polyOut.DataTable.Columns.Add("COMID", typeof(string));
            polyOut.DataTable.Columns.Add("AveSlope", typeof(double));

            for (int i = 0; i <= maxX; i++)
            {

                current = Convert.ToInt32(i * 100 / maxX);
                //only update when increment in percentage
                if (current > previous+5)
                {
                    cancelProgressHandler.Progress("", current, current.ToString() + "% progress completed");
                    previous = current;
                }
                    

                for (int j = 0; j <= maxY; j++)
                {
                    if (i > 0 && j > 0)
                    {
                        currVal = Convert.ToInt16(gridIn.Value[i, j]);
                        currTrack = Convert.ToInt16(gridTrack.Value[i, j]);
                        if (currVal == gridIn.NoDataValue)
                        {
                            gridTrack.Value[i, j] = 1;

                            if (cancelProgressHandler.Cancel == true)
                                return false;
                        }
                        else
                        {
                            if (currTrack == 1)
                            {
                            }
                            else
                            {
                                formPolyFromCell(gridIn, gridTrack, i, j, polyOut, cancelProgressHandler);

                                if (cancelProgressHandler.Cancel == true)
                                    return false;
                            }
                        }
                    }
                    else
                    {
                        gridTrack.Value[i, j] = gridIn.NoDataValue;
                    }

                    

                }
            }
            gridIn.Close();
            gridTrack.Close();
            polyOut.SaveAs(polyOut.Filename, true);
            polyOut.Close();
            return true;

        }
예제 #6
0
        private void AddLayerAndGetAtt(string strPath)
        {
            try
            {
                mainMap.ProjectionModeReproject = ActionMode.Never; mainMap.ProjectionModeDefine = ActionMode.Never;
                mainMap.Layers.Clear();
                mainMap.Layers.Add(strPath);
                IFeatureSet fs      = FeatureSet.Open(strPath);
                List <int>  lsCol   = new List <int>();
                List <int>  lsRow   = new List <int>();
                int         icol    = -1;
                int         irow    = -1;
                bool        colname = false;
                bool        rowname = false;
                for (int i = 0; i < fs.DataTable.Columns.Count; i++)
                {
                    if (fs.DataTable.Columns[i].ToString() == "ROW")
                    {
                        irow    = i;
                        rowname = true;
                    }
                    else if (fs.DataTable.Columns[i].ToString().ToLower() == "row")
                    {
                        irow = i;
                    }

                    if (fs.DataTable.Columns[i].ToString() == "COL")
                    {
                        icol    = i;
                        colname = true;
                    }
                    else if (fs.DataTable.Columns[i].ToString().ToLower() == "col" || fs.DataTable.Columns[i].ToString().ToLower() == "column")
                    {
                        icol = i;
                    }
                }

                if (icol >= 0 && irow >= 0)
                {
                    try
                    {
                        foreach (DataRow dr in fs.DataTable.Rows)
                        {
                            lsCol.Add(Convert.ToInt32(Convert.ToDouble(dr[icol].ToString())));
                            lsRow.Add(Convert.ToInt32(Convert.ToDouble(dr[irow].ToString())));
                        }
                    }
                    catch
                    {
                        MessageBox.Show("Column/Row value are invalid.");
                        fs.Close();
                        return;
                    }
                    _shapeCol = lsCol.Max();
                    _shapeRow = lsRow.Max();
                }
                else
                {
                    txtShapefile.Text = "";
                    MessageBox.Show("This shapefile does not have the required column and row variables.");
                }

                if (colname == false || rowname == false)
                {
                    fs.DataTable.Columns[icol].ColumnName = "COL";
                    fs.DataTable.Columns[irow].ColumnName = "ROW";
                    fs.SaveAs(strPath, true);
                }
                fs.Close();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
            }
        }
예제 #7
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            FireBirdHelperBase fb          = new ESILFireBirdHelper();
            string             commandText = string.Empty;

            _columns = int.Parse(nudColumns.Value.ToString());
            _rrows   = int.Parse(nudRows.Value.ToString());
            try
            {
                if (cboGridType.SelectedIndex == 0)
                {
                    _shapeFileName = lblShapeFileName.Text;
                }
                else
                {
                    _gridType = 0;
                    try
                    {
                        _columns         = int.Parse(nudColumns.Value.ToString());
                        _rrows           = int.Parse(nudRows.Value.ToString());
                        _colPerLongitude = int.Parse(nudColumnsPerLongitude.Value.ToString());
                        _rowPerLatitude  = int.Parse(nudRowsPerLatitude.Value.ToString());
                        _minLongitude    = System.Convert.ToDouble(txtMinimumLongitude.Text);
                        _minLatitude     = System.Convert.ToDouble(txtMinimumLatitude.Text);
                    }
                    catch
                    {
                        MessageBox.Show("Input data was not in a correct format.");
                        return;
                    }
                }
                if (IsEditor)
                {
                    commandText = string.Format("select Ttype from GridDefinitions where GridDefinitionID=" + _gridID + "");
                    int type = Convert.ToInt32(fb.ExecuteScalar(CommonClass.Connection, new CommandType(), commandText));

                    switch (_gridType)
                    {
                    case 1:
                        if (_shapeFilePath == string.Empty)
                        {
                            commandText = string.Format("Update GridDefinitions set GridDefinitionName='{0}'WHERE GridDefinitionID={1}", txtGridID.Text, _gridID);
                            fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                            this.DialogResult = DialogResult.OK; return;
                        }
                        if (type == 1)
                        {
                            commandText = string.Format("Update GridDefinitions set GridDefinitionName='{0}',COLUMNS={1},RROWS={2},TTYPE={3} WHERE GridDefinitionID={4}", txtGridID.Text, _shapeCol, _shapeRow, _gridType, _gridID);
                            fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                            if (File.Exists(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.ManageSetup.SetupName + "\\" + _shapeFileName + ".shp"))
                            {
                                RenameorOverride ro = new RenameorOverride();
                                DialogResult     dr = ro.ShowDialog();
                                if (dr == DialogResult.Cancel)
                                {
                                    return;
                                }
                                else
                                {
                                    if (dr == DialogResult.OK)
                                    {
                                        Renamefile frm = new Renamefile();
                                        frm.newfileName = _shapeFileName;
                                        frm.manage      = "GridDefinition";
                                        DialogResult dresult = frm.ShowDialog();
                                        if (dresult == DialogResult.OK)
                                        {
                                            _shapeFileName = frm.newfileName;
                                        }
                                        else
                                        {
                                            return;
                                        }
                                    }
                                    commandText = string.Format("Update ShapefileGriddefinitiondetails set shapefilename='{0}' where GridDefinitionID={1}", _shapeFileName, _gridID);
                                    fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                                }
                            }
                        }
                        else
                        {
                            DialogResult rtn = MessageBox.Show("Replace the 'Regular Grid' with 'Shapefile'?", "", MessageBoxButtons.YesNo);
                            if (rtn == DialogResult.Yes)
                            {
                                if (File.Exists(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.ManageSetup.SetupName + "\\" + _shapeFileName + ".shp"))
                                {
                                    RenameorOverride ro = new RenameorOverride();
                                    DialogResult     dr = ro.ShowDialog();
                                    if (dr == DialogResult.Cancel)
                                    {
                                        return;
                                    }
                                    else
                                    {
                                        if (dr == DialogResult.OK)
                                        {
                                            Renamefile frm = new Renamefile();
                                            frm.newfileName = _shapeFileName;
                                            frm.manage      = "GridDefinition";
                                            DialogResult dresult = frm.ShowDialog();
                                            if (dresult == DialogResult.OK)
                                            {
                                                _shapeFileName = frm.newfileName;
                                            }
                                            else
                                            {
                                                return;
                                            }
                                        }
                                        commandText = string.Format("insert into ShapeFileGridDefinitionDetails (GridDefinitionID,ShapeFileName) values ({0},'{1}')", _gridID, _shapeFileName);
                                        fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                                    }
                                }
                                commandText = string.Format("Update GridDefinitions set GridDefinitionName='{0}',COLUMNS={1},RROWS={2},TTYPE={3} WHERE GridDefinitionID={4}", txtGridID.Text, _shapeCol, _shapeRow, _gridType, _gridID);
                                fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                                commandText = "delete From RegularGridDefinitionDetails where GridDefinitionID=" + _gridID + "";
                                fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                            }
                            else
                            {
                                return;
                            }
                        }

                        IFeatureSet fs = FeatureSet.Open(_shapeFilePath);
                        try
                        {
                            if (fs.DataTable.Columns["ROW"].DataType == typeof(System.String) || fs.DataTable.Columns["COL"].DataType == typeof(System.String))
                            {
                                for (int iDt = 0; iDt < fs.DataTable.Rows.Count; iDt++)
                                {
                                    int r = (int)Convert.ToDouble(fs.DataTable.Rows[iDt]["ROW"].ToString());
                                    int c = (int)Convert.ToDouble(fs.DataTable.Rows[iDt]["COL"].ToString());
                                    fs.DataTable.Rows[iDt]["ROW"] = r;
                                    fs.DataTable.Rows[iDt]["COL"] = c;
                                }
                            }
                            fs.SaveAs(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.ManageSetup.SetupName + "\\" + _shapeFileName + ".shp", true);
                        }
                        finally
                        {
                            fs.Close();
                        }
                        break;

                    case 0:
                        if (Math.Abs(_minLongitude) > 180 || Math.Abs(_minLatitude) > 90)
                        {
                            MessageBox.Show("Longitude must be less than 180 degrees and latitude less than 90 degrees. Please check the longitude and latitude values."); return;
                        }
                        if (type == 0)
                        {
                            commandText = string.Format("Update GridDefinitions set GridDefinitionName='{0}',COLUMNS={1},RROWS={2},TTYPE={3} WHERE GridDefinitionID={4}", txtGridID.Text, _columns, _rrows, _gridType, _gridID);
                            fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                            commandText = string.Format("Update RegularGriddefinitionDetails set minimumlatitude={0},minimumlongitude={1},columnsperlongitude={2},rowsperlatitude={3} where GridDefinitionID={4}", _minLatitude, _minLongitude, _colPerLongitude, _rowPerLatitude, _gridID);
                            fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                        }
                        else
                        {
                            DialogResult rtn = MessageBox.Show("Replace the 'Shapefile' with 'Regular Grid'?", "", MessageBoxButtons.YesNo);
                            if (rtn == DialogResult.Yes)
                            {
                                commandText = string.Format("Update GridDefinitions set GridDefinitionName='{0}',COLUMNS={1},RROWS={2},TTYPE={3} WHERE GridDefinitionID={4}", txtGridID.Text, _columns, _rrows, _gridType, _gridID);
                                fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                                commandText = "delete From ShapefileGriddefinitiondetails where GridDefinitionID=" + _gridID + "";
                                fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                                commandText = string.Format("insert into RegularGriddefinitionDetails (GridDefinitionID,MinimumLatitude,MinimumLongitude,ColumnsPerLongitude,RowsPerLatitude,ShapeFileName) values ({0},{1},{2},{3},{4},'{5}')", _gridID, _minLatitude, _minLongitude, _colPerLongitude, _rowPerLatitude, txtGridID.Text);
                                fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                            }
                            else
                            {
                                return;
                            }
                        }
                        fs = getFeatureSetFromRegularGrid(_columns, _rrows, _minLatitude, _minLongitude, _colPerLongitude, _rowPerLatitude);
                        try
                        {
                            fs.SaveAs(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.ManageSetup.SetupName + "\\" + txtGridID.Text + ".shp", true);
                        }
                        finally
                        {
                            fs.Close();
                        }
                        break;
                    }
                    if (!chkBoxCreatePercentage.Checked)
                    {
                        WaitShow("Updating the grid definition...");
                        commandText = string.Format("delete from GridDefinitionPercentageEntries where PercentageID in ( select PercentageID  from GridDefinitionPercentages where SourceGridDefinitionID={0} or TargetGridDefinitionID={0})", _gridID);
                        fb.ExecuteNonQuery(CommonClass.Connection, CommandType.Text, commandText);
                        commandText = string.Format("delete from GridDefinitionPercentages where SourceGridDefinitionID={0} or TargetGridDefinitionID={0}", _gridID);
                        fb.ExecuteNonQuery(CommonClass.Connection, CommandType.Text, commandText);
                        this.DialogResult = DialogResult.OK;
                        WaitClose();
                        return;
                    }
                }

                else
                {
                    commandText = "select GridDefinitionID from GridDefinitions where GridDefinitionName='" + txtGridID.Text + "' and SetupID=" + CommonClass.ManageSetup.SetupID;
                    object obj = fb.ExecuteScalar(CommonClass.Connection, new CommandType(), commandText);
                    if (obj != null)
                    {
                        MessageBox.Show("This grid definition name is already in use. Please enter a different name.");
                        return;
                    }
                    commandText = string.Format("select max(GRIDDEFINITIONID) from GRIDDEFINITIONS");
                    _gridID     = Convert.ToInt32(fb.ExecuteScalar(CommonClass.Connection, new CommandType(), commandText)) + 1;

                    switch (_gridType)
                    {
                    case 1:
                        if (File.Exists(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.ManageSetup.SetupName + "\\" + _shapeFileName + ".shp"))
                        {
                            Renamefile frm = new Renamefile();
                            frm.newfileName = _shapeFileName;
                            frm.manage      = "GridDefinition";
                            DialogResult dr = frm.ShowDialog();
                            if (dr == DialogResult.OK)
                            {
                                _shapeFileName = frm.newfileName;
                            }
                            else
                            {
                                return;
                            }
                        }

                        commandText = string.Format("INSERT INTO GRIDDEFINITIONS (GridDefinitionID,SetUpID,GridDefinitionName,Columns,Rrows,Ttype,DefaultType) VALUES(" + _gridID + ",{0},'{1}',{2},{3},{4},{5})", CommonClass.ManageSetup.SetupID, txtGridID.Text, _shapeCol, _shapeRow, _gridType, 0);
                        fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                        commandText = string.Format("INSERT INTO SHAPEFILEGRIDDEFINITIONDETAILS (GridDefinitionID,ShapeFileName) VALUES(" + _gridID + ",'{0}')", _shapeFileName);
                        fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);
                        CommonClass.DeleteShapeFileName(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.ManageSetup.SetupName + "\\" + _shapeFileName + ".shp");
                        IFeatureSet fs = FeatureSet.Open(_shapeFilePath);
                        try
                        {
                            if (fs.DataTable.Columns["ROW"].DataType == typeof(System.String) || fs.DataTable.Columns["COL"].DataType == typeof(System.String))
                            {
                                for (int iDt = 0; iDt < fs.DataTable.Rows.Count; iDt++)
                                {
                                    int r = (int)Convert.ToDouble(fs.DataTable.Rows[iDt]["ROW"].ToString());
                                    int c = (int)Convert.ToDouble(fs.DataTable.Rows[iDt]["COL"].ToString());
                                    fs.DataTable.Rows[iDt]["ROW"] = r;
                                    fs.DataTable.Rows[iDt]["COL"] = c;
                                }
                            }
                            fs.SaveAs(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.ManageSetup.SetupName + "\\" + _shapeFileName + ".shp", true);
                        }
                        finally
                        {
                            fs.Close();
                        }
                        break;

                    case 0:
                        DialogResult rtn = MessageBox.Show("Save this grid?", "", MessageBoxButtons.YesNo);
                        if (rtn == DialogResult.No)
                        {
                            this.DialogResult = DialogResult.Cancel; return;
                        }
                        else
                        {
                            commandText = string.Format("INSERT INTO GRIDDEFINITIONS (GridDefinitionID,SetUpID,GridDefinitionName,Columns,Rrows,Ttype,DefaultType) VALUES(" + _gridID + ",{0},'{1}',{2},{3},{4},{5})", CommonClass.ManageSetup.SetupID, txtGridID.Text, _columns, _rrows, _gridType, 0);
                            fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);

                            if (Math.Abs(_minLongitude) > 180 || Math.Abs(_minLatitude) > 90)
                            {
                                MessageBox.Show("Please input valid longitude and latitude values."); return;
                            }
                            commandText = string.Format("INSERT INTO RegularGridDefinitionDetails (GridDefinitionID,MinimumLatitude,MinimumLongitude,ColumnsPerLongitude,RowsPerLatitude,ShapeFileName)  VALUES ({0},{1},{2},{3},{4},'{5}')", _gridID, txtMinimumLatitude.Text, txtMinimumLongitude.Text, nudColumnsPerLongitude.Value, nudRowsPerLatitude.Value, txtGridID.Text);
                            fb.ExecuteNonQuery(CommonClass.Connection, new CommandType(), commandText);

                            fs = getFeatureSetFromRegularGrid(_columns, _rrows, _minLatitude, _minLongitude, _colPerLongitude, _rowPerLatitude);
                            CommonClass.DeleteShapeFileName(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.ManageSetup.SetupName + "\\" + txtGridID.Text + ".shp");

                            try
                            {
                                fs.SaveAs(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.ManageSetup.SetupName + "\\" + txtGridID.Text + ".shp", true);
                            }
                            finally
                            {
                                fs.Close();
                            }
                        }
                        break;
                    }
                    if (!chkBoxCreatePercentage.Checked)
                    {
                        this.DialogResult = DialogResult.OK;
                        return;
                    }
                }
                lblprogress.Visible = true;
                lblprogress.Refresh();
                progressBar1.Visible = true;
                progressBar1.Refresh();
                BenMAPGrid addBenMAPGrid = Grid.GridCommon.getBenMAPGridFromID(_gridID);
                try
                {
                    commandText = "select a.GridDefinitionID,SetupID,GridDefinitionName,Columns,RRows,TType,b.ShapeFileName from GridDefinitions a,ShapeFileGridDefinitionDetails b " +
                                  " where a.GridDefinitionID=b.GridDefinitionID and a.TType=1  and a.SetupID=" + addBenMAPGrid.SetupID +
                                  " union " +
                                  " select a.GridDefinitionID,SetupID,GridDefinitionName,Columns,RRows,TType,b.ShapeFileName from GridDefinitions a,RegularGridDefinitionDetails b " +
                                  " where a.GridDefinitionID=b.GridDefinitionID and a.TType=0  and a.SetupID=" + addBenMAPGrid.SetupID;
                    fb = new ESIL.DBUtility.ESILFireBirdHelper();
                    System.Data.DataSet ds = fb.ExecuteDataset(CommonClass.Connection, CommandType.Text, commandText);
                    commandText = string.Format("delete from GridDefinitionPercentageEntries where PercentageID in ( select PercentageID  from GridDefinitionPercentages where SourceGridDefinitionID={0} or TargetGridDefinitionID={0})", addBenMAPGrid.GridDefinitionID);
                    fb.ExecuteNonQuery(CommonClass.Connection, CommandType.Text, commandText);
                    commandText = string.Format("delete from GridDefinitionPercentages where SourceGridDefinitionID={0} or TargetGridDefinitionID={0}", addBenMAPGrid.GridDefinitionID);
                    fb.ExecuteNonQuery(CommonClass.Connection, CommandType.Text, commandText);
                    string AppPath = Application.StartupPath;
                    if (ds.Tables[0].Rows.Count == 1)
                    {
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    }
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        int gridDefinitionID = Convert.ToInt32(dr["GridDefinitionID"]);
                        if (gridDefinitionID == addBenMAPGrid.GridDefinitionID)
                        {
                            continue;
                        }



                        int bigGridID, smallGridID;



                        bigGridID   = gridDefinitionID;
                        smallGridID = addBenMAPGrid.GridDefinitionID;
                        AsyncgetRelationshipFromBenMAPGridPercentage dlgt = new AsyncgetRelationshipFromBenMAPGridPercentage(getRelationshipFromBenMAPGridPercentage);
                        lstAsyns.Add(bigGridID + "," + smallGridID);
                        lstAsyns.Add(smallGridID + "," + bigGridID);
                        iAsyns++; iAsyns++;
                        IAsyncResult ar = dlgt.BeginInvoke(bigGridID, smallGridID, new AsyncCallback(outPut), dlgt);


                        IAsyncResult ar2 = dlgt.BeginInvoke(smallGridID, bigGridID, new AsyncCallback(outPut), dlgt);
                    }
                    progressBar1.Step    = 1;
                    progressBar1.Minimum = 1;
                    progressBar1.Maximum = iAsyns + 1;
                    this.Enabled         = false;
                }

                catch (Exception ex)
                {
                    Logger.LogError(ex);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
            }
        }
예제 #8
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet fs_source = null;
            IFeatureSet fs_target = null;

            if (SourceFeatureLayer != null)
            {
                fs_source = SourceFeatureLayer.DataSet as IFeatureSet;
            }
            else if (TypeConverterEx.IsNotNull(SourceFeatureFile))
            {
                fs_source = FeatureSet.Open(SourceFeatureFile);
            }

            if (TargetFeatureLayer != null)
            {
                fs_target = TargetFeatureLayer.DataSet as IFeatureSet;
            }
            else if (TypeConverterEx.IsNotNull(TargetFeatureFile))
            {
                fs_target = FeatureSet.Open(TargetFeatureFile);
            }

            if (fs_source == null || fs_target == null)
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "Failed. The inputs are invalid.");
                return(false);
            }

            CSVFileStream csv     = new CSVFileStream(DataFileName);
            var           ts_data = csv.Load <double>();

            cancelProgressHandler.Progress("Package_Tool", 1, "Time series at known sites loaded");
            int    nsource_sites = fs_source.DataTable.Rows.Count;
            int    ntar_sites    = fs_target.DataTable.Rows.Count;
            int    nstep         = ts_data.Size[0];
            int    nsite_data    = ts_data.Size[1];
            int    progress      = 0;
            int    count         = 1;
            double sumOfDis      = 0;
            double sumOfVa       = 0;

            if (nsite_data != nsource_sites)
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "the number of sites in the data file dose not match to that in the source feature file");
                return(false);
            }
            else
            {
                if (Neighbors > nsource_sites)
                {
                    Neighbors = nsource_sites;
                }
                var known_sites      = new Site[nsource_sites];
                DataCube <float> mat = new DataCube <float>(1, nstep, ntar_sites);
                mat.DateTimes      = new DateTime[nstep];
                mat.Name           = OutputDataCube;
                mat.TimeBrowsable  = true;
                mat.AllowTableEdit = false;
                for (int i = 0; i < nsource_sites; i++)
                {
                    var cor = fs_source.Features[i].Geometry.Coordinate;
                    known_sites[i] = new Site()
                    {
                        LocalX = cor.X,
                        LocalY = cor.Y,
                        ID     = i
                    };
                }
                for (int i = 0; i < ntar_sites; i++)
                {
                    var cor        = fs_target.Features[i].Geometry.Coordinate;
                    var site_intep = new Site()
                    {
                        LocalX = cor.X,
                        LocalY = cor.Y,
                        ID     = i
                    };
                    var neighborSites = FindNeareastSites(Neighbors, known_sites, site_intep);
                    for (int j = 0; j < nstep; j++)
                    {
                        sumOfDis = 0;
                        sumOfVa  = 0;
                        foreach (var nsite in neighborSites)
                        {
                            var vv = ts_data.GetValue(j, nsite.ID);
                            if (vv < MaximumValue)
                            {
                                double temp = 1 / System.Math.Pow(nsite.Distance, Power);
                                sumOfVa  += vv * temp;
                                sumOfDis += temp;
                            }
                        }
                        if (sumOfDis != 0)
                        {
                            mat[0, j, i] = (float)(sumOfVa / sumOfDis);
                            if (!AllowNegative && mat[0, j, i] < 0)
                            {
                                mat[0, j, i] = MinmumValue;
                            }
                        }
                        else
                        {
                            mat[0, j, i] = MinmumValue;
                        }
                    }
                    progress = (i + 1) * 100 / ntar_sites;
                    if (progress > count)
                    {
                        cancelProgressHandler.Progress("Package_Tool", progress, "Caculating Cell: " + (i + 1));
                        count++;
                    }
                }
                for (int j = 0; j < nstep; j++)
                {
                    mat.DateTimes[j] = Start.AddSeconds(j * TimeStep);
                }
                cancelProgressHandler.Progress("Package_Tool", 100, "");
                Workspace.Add(mat);
                fs_source.Close();
                fs_target.Close();
                return(true);
            }
        }
예제 #9
0
        private bool HandleLayers(AppCommand command)
        {
            switch (command)
            {
            //case AppCommand.AddDatabase:
            //    LayerHelper.OpenOgrLayer();
            //    return true;
            //case AppCommand.Open:
            //    LayerHelper.AddLayer(LayerType.All);
            //    return true;
            //case AppCommand.AddRaster:
            //    LayerHelper.AddLayer(LayerType.Raster);
            //    return true;

            //관리 -> 레이어 불러오기
            case AppCommand.AddVector:
            {
                var dm = new DotSpatial.Data.DataManager()
                {
                    LoadInRam = true
                };

                var files = MmakerShell.Dialog.OpenShapeFiles();
                if (files == null)
                {
                    //선택 파일이 없으면 리턴
                    return(true);
                }

                foreach (string file in files)
                {
                    IFeatureSet layer = dm.OpenVector(file, true, null);
                    LayerLoader form  = new Views.LayerLoader(layer)
                    {
                        StartPosition = FormStartPosition.CenterScreen, MmakerShell = MmakerShell
                    };
                    DialogResult log = form.ShowDialog();
                    layer.Close();
                }
            }
                return(true);

            case AppCommand.ZoomToLayer:
            {
                IMapLayer layer = Map.Layers.SelectedLayer;
                if (layer == null)
                {
                    return(false);
                }

                Map.ViewExtents = layer.Extent;
            }
                return(true);

                //case AppCommand.CreateLayer:
                //    Editor.RunCommand(EditorCommand.CreateLayer);
                //    return true;
                //case AppCommand.RemoveLayer:
                //    LayerHelper.RemoveLayer();
                //    return true;
            }
            return(false);
        }
예제 #10
0
        public void shpWrite(string path)
        {
            fs.DataTable.Columns.Add(new DataColumn("ID", typeof(int)));
            DataColumn col = new DataColumn("Project", typeof(string));

            col.MaxLength = 50;
            fs.DataTable.Columns.Add(col);
            fs.DataTable.Columns.Add(new DataColumn("Area", typeof(double)));
            IFeatureSet fsource = FeatureSet.Open(@"Sample\Sample.shp");

            fs.Projection = fsource.Projection;
            fsource.Close();
            int ID = 0;

            foreach (Geometries geometry in project.Geometries)
            {
                ID++;
                Polygon[] pgs = new Polygon[geometry.Polygons.Count];
                int       i   = 0;
                //foreach (Geometries geometry in project.Geometries) {

                foreach (GeoPolygon polygon in geometry.Polygons)
                {
                    List <Coordinate> vertices = new List <Coordinate>();

                    //polygon.Points.Reverse();

                    if (polygon.Circle > 1 && !polygon.GetDirection())
                    {
                        polygon.Points.Reverse();
                    }
                    else if (polygon.Circle == 1 && polygon.GetDirection())
                    {
                        polygon.Points.Reverse();
                    }

                    foreach (GeoPoint point in polygon.Points)
                    {
                        Coordinate vertice = new Coordinate();
                        vertice.X = point.X;
                        vertice.Y = point.Y;
                        vertices.Add(vertice);
                    }

                    Polygon geom = new Polygon(vertices);

                    pgs[i] = geom;

                    i++;
                }
                //}


                MultiPolygon geoms = new MultiPolygon(pgs);
                geoms.ToText();
                IFeature feature = fs.AddFeature(geoms);
                feature.DataRow.BeginEdit();
                feature.DataRow["ID"]      = ID;
                feature.DataRow["Project"] = project.Name;
                //feature.DataRow["Area"] = feature.Area();
                feature.DataRow.EndEdit();
            }
            //fs.Projection = ProjectionInfo.(@"F:\数据\2013SHP\DLTB.shp");
            //fs.ProjectionString = " +x_0=40500000 +y_0=0 +lat_0=0 +lon_0=120 +proj=tmerc +a=6378140 +b=6356755.28815753 +no_defs";

            fs.SaveAs(path, true);

            fs.Dispose();
            GeoRead gr = new GeoRead(path);

            gr.shpAreaReCalculate();
            //fs = FeatureSet.Open(path);
        }
예제 #11
0
        public bool Execute1(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            StreamReader sr    = new StreamReader(Path.Combine(FileDirectory, "list.txt"));
            int          nfile = 0;

            while (!sr.EndOfStream)
            {
                sr.ReadLine();
                nfile++;
            }
            sr.Close();
            sr = new StreamReader(Path.Combine(FileDirectory, "list.txt"));
            string[] dirs = new string[nfile];
            for (int i = 0; i < nfile; i++)
            {
                var str = sr.ReadLine();
                dirs[i] = Path.Combine(FileDirectory, str + "_2.tif");
            }

            int[] bandlist = new int[] { 4, 3, 2 };
            //string[] dirs = Directory.GetFiles(FileDirectory, "*_2.tif");
            string        center_shp = @"E:\Project\HRB\Badan Jarian\Data\Geospatial\Center35.shp";
            StreamWriter  sw         = new StreamWriter(Path.Combine(FileDirectory, "area.csv"));
            StreamWriter  sw_alpha   = new StreamWriter(Path.Combine(FileDirectory, "alpha.txt"));
            IFeatureSet   center_fs  = FeatureSet.Open(center_shp);
            List <double> vec        = new List <double>();

            try
            {
                double cell_area = 5 * 5;

                var center_pt  = center_fs.Features[0].Geometry.Coordinate;
                var center_vec = new double[3];
                var pt_vec     = new double[3];
                int progress   = 0;
                int count      = 1;
                int t          = 0;
                vec.Clear();
                foreach (var file in dirs)
                {
                    long    wcount     = 0;
                    var     temp       = Path.GetFileNameWithoutExtension(file);
                    var     daystr     = temp.Remove(10);
                    var     water_file = file.Replace("_2", "_water");
                    IRaster raster2    = Raster.OpenFile(file);
                    raster2.SaveAs(water_file);
                    IRaster raster3      = Raster.OpenFile(file.Replace("_2", "_3"));
                    IRaster raster4      = Raster.OpenFile(file.Replace("_2", "_4"));
                    IRaster raster_water = Raster.OpenFile(water_file);
                    double[,] img = new double[raster2.NumRows, raster2.NumColumns];
                    var cell = raster2.ProjToCell(center_pt);
                    center_vec[0] = raster2.Value[cell.Row, cell.Column];
                    center_vec[1] = raster3.Value[cell.Row, cell.Column];
                    center_vec[2] = raster4.Value[cell.Row, cell.Column];
                    for (int i = 0; i < raster2.NumRows; i++)
                    {
                        for (int j = 0; j < raster2.NumColumns; j++)
                        {
                            if (raster2.Value[i, j] == raster2.NoDataValue)
                            {
                                img[i, j] = 0;
                                raster_water.Value[i, j] = 0;
                                sw_alpha.WriteLine(0);
                                vec.Add(0);
                            }
                            else
                            {
                                pt_vec[0] = raster2.Value[i, j];
                                pt_vec[1] = raster3.Value[i, j];
                                pt_vec[2] = raster4.Value[i, j];
                                var alpha = sam(pt_vec, center_vec);
                                if (alpha <= AlphaThreashhold)
                                {
                                    raster_water.Value[i, j] = 1;
                                    wcount++;
                                }
                                else
                                {
                                    raster_water.Value[i, j] = 0;
                                }
                                try
                                {
                                    raster_water.Value[i, j] = alpha;
                                }
                                catch (Exception ex)
                                {
                                    cancelProgressHandler.Progress("Package_Tool", progress, "Warning: " + ex.Message + " " + alpha);
                                    alpha = 0;
                                    raster_water.Value[i, j] = 0;
                                }
                                finally
                                {
                                    img[i, j] = alpha;
                                    vec.Add(alpha);
                                    sw_alpha.WriteLine(alpha);
                                }
                            }
                        }
                    }
                    var max   = vec.Max();
                    var min   = vec.Min();
                    var delta = max - min;
                    int k     = 0;
                    for (int i = 0; i < raster2.NumRows; i++)
                    {
                        for (int j = 0; j < raster2.NumColumns; j++)
                        {
                            img[i, j] = (vec[k] - min) / delta * 255;
                            raster_water.Value[i, j] = img[i, j];
                            k++;
                        }
                    }

                    var sobled_img = sobel(img, raster2.NumRows, raster2.NumColumns);
                    for (int i = 0; i < raster2.NumRows; i++)
                    {
                        for (int j = 0; j < raster2.NumColumns; j++)
                        {
                            raster_water.Value[i, j] = sobled_img[i, j];
                        }
                    }
                    var water_area = wcount * cell_area;
                    sw.WriteLine(daystr + "," + water_area);
                    raster2.Close();
                    raster3.Close();
                    raster4.Close();
                    raster_water.Save();
                    raster_water.Close();
                    progress = t * 100 / dirs.Length;
                    if (progress > count)
                    {
                        cancelProgressHandler.Progress("Package_Tool", progress, "Processing: " + file);
                        count++;
                    }
                    t++;
                }
            }
            catch (Exception ex)
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "Error: " + ex.Message);
            }
            finally
            {
                sw_alpha.Close();
                sr.Close();
                sw.Close();
                center_fs.Close();
            }

            return(true);
        }