public static string GetWkt(this Geometry geom)
        {
            string wkt = string.Empty;

            geom.ExportToWkt(out wkt);
            return(wkt);
        }
        public static object OutputDistricts(string pMdbFile)
        {
            var mDriver = Ogr.GetDriverByName("PGeo");

            if (mDriver == null)
            {
                return(null);
            }

            Debug.WriteLine("Loaded driver");
            var mSource = mDriver.Open(pMdbFile, 0);

            if (mSource == null)
            {
                return(null);
            }

            Debug.WriteLine("Loaded datasource");
            var mLayer = mSource.GetLayerByName("ADRDISTRICT");

            //Debug.WriteLine("Set attribute filter");
            if (mLayer == null)
            {
                return(null);
            }
            Debug.WriteLine("Loaded layer");
            var i = 0;

            OSGeo.OGR.Feature mFeature;
            Debug.WriteLine("First pass - get feature");
            var mCount = mLayer.GetFeatureCount(1);

            for (var j = 0; j < mCount; j++)
            {
                mFeature = mLayer.GetFeature(j);
                string             mWkt;
                string             mAbbrev = mFeature.GetFieldAsString("ABBREVIATION");
                OSGeo.OGR.Geometry mGeom   = mFeature.GetGeometryRef();
                mGeom.ExportToWkt(out mWkt);
                if (String.IsNullOrEmpty(mWkt))
                {
                    Debug.WriteLine("Error with geometry");
                }
                else
                {
                    Debug.WriteLine(mAbbrev);
                }
            }
            Debug.WriteLine("Second pass - get next");

            while (null != (mFeature = mLayer.GetNextFeature()))
            {
                i++;
                string             mWkt;
                string             mAbbrev = mFeature.GetFieldAsString("ABBREVIATION");
                OSGeo.OGR.Geometry mGeom   = mFeature.GetGeometryRef();
                mGeom.ExportToWkt(out mWkt);
                if (String.IsNullOrEmpty(mWkt))
                {
                    Debug.WriteLine("Error with geometry");
                }
                else
                {
                    Debug.WriteLine(mAbbrev);
                }
            }
            Debug.WriteLine("Processed {0} features", i);
            return(true);
        }
        /// <summary>
        /// Exports the selected database to fieldAttributes filegeodatabase
        /// </summary>
        /// <param name="pOnlyApproved"></param>
        /// <returns></returns>
        public static FeatureSet GetDistrictsFeatureSetFromAdmAdrMdb(ref ToolStripProgressBar pPgBar, string pMdbFile, int pOnlyApproved = 0)
        {
            // Setup SQL string to select all or only some streets
            string mSql;

            if (pOnlyApproved == 1)
            {
                mSql = "SELECT OBJECTID, ABBREVIATION, NAMEENGLISH, NAMEARABIC, NAMEPOPULARENGLISH, NAMEPOPULARARABIC, APPROVED FROM ADRDISTRICT WHERE APPROVED = 'Y'";
            }
            else
            {
                mSql = "SELECT OBJECTID, ABBREVIATION, NAMEENGLISH, NAMEARABIC, NAMEPOPULARENGLISH, NAMEPOPULARARABIC, APPROVED FROM ADRDISTRICT";
            }

            // Setup fieldAttributes dictionary to hold road names
            var mDistrictNames = new Dictionary <int, DataRow>();

            // Connect to database and load names
            var mOdbcConn    = new OdbcConnection("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=" + pMdbFile + ";Uid=Admin;Pwd=;");
            var mDataAdapter = new OdbcDataAdapter(mSql, mOdbcConn);
            var mDataTable   = new DataTable();

            mDataAdapter.Fill(mDataTable);
            int ctr1   = 0;
            int total1 = mDataTable.Rows.Count;

            pPgBar.Value = ctr1;
            foreach (DataRow mRow in mDataTable.Rows)
            {
                if (mDistrictNames.Keys.Contains(mRow["OBJECTID"].ToInt()))
                {
                    Utilities.LogDebug("Key " + mRow["OBJECTID"].ToInt() + " already exists in districts");
                }
                mDistrictNames.Add(mRow["OBJECTID"].ToInt(), mRow);
                ctr1++;
                if (ctr1 % 100 == 0)
                {
                    double mFraction1 = (((double)ctr1 / (double)total1) * 100);
                    pPgBar.ProgressBar.Value = (int)(Math.Round(mFraction1));
                    Application.DoEvents();
                }
            }

            Debug.WriteLine("Done loading district names");
            Debug.WriteLine(ctr1);
            mOdbcConn.Close();
            mDataAdapter = null;
            mOdbcConn    = null;

            // Connect to database using OGR to load geometries
            var mDriver = Ogr.GetDriverByName("PGeo");

            if (mDriver == null)
            {
                return(null);
            }

            Debug.WriteLine("Loaded driver");
            var mSource = mDriver.Open(pMdbFile, 0);

            if (mSource == null)
            {
                return(null);
            }

            Debug.WriteLine("Loaded datasource");
            var mLayer = mSource.GetLayerByName("ADRDISTRICT");

            //Debug.WriteLine("Set attribute filter");
            if (mLayer == null)
            {
                return(null);
            }
            Debug.WriteLine("Loaded layer");

            // Create simplified roads
            var mDistrict = new District();

            int mTotal2 = mLayer.GetFeatureCount(1);

            Debug.WriteLine("Number of features" + mTotal2);

            pPgBar.Value = 0;
            OSGeo.OGR.Feature mFeature;

            int mFeatureIndex = 0;

            while (null != (mFeature = mLayer.GetNextFeature()))
            {
                if (mFeature == null)
                {
                    Debug.WriteLine("Feature #{0} is null", mFeatureIndex);
                }
                else
                {
                    OSGeo.OGR.Geometry mGeometry = mFeature.GetGeometryRef();
                    if (mGeometry != null)
                    {
                        mGeometry.FlattenTo2D();
                        byte[] mWkb = new Byte[mGeometry.WkbSize()];
                        string mWkt = "";
                        mGeometry.ExportToWkb(mWkb);
                        mGeometry.ExportToWkt(out mWkt);

                        IMultiPolygon mPolygon;

                        int mDistrictObjectId = mFeature.GetFieldAsInteger("OBJECTID");

                        if (mDistrictObjectId > 0)
                        {
                            var       mWkbReader = new WkbReader();
                            IGeometry mGeom      = mWkbReader.Read(mWkb);
                            if (mGeom.GetType() == typeof(DotSpatial.Topology.MultiPolygon))
                            {
                                var mPolygons = new List <Polygon>();
                                mPolygons.Add(mGeom as Polygon);

                                var mPolygonsN = new List <Polygon>();
                                foreach (var mPart in mPolygons)
                                {
                                    if (mPart != null)
                                    {
                                        mPolygonsN.Add(mPart);
                                    }
                                }
                                mPolygon = new DotSpatial.Topology.MultiPolygon(mPolygonsN.ToArray <Polygon>());
                            }
                            else
                            {
                                mPolygon = mGeom as IMultiPolygon;
                            }

                            if (mDistrictNames.ContainsKey(mDistrictObjectId))
                            {
                                var mDistrictName = mDistrictNames[mDistrictObjectId];


                                var mDistrictAbbreviation = mDistrictName["ABBREVIATION"].ToString();
                                var mNameArabic           = mDistrictName["NAMEARABIC"].ToString();
                                var mNameLatin            = mDistrictName["NAMEENGLISH"].ToString();
                                var mNamePopularArabic    = mDistrictName["NAMEPOPULARARABIC"].ToString();
                                var mNamePopularLatin     = mDistrictName["NAMEPOPULARENGLISH"].ToString();
                                var mApproved             = mDistrictName["APPROVED"].ToString();
                                mDistrict.AddNewRow(mGeom, mDistrictObjectId, mDistrictAbbreviation, mNameArabic, mNameLatin, mNamePopularArabic, mNamePopularLatin, mApproved);
                            }
                            else
                            {
                                Debug.WriteLine("No matching abbreviation");
                            }
                        }
                        else
                        {
                            Debug.WriteLine("No abbreviation");
                        }
                    }
                    else
                    {
                        Debug.WriteLine("No geometry");
                    }
                }

                if (mFeatureIndex % (mTotal2 / 20) == 0)
                {
                    double mFraction = (double)mFeatureIndex / (double)mTotal2;
                    int    mProgress = (int)Math.Round(mFraction * 100);
                    pPgBar.ProgressBar.Value = mProgress;
                    Application.DoEvents();
                }
                mFeatureIndex++;
            }

            mDistrict.UpdateExtent();
            Debug.WriteLine("Done creating districts...");
            return(mDistrict);
        }
        public static void AnalyzeRoadBoundingBoxes(string pMdbFile, string pLogFile, Action <Object, bool> aLog, int pOnlyApproved = 0)
        {
            var roadSuspects = new List <RoadSuspect>();
            // Setup SQL string to select all or only some streets
            string sql;

            if (pOnlyApproved == 1)
            {
                sql = "SELECT ADRROADID, NAMEENGLISH, NAMEARABIC, NAMEPOPULARENGLISH, NAMEPOPULARARABIC, ROADTYPE, ADRDISTRICTID, APPROVED FROM ADM_ADRROAD WHERE APPROVED = 1 ORDER BY ADRROADID";
            }
            else
            {
                sql = "SELECT ADRROADID, NAMEENGLISH, NAMEARABIC, NAMEPOPULARENGLISH, NAMEPOPULARARABIC, ROADTYPE, ADRDISTRICTID, APPROVED FROM ADM_ADRROAD ORDER BY ADRROADID";
            }

            // Setup fieldAttributes dictionary to hold road names
            var mRoads = new Dictionary <int, DataRow>();

            // Connect to database and load names
            var mOdbcConn    = new OdbcConnection("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=" + pMdbFile + ";Uid=Admin;Pwd=;");
            var mDataAdapter = new OdbcDataAdapter(sql, mOdbcConn);
            var mDataTable   = new DataTable();

            mDataAdapter.Fill(mDataTable);
            int ctr1   = 0;
            int total1 = mDataTable.Rows.Count;

            foreach (DataRow mRow in mDataTable.Rows)
            {
                int mRoadId;
                if (int.TryParse(mRow["ADRROADID"].ToString(), out mRoadId))
                {
                    mRoads.Add(mRoadId, mRow);
                }
                ctr1++;
                if (ctr1 % 100 == 0)
                {
                    double mFraction1 = (((double)ctr1 / (double)total1) * 100);
                    Application.DoEvents();
                }
            }
            Debug.WriteLine("Done loading road names");
            mOdbcConn.Close();
            mDataAdapter = null;
            mOdbcConn    = null;

            // Connect to database using OGR to load geometries
            var mDriver = Ogr.GetDriverByName("PGeo");

            if (mDriver == null)
            {
                return;
            }

            Debug.WriteLine("Loaded driver");
            var mSource = mDriver.Open(pMdbFile, 0);

            if (mSource == null)
            {
                return;
            }

            Debug.WriteLine("Loaded datasource");
            var mLayer = mSource.GetLayerByName("ADRROADSEGMENT");

            if (mLayer == null)
            {
                return;
            }
            Debug.WriteLine("Loaded layer");

            // Create simplified roads
            var mSimplifiedRoadsFeatureSet = new SimplifiedRoads();

            int mTotal2 = mLayer.GetFeatureCount(0);

            foreach (var mRoadID in mRoads)
            {
                mLayer.SetAttributeFilter("ADRROADID = " + mRoadID.Key);

                OSGeo.OGR.Feature mFeature;
                int           mNumShapes  = 0;
                double        mLength     = 0;
                double        mLeft       = 0;
                double        mBottom     = 0;
                double        mTop        = 0;
                double        mRight      = 0;
                int           mDuplicates = 0;
                List <string> mGeoms      = new List <string>();
                while (null != (mFeature = mLayer.GetNextFeature()))
                {
                    OSGeo.OGR.Geometry mGeom = mFeature.GetGeometryRef();

                    if (mGeom != null)
                    {
                        string wkt;
                        mGeom.ExportToWkt(out wkt);
                        OSGeo.OGR.Envelope mExtent = new OSGeo.OGR.Envelope();
                        mGeom.GetEnvelope(mExtent);
                        if (mTop == 0 || mExtent.MaxY > mTop)
                        {
                            mTop = mExtent.MaxY;
                        }
                        if (mBottom == 0 || mExtent.MinY < mBottom)
                        {
                            mBottom = mExtent.MinY;
                        }
                        if (mLeft == 0 || mExtent.MinX < mLeft)
                        {
                            mLeft = mExtent.MinX;
                        }
                        if (mRight == 0 || mExtent.MaxX > mRight)
                        {
                            mRight = mExtent.MaxX;
                        }

                        if (!mGeoms.Contains(wkt))
                        {
                            mLength = mLength + mGeom.Length();
                            mGeoms.Add(wkt);
                        }
                        else
                        {
                            mDuplicates++;
                        }
                    }

                    mNumShapes++;
                }

                var mBoxWidth    = mRight - mLeft;
                var mBoxHeight   = mTop - mBottom;
                var mBoxDiagonal = Math.Sqrt(mBoxWidth * mBoxWidth + mBoxHeight * mBoxHeight);

                roadSuspects.Add(new RoadSuspect(mRoadID.Key,
                                                 mNumShapes,
                                                 mDuplicates,
                                                 Math.Round(mBoxDiagonal, 1),
                                                 Math.Round(mLength, 1)));


                if (mLength > (2.2 * mBoxDiagonal) || mDuplicates > 0)
                {
                    aLog(String.Format("r: {0}, s: {1}, l: {2}, d: {3}, bb: {4}",
                                       mRoadID.Key,
                                       mNumShapes,
                                       Math.Round(mLength, 1),
                                       mDuplicates,
                                       Math.Round(mBoxDiagonal, 1)),
                         true);
                }
            }

            using (var mCsvWriter = new CsvHelper.CsvWriter(new ExcelSerializer(pLogFile)))
            {
                mCsvWriter.WriteRecords(roadSuspects);
                aLog("Wrote output to " + pLogFile, true);
                aLog("Operation completed...", true);
            }
        }