private void exportThreatSurfaceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CurrentThreatSurface == null)
                MessageBox.Show("No threat surface displayed. Nothing to export.");
            else
            {
                List<string> filters = new List<string>();
                Dictionary<string, ImageFormat> extensionImageFormat = new Dictionary<string, ImageFormat>();
                foreach (ImageFormat format in new ImageFormat[] { ImageFormat.Bmp, ImageFormat.Emf, ImageFormat.Exif, ImageFormat.Gif, ImageFormat.Icon, ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Tiff, ImageFormat.Wmf })
                {
                    string extension = format.ToString().ToLower();
                    filters.Add(format + " image files (*." + extension + ")|*." + extension);
                    extensionImageFormat.Add(extension, format);
                }

                filters.Add("ESRI shapefiles (*.shp)|*.shp");

                filters.Sort();

                string path = LAIR.IO.File.PromptForSavePath("Select export location...", filters.Concatenate("|"));
                if (path != null)
                {
                    if (File.Exists(path))
                        File.Delete(path);

                    string extension = Path.GetExtension(path).Trim('.').ToLower();

                    if (extensionImageFormat.ContainsKey(extension))
                        CurrentThreatSurface.Save(path, extensionImageFormat[extension]);
                    else if (extension == "shp")
                    {
                        NpgsqlCommand cmd = DB.Connection.NewCommand(null);
                        try
                        {
                            cmd.CommandText = "CREATE TABLE temp (" +
                                              "id SERIAL PRIMARY KEY," +
                                              "region GEOMETRY(POLYGON," + DisplayedPrediction.PredictionArea.Shapefile.SRID + ")," +
                                              "level DOUBLE PRECISION," +
                                              "type VARCHAR)";
                            cmd.ExecuteNonQuery();

                            Dictionary<long, List<Tuple<RectangleF, double, string>>> sliceSquareThreatType = new Dictionary<long, List<Tuple<RectangleF, double, string>>>();
                            GetThreatSurfaces(new Rectangle(0, 0, CurrentThreatSurface.Width, CurrentThreatSurface.Height), false, sliceSquareThreatType);
                            string basePath = path;
                            foreach (long slice in sliceSquareThreatType.Keys)
                            {
                                if (slice != -1)
                                    path = Path.Combine(Path.GetDirectoryName(basePath), Path.GetFileNameWithoutExtension(basePath), "_" + slice, Path.GetExtension(basePath));

                                cmd.CommandText = "DELETE FROM temp";
                                cmd.ExecuteNonQuery();

                                int insertNum = 0;
                                int insertsPerBatch = 500;
                                StringBuilder cmdTxt = new StringBuilder();
                                foreach (Tuple<RectangleF, double, string> squareThreatType in sliceSquareThreatType[slice])
                                {
                                    float bottom = squareThreatType.Item1.Bottom;
                                    float left = squareThreatType.Item1.Left;
                                    float top = squareThreatType.Item1.Top;
                                    float right = squareThreatType.Item1.Right;
                                    PostGIS.Polygon polygon = new PostGIS.Polygon(new PostGIS.Point[]{
                                    GetPostGisPointFromDrawingPoint(new PointF(left, bottom)),
                                    GetPostGisPointFromDrawingPoint(new PointF(left, top)),
                                    GetPostGisPointFromDrawingPoint(new PointF(right, top)),
                                    GetPostGisPointFromDrawingPoint(new PointF(right, bottom)),
                                    GetPostGisPointFromDrawingPoint(new PointF(left, bottom))}, DisplayedPrediction.PredictionArea.Shapefile.SRID);

                                    cmdTxt.Append((cmdTxt.Length == 0 ? "INSERT INTO temp (region,level,type) VALUES " : ",") + "(" + polygon.StGeometryFromText + "," +
                                                                                                                                      squareThreatType.Item2 + "," +
                                                                                                                                      "'" + squareThreatType.Item3 + "')");
                                    if ((insertNum++ % insertsPerBatch) == 0)
                                    {
                                        cmd.CommandText = cmdTxt.ToString();
                                        cmd.ExecuteNonQuery();
                                        cmdTxt.Clear();
                                    }
                                }

                                if (cmdTxt.Length > 0)
                                {
                                    cmd.CommandText = cmdTxt.ToString();
                                    cmd.ExecuteNonQuery();
                                    cmdTxt.Clear();
                                }

                                using (Process process = new Process())
                                {
                                    process.StartInfo.FileName = ATT.Configuration.Pgsql2ShpPath;
                                    process.StartInfo.Arguments = "-f \"" + path + "\" " +
                                                                  "-h " + ATT.Configuration.PostgresHost + " " +
                                                                  "-u " + ATT.Configuration.PostgresUser + " " +
                                                                  "-P " + ATT.Configuration.PostgresPassword + " " +
                                                                  ATT.Configuration.PostgresDatabase + " " +
                                                                  "temp";

                                    process.StartInfo.CreateNoWindow = true;
                                    process.StartInfo.UseShellExecute = false;
                                    process.StartInfo.RedirectStandardError = true;
                                    process.StartInfo.RedirectStandardOutput = true;
                                    process.Start();

                                    Console.Out.WriteLine("Exporting threat surface to shapefile \"" + path + "\".");

                                    string output = process.StandardOutput.ReadToEnd().Trim();
                                    string error = process.StandardError.ReadToEnd().Trim();
                                    Console.Out.WriteLine(output + Environment.NewLine + error);

                                    process.WaitForExit();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.Out.WriteLine("Error while exporting threat surface as shapefile:  " + ex.Message);
                            throw ex;
                        }
                        finally
                        {
                            try
                            {
                                cmd.CommandText = "DROP TABLE temp";
                                cmd.ExecuteNonQuery();
                            }
                            catch (Exception ex) { Console.Out.WriteLine("Failed to drop temp table for threat surface export:  " + ex.Message); }

                            DB.Connection.Return(cmd.Connection);
                        }
                    }
                    else
                        MessageBox.Show("The file extension \"" + extension + "\" is not a supported export type.");

                    Console.Out.WriteLine("Export finished.");
                }
            }
        }
Example #2
0
        /// <summary>
        /// Updates the queued report status.
        /// I would prefer this to be an instance method on the GenerationDao (but this is ok for now)
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="reportGenerationQueueId">The report generation queue id.</param>
        /// <param name="reportStatus">The report status.</param>
        /// <param name="executionLog">The execution log.</param>
        /// <param name="queryText">The query text.</param>
        public static void UpdateQueuedReportStatus(
            IReportQueueStatusService service,
            int reportGenerationQueueId,
            ReportStatus reportStatus,
            List<string> executionLog,
            string queryText)
        {
            string executionLogStr = string.Empty;
            string queryTextStr = string.Empty;

            if (reportStatus == ReportStatus.Completed || reportStatus == ReportStatus.Failed)
            {
                executionLogStr = " Execution Log : " + executionLog.Concatenate(System.Environment.NewLine);
                queryTextStr = "QueryText: " + queryText;
            }
            else if (reportStatus == ReportStatus.Cancelled)
            {
                executionLogStr = "-- Report cancelled due to deactivated ReportType";
                queryTextStr = "-- Report cancelled due to deactivated ReportType";
            }

            service.UpdateReportGenerationQueue(new ReportGenerationQueueStatusDto()
            {
                ReportGenerationQueueId = reportGenerationQueueId,
                ReportStatus = reportStatus,
                QueryText = queryTextStr,
                ExecutionLog = executionLogStr
            });
        }
        public override void Import()
        {
            base.Import();

            Console.Out.WriteLine("Importing shapefile from \"" + Path + "\"...");

            try
            {
                Dictionary<string, string> importOptionValue = new Dictionary<string, string>();
                string importOptionsPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Path), System.IO.Path.GetFileNameWithoutExtension(Path) + ".att");
                if (File.Exists(importOptionsPath))
                    foreach (string line in File.ReadLines(importOptionsPath))
                    {
                        string[] parts = line.Split('=');
                        importOptionValue.Add(parts[0].Trim(), parts[1].Trim());
                    }

                if (_sourceSRID > 0 && _targetSRID > 0)
                    importOptionValue["reprojection"] = _sourceSRID + ":" + _targetSRID;

                if (!string.IsNullOrWhiteSpace(Name))
                    importOptionValue["name"] = Name;

                List<string> neededValues = new List<string>();
                if (!importOptionValue.ContainsKey("reprojection") || string.IsNullOrWhiteSpace(importOptionValue["reprojection"])) neededValues.Add("reprojection");
                if (!importOptionValue.ContainsKey("name") || string.IsNullOrWhiteSpace(importOptionValue["name"])) neededValues.Add("name");
                if (neededValues.Count > 0)
                {
                    if (_shapefileInfoRetriever == null)
                        throw new Exception("Missing the following shapefile options, and no information retriever was present:  " + neededValues.Concatenate(","));
                    else
                        _shapefileInfoRetriever.GetShapefileInfo(Path, neededValues, importOptionValue);
                }

                string missingValues = neededValues.Where(v => !importOptionValue.ContainsKey(v) || string.IsNullOrWhiteSpace(importOptionValue[v])).Concatenate(", ");
                if (missingValues != "")
                    throw new Exception("Failed to provide needed values for shapefile import:  " + missingValues);

                string reprojection = importOptionValue["reprojection"];
                Match reprojectionMatch = new Regex("(?<from>[0-9]+):(?<to>[0-9]+)").Match(reprojection);
                if (!reprojectionMatch.Success)
                    throw new Exception("Invalid shapefile reprojection \"" + reprojection + "\". Must be in 1234:1234 format.");

                int fromSRID = int.Parse(reprojectionMatch.Groups["from"].Value);
                int toSRID = int.Parse(reprojectionMatch.Groups["to"].Value);
                if (fromSRID == toSRID)
                    reprojection = fromSRID.ToString();

                string name = importOptionValue["name"];
                if (string.IsNullOrWhiteSpace(name))
                    throw new Exception("Empty name given for shapefile \"" + Path + "\".");

                Name = name; // to make sure names retrieved from *.att files get back to the object and ultimately back to the DB

                File.WriteAllText(importOptionsPath, "reprojection=" + fromSRID + ":" + toSRID + Environment.NewLine +
                                                     "name=" + name);

                Shapefile.ShapefileType type;
                if (this is FeatureShapefileImporter)
                    type = Shapefile.ShapefileType.Feature;
                else if (this is AreaShapefileImporter)
                    type = Shapefile.ShapefileType.Area;
                else if (this is IncidentShapefileImporter)
                    type = Shapefile.ShapefileType.Incident;
                else
                    throw new NotImplementedException("Unrecognized shapefile importer type:  " + GetType());

                _importedShapefile = Shapefile.Create(name, toSRID, type);

                string sql;
                string error;
                using (Process process = new Process())
                {
                    process.StartInfo.FileName = Configuration.Shp2PgsqlPath;
                    process.StartInfo.Arguments = "-I -g " + ShapefileGeometry.Columns.Geometry + " -s " + reprojection + " \"" + Path + "\" " + _importedShapefile.GeometryTable;
                    process.StartInfo.CreateNoWindow = true;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardError = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.Start();

                    Console.Out.WriteLine("Converting shapefile \"" + name + "\".");

                    sql = process.StandardOutput.ReadToEnd().Replace("BEGIN;", "").Replace("COMMIT;", "");
                    error = process.StandardError.ReadToEnd().Trim().Replace(Environment.NewLine, "; ").Replace("\n", "; ");

                    process.WaitForExit();
                }

                Console.Out.WriteLine(error);

                DB.Connection.ExecuteNonQuery(sql);

                // if there's an id column already, rename it native_id
                if (DB.Connection.GetColumnNames(_importedShapefile.GeometryTable).Select(c => c.ToLower()).Contains("id"))
                {
                    DB.Connection.ExecuteNonQuery("ALTER TABLE " + _importedShapefile.GeometryTable + " DROP COLUMN IF EXISTS native_id;" +
                                                  "ALTER TABLE " + _importedShapefile.GeometryTable + " RENAME COLUMN id TO native_id");
                }

                // rename primary key column to ShapefileGeometry.Columns.Id
                List<string> primaryKeyColumns = DB.Connection.GetPrimaryKeyColumns(_importedShapefile.GeometryTable).ToList();
                if (primaryKeyColumns.Count == 1)
                {
                    if (primaryKeyColumns[0] != ShapefileGeometry.Columns.Id)
                    {
                        DB.Connection.ExecuteNonQuery("ALTER TABLE " + _importedShapefile.GeometryTable + " DROP COLUMN IF EXISTS " + ShapefileGeometry.Columns.Id + ";" +
                                                      "ALTER TABLE " + _importedShapefile.GeometryTable + " RENAME COLUMN " + primaryKeyColumns[0] + " TO " + ShapefileGeometry.Columns.Id);
                    }
                }
                else
                    throw new Exception("Imported shapefile database does not contain a single primary key column.");

                Console.Out.WriteLine("Shapefile import succeeded.");
            }
            catch (Exception ex)
            {
                if (_importedShapefile != null)
                {
                    try { _importedShapefile.Delete(); }
                    catch (Exception ex2) { Console.Out.WriteLine("Failed to delete shapefile:  " + ex2.Message); }
                }

                _importedShapefile = null;

                throw new Exception("Shapefile import failed:  " + ex.Message);
            }
        }