Example #1
0
        public void TestForFinality()
        {
            string simpleClass = "public class Garble { public final func finalmethod() { }; public func virtmethod() { } }";

            using (DisposableTempFile montyLib = new DisposableTempFile("libXython.dylib", false)) {
                Compiler.CompileStringToFileUsing(null, XCodeCompiler.SwiftcCustom, simpleClass, " -emit-library -module-name Xython", montyLib);
                var             errors    = new ErrorHandling();
                ModuleInventory inventory = ModuleInventory.FromFile(montyLib.Filename, errors);
                Utils.CheckErrors(errors);
                ClassContents cl = inventory.ClassesForName(new SwiftName("Xython", false)).FirstOrDefault();
                Assert.IsNotNull(cl);

                if (cl.WitnessTable == null || cl.WitnessTable.MangledNames == null ||
                    cl.WitnessTable.MangledNames.Count() == 0)
                {
                    return;
                }

                foreach (var oi in cl.Methods.Values)
                {
                    foreach (TLFunction f in oi.Functions)
                    {
                        if (f.MangledName.Contains("finalmethod"))
                        {
                            Assert.IsTrue(cl.IsFinal(f));
                        }
                        else if (f.MangledName.Contains("virtmethod"))
                        {
                            Assert.IsFalse(cl.IsFinal(f));
                        }
                    }
                }
            }
        }
Example #2
0
        string CompileWithInvokingCode(CSFile cs, CSLine invoker, string nameSpace)
        {
            CSNamespace ns       = new CSNamespace(nameSpace);
            CSCodeBlock mainBody = CSCodeBlock.Create(invoker);
            CSMethod    main     = new CSMethod(CSVisibility.Public, CSMethodKind.Static, CSSimpleType.Void,
                                                new CSIdentifier("Main"), new CSParameterList(new CSParameter(new CSSimpleType("string", true), "args")),
                                                mainBody);
            CSClass cl = new CSClass(CSVisibility.Public, "NameNotImportant", new CSMethod [] { main });

            ns.Block.Add(cl);

            cs.Namespaces.Add(ns);

            using (DisposableTempFile csOut = new DisposableTempFile(null, null, "cs", true)) {
                CodeWriter.WriteToFile(csOut.Filename, cs);

                using (Stream csExeStm = Compiler.CompileUsing(null, XCodeCompiler.CSharpExe, csOut.Filename,
                                                               $"-lib:{kSwiftRuntimeMacOutputDirectory} -r:{kSwiftRuntimeLibraryMac}")) {
                    using (DisposableTempFile csExe = new DisposableTempFile(null, null, "exe", true)) {
                        csExeStm.CopyTo(csExe.Stream);
                        csExe.Stream.Close();
                        string output = Compiler.RunWithMono(csExe.Filename);
                        return(output);
                    }
                }
            }
        }
Example #3
0
        public ActionResult ImportGdbFile(ProjectPrimaryKey projectPrimaryKey, ImportGdbFileViewModel viewModel)
        {
            var project = projectPrimaryKey.EntityObject;

            if (!ModelState.IsValid)
            {
                return(ViewImportGdbFile(viewModel, project.ProjectID));
            }

            var httpPostedFileBase = viewModel.FileResourceData;
            var fileEnding         = ".gdb.zip";

            using (var disposableTempFile = DisposableTempFile.MakeDisposableTempFileEndingIn(fileEnding))
            {
                var gdbFile = disposableTempFile.FileInfo;
                httpPostedFileBase.SaveAs(gdbFile.FullName);
                var pls = project.ProjectLocationStagings.ToList();
                foreach (var projectLocationStaging in pls)
                {
                    projectLocationStaging.DeleteFull(HttpRequestStorage.DatabaseEntities);
                }
                project.ProjectLocationStagings.Clear();
                ProjectLocationStaging.CreateProjectLocationStagingListFromGdb(gdbFile, project, CurrentPerson);
            }
            return(ApproveGisUpload(project));
        }
Example #4
0
        public static Tuple <double, double, double, double> GetExtentFromGeoJson(FileInfo ogrInfoFileInfo, string geoJson, double totalMilliseconds)
        {
            using (var geoJsonFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".json"))
            {
                File.WriteAllText(geoJsonFile.FileInfo.FullName, geoJson);

                var gdalDataDirectory    = new DirectoryInfo(Path.Combine(ogrInfoFileInfo.DirectoryName, "gdal-data"));
                var commandLineArguments = BuildOgrInfoCommandLineArgumentsGetExtent(geoJsonFile.FileInfo, gdalDataDirectory);
                var processUtilityResult = ProcessUtility.ShellAndWaitImpl(ogrInfoFileInfo.DirectoryName, ogrInfoFileInfo.FullName, commandLineArguments, true, Convert.ToInt32(totalMilliseconds));

                var lines = processUtilityResult.StdOut.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();

                // I believe this is happening irregularly - I see crashes below I can't readily reproduce. This is an attempt to narrow down the problem.
                // (Is the problem that a simple GET request is pounding on the Ogr2Ogr command line .EXE, and that the .EXE then gets too busy/overwhelmed to process multiple requests?
                //  Just my first guess. -- SLG 9/30/2019)
                Check.Ensure(lines.Any(), $"No lines found returning from exec of \"{ogrInfoFileInfo.Name}\" in processed GeoJson string \"{geoJson}\". Raw StdOut: \"{processUtilityResult.StdOut}\"");

                if (lines.Any(x => x.Contains("Feature Count: 0")))
                {
                    return(null);
                }

                // We see crash here: "Sequence contains no matching element" on lines.First(..)
                var extentTokens = lines.First(x => x.StartsWith("Extent:")).Split(new[] { ' ', '(', ')', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                return(new Tuple <double, double, double, double>(double.Parse(extentTokens[1]), double.Parse(extentTokens[2]), double.Parse(extentTokens[4]), double.Parse(extentTokens[5])));
            }
        }
Example #5
0
 public static void CompileAStream(Stream stm)
 {
     using (DisposableTempFile tf = new DisposableTempFile(null, null, "cs", true)) {
         stm.CopyTo(tf.Stream);
         tf.Stream.Flush();
         Compiler.CompileUsing(null, XCodeCompiler.CSharp, tf.Filename, "");
     }
 }
 // ReSharper disable once UnusedMember.Global
 public void ImportGeoJsonToEsriShapefile(string geoJson, string outputFilePath, string outputFileName)
 {
     using (var geoJsonFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".json"))
     {
         File.WriteAllText(geoJsonFile.FileInfo.FullName, geoJson);
         var commandLineArguments = BuildCommandLineArgumentsForGeoJsonToEsriShapefile(geoJsonFile.FileInfo, _gdalDataPath, _coordinateSystemId, outputFilePath, outputFileName);
         ExecuteOgr2OgrCommand(commandLineArguments);
     }
 }
 public void ImportGeoJsonToFileGdb(string geoJson, string outputFilePath, string outputLayerName, bool update, bool assignSrs)
 {
     using (var geoJsonFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".json"))
     {
         File.WriteAllText(geoJsonFile.FileInfo.FullName, geoJson);
         var commandLineArguments = BuildCommandLineArgumentsForGeoJsonToFileGdb(geoJsonFile.FileInfo, _gdalDataPath, _coordinateSystemId, outputFilePath, outputLayerName, update, assignSrs);
         ExecuteOgr2OgrCommandForFileGdbWrite(commandLineArguments);
     }
 }
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var errors = new List <ValidationResult>();

            FileResource.ValidateFileSize(FileResourceData, errors, GeneralUtility.NameOf(() => FileResourceData));

            using (var disposableTempFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".gdb.zip"))
            {
                var gdbFile = disposableTempFile.FileInfo;
                FileResourceData.SaveAs(gdbFile.FullName);

                var ogr2OgrCommandLineRunner = new Ogr2OgrCommandLineRunner(FirmaWebConfiguration.Ogr2OgrExecutable,
                                                                            Ogr2OgrCommandLineRunner.DefaultCoordinateSystemId,
                                                                            FirmaWebConfiguration.HttpRuntimeExecutionTimeout.TotalMilliseconds);

                List <string> featureClassNames = null;
                try
                {
                    featureClassNames = OgrInfoCommandLineRunner.GetFeatureClassNamesFromFileGdb(new FileInfo(FirmaWebConfiguration.OgrInfoExecutable),
                                                                                                 gdbFile,
                                                                                                 Ogr2OgrCommandLineRunner.DefaultTimeOut);
                }
                catch (Exception e)
                {
                    errors.Add(new ValidationResult("There was a problem uploading your file geodatabase. Verify it meets the requirements and is not corrupt."));
                    SitkaLogger.Instance.LogDetailedErrorMessage(e);
                }

                if (featureClassNames != null)
                {
                    var featureClasses = featureClassNames.ToDictionary(x => x,
                                                                        x =>
                    {
                        try
                        {
                            var geoJson = ogr2OgrCommandLineRunner.ImportFileGdbToGeoJson(gdbFile, x, false);
                            return(JsonTools.DeserializeObject <FeatureCollection>(geoJson));
                        }
                        catch (Exception e)
                        {
                            errors.Add(new ValidationResult($"There was a problem processing the Feature Class \"{x}\"."));
                            SitkaLogger.Instance.LogDetailedErrorMessage(e);
                            return(null);
                        }
                    }).Where(x => x.Value != null && FocusAreaLocationStaging.IsUsableFeatureCollectionGeoJson(x.Value));

                    if (!featureClasses.Any())
                    {
                        errors.Add(new ValidationResult("There are no usable Feature Classes in the uploaded file. Feature Classes must contain Polygon and/or Multi-Polygon features."));
                    }
                }
            }

            return(errors);
        }
 public void UpdateModel(ProjectFirmaModels.Models.Organization organization)
 {
     using (var disposableTempFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".gdb.zip"))
     {
         var gdbFile = disposableTempFile.FileInfo;
         FileResourceData.SaveAs(gdbFile.FullName);
         HttpRequestStorage.DatabaseEntities.AllOrganizationBoundaryStagings.RemoveRange(organization.OrganizationBoundaryStagings.ToList());
         organization.OrganizationBoundaryStagings.Clear();
         OrganizationModelExtensions.CreateOrganizationBoundaryStagingStagingListFromGdb(gdbFile, FileResourceData.FileName, organization);
     }
 }
 public void UpdateModel(Models.FocusArea focusArea)
 {
     using (var disposableTempFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".gdb.zip"))
     {
         var gdbFile = disposableTempFile.FileInfo;
         FileResourceData.SaveAs(gdbFile.FullName);
         HttpRequestStorage.DatabaseEntities.FocusAreaLocationStagings.RemoveRange(focusArea.FocusAreaLocationStagings.ToList());
         focusArea.FocusAreaLocationStagings.Clear();
         FocusAreaLocationStaging.CreateFocusAreaLocationStagingListFromGdb(gdbFile, focusArea);
     }
 }
        public ActionResult ImportGdbFile(ProjectPrimaryKey projectPrimaryKey, ImportGdbFileViewModel viewModel)
        {
            var project = projectPrimaryKey.EntityObject;

            if (!ModelState.IsValid)
            {
                return(ViewImportGdbFile(viewModel, project.ProjectID));
            }

            var httpPostedFileBase = viewModel.FileResourceData;
            var isKml      = httpPostedFileBase.FileName.EndsWith(".kml");
            var isKmz      = httpPostedFileBase.FileName.EndsWith(".kmz");
            var fileEnding = isKml ? ".kml" : isKmz ? ".kmz" : ".gdb.zip";

            using (var disposableTempFile = DisposableTempFile.MakeDisposableTempFileEndingIn(fileEnding))
            {
                var disposableTempFileFileInfo = disposableTempFile.FileInfo;
                httpPostedFileBase.SaveAs(disposableTempFileFileInfo.FullName);
                foreach (var projectLocationStaging in project.ProjectLocationStagings.ToList())
                {
                    projectLocationStaging.DeleteFull(HttpRequestStorage.DatabaseEntities);
                }

                try
                {
                    if (isKml)
                    {
                        ProjectLocationStagingModelExtensions.CreateProjectLocationStagingListFromKml(
                            disposableTempFileFileInfo, httpPostedFileBase.FileName, project, CurrentFirmaSession);
                    }
                    else if (isKmz)
                    {
                        ProjectLocationStagingModelExtensions.CreateProjectLocationStagingListFromKmz(
                            disposableTempFileFileInfo, httpPostedFileBase.FileName, project, CurrentFirmaSession);
                    }
                    else
                    {
                        ProjectLocationStagingModelExtensions.CreateProjectLocationStagingListFromGdb(
                            disposableTempFileFileInfo, httpPostedFileBase.FileName, project, CurrentFirmaSession);
                    }
                    // Run a quick test to see if the uploaded geometries are going to be reducible later.
                    // If they aren't, we can throw the SitkaGeometryDisplayErrorException to capture a record of the uploaded file.
                    var mockGeometries = project.ProjectLocationStagings.SelectMany(x =>
                                                                                    x.ToGeoJsonFeatureCollection().Features.Select(y => y.ToSqlGeometry())).ToList();
                    Check.Assert(DbSpatialHelper.CanReduce(mockGeometries), new SitkaGeometryDisplayErrorException("Could not reduce the uploaded geometries."));
                }
                catch (SitkaGeometryDisplayErrorException exception)
                {
                    string preservedFilenameFullPath = ProjectLocationStagingModelExtensions.PreserveFailedLocationImportFile(httpPostedFileBase);
                    throw new SitkaGeometryDisplayErrorException(exception.Message, preservedFilenameFullPath);
                }
            }
            return(ApproveGisUpload(project));
        }
Example #12
0
        public FileContentResult DownloadWebLogFileZipArchive()
        {
            var webLogZipFileName = "WebLogZipFile.zip";

            using (var tempFile = DisposableTempFile.MakeDisposableTempFileEndingIn(webLogZipFileName))
            {
                ZipFile.CreateFromDirectory(FirmaWebConfiguration.LogFileFolder.FullName, tempFile.FileInfo.FullName);
                var zipFileBytes = System.IO.File.ReadAllBytes(tempFile.FileInfo.FullName);
                return(File(zipFileBytes, "application/zip", webLogZipFileName));
            }
        }
        public void ImportGeoJsonToMsSql(string geoJson, string connectionString, string destinationTableName, string sourceColumnName, string destinationColumnName, string extraColumns)
        {
            var databaseConnectionString = $"MSSQL:{connectionString}";

            using (var geoJsonFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".json"))
            {
                File.WriteAllText(geoJsonFile.FileInfo.FullName, geoJson);
                var commandLineArguments = BuildCommandLineArgumentsForGeoJsonToMsSql(geoJsonFile.FileInfo,
                                                                                      sourceColumnName, destinationTableName, destinationColumnName, _gdalDataPath, databaseConnectionString, _coordinateSystemId, extraColumns);
                ExecuteOgr2OgrCommand(commandLineArguments);
            }
        }
        public void ImportGeoJsonToMsSql(string geoJson, string connectionString, string destinationTableName, string sqlSelectClause, int sourceCrsId, int targetCrsId)
        {
            var databaseConnectionString = $"MSSQL:{connectionString}";

            using (var geoJsonFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".json"))
            {
                File.WriteAllText(geoJsonFile.FileInfo.FullName, geoJson);
                var commandLineArguments = BuildCommandLineArgumentsForGeoJsonToMsSql(geoJsonFile.FileInfo,
                                                                                      destinationTableName, _gdalDataPath, databaseConnectionString, sqlSelectClause, sourceCrsId, targetCrsId);
                ExecuteOgr2OgrCommand(commandLineArguments);
            }
        }
Example #15
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var errors = new List <ValidationResult>();

            FileResource.ValidateFileSize(FileResourceData, errors, GeneralUtility.NameOf(() => FileResourceData));

            using (var disposableTempFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".gdb.zip"))
            {
                var gdbFile = disposableTempFile.FileInfo;
                FileResourceData.SaveAs(gdbFile.FullName);

                try
                {
                    var featureClassNames = OgrInfoCommandLineRunner.GetFeatureClassNamesFromFileGdb(
                        new FileInfo(NeptuneWebConfiguration.OgrInfoExecutable),
                        gdbFile,
                        Ogr2OgrCommandLineRunner.DefaultTimeOut);

                    if (featureClassNames?.Count == 0)
                    {
                        errors.Add(new ValidationResult(
                                       "The file geodatabase contained no feature class. Please upload a file geodatabase containing exactly one feature class."));
                        return(errors);
                    }

                    if (featureClassNames?.Count != 1)
                    {
                        errors.Add(new ValidationResult(
                                       "The file geodatabase contained more than one feature class. Please upload a file geodatabase containing exactly one feature class."));
                        return(errors);
                    }

                    var featureClassName = featureClassNames[0];
                    if (!OgrInfoCommandLineRunner.ConfirmAttributeExistsOnFeatureClass(
                            new FileInfo(NeptuneWebConfiguration.OgrInfoExecutable),
                            gdbFile,
                            Ogr2OgrCommandLineRunner.DefaultTimeOut, featureClassName, TreatmentBMPNameField))
                    {
                        errors.Add(new ValidationResult($"The feature class in the file geodatabase does not have an attribute named {TreatmentBMPNameField}. Please double-check the attribute name you entered and try again."));
                        return(errors);
                    }
                }
                catch (Exception e)
                {
                    SitkaLogger.Instance.LogAbridgedErrorMessage(e);
                    errors.Add(new ValidationResult(
                                   "There was a problem uploading your file geodatabase. Verify it meets the requirements and is not corrupt."));
                }
            }

            return(errors);
        }
Example #16
0
        public async Task <IActionResult> UploadGDBAndParseFeatureClasses([FromForm] IFormFile inputFile)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            byte[] inputFileContents;
            await using (var ms = new MemoryStream(4096))
            {
                await inputFile.CopyToAsync(ms);

                inputFileContents = ms.ToArray();
            }
            // save the gdb file contents to UploadedGdb so user doesn't have to wait for upload of file again
            var uploadedGdbID = UploadedGdb.CreateNew(_dbContext, inputFileContents);

            using var disposableTempFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".gdb.zip");
            var gdbFile = disposableTempFile.FileInfo;

            System.IO.File.WriteAllBytes(gdbFile.FullName, inputFileContents);

            try
            {
                var featureClassInfos = OgrInfoCommandLineRunner.GetFeatureClassInfoFromFileGdb(
                    _rioConfiguration.OgrInfoExecutable,
                    gdbFile.FullName,
                    250000000, _logger, 1);
                var uploadParcelLayerInfoDto = new UploadParcelLayerInfoDto()
                {
                    UploadedGdbID  = uploadedGdbID,
                    FeatureClasses = featureClassInfos
                };

                return(Ok(uploadParcelLayerInfoDto));
            }
            catch (System.ComponentModel.DataAnnotations.ValidationException e)
            {
                _logger.LogError(e, e.Message);
                UploadedGdb.Delete(_dbContext, uploadedGdbID);
                return(BadRequest(e.Message));
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                UploadedGdb.Delete(_dbContext, uploadedGdbID);
                return(BadRequest("Error reading GDB file!"));
            }
        }
Example #17
0
        public ActionResult <ParcelUpdateExpectedResultsDto> PreviewParcelLayerGDBChangesViaGeoJsonFeatureCollectionAndUploadToStaging([FromBody] ParcelLayerUpdateDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var waterYearDto = WaterYear.GetByWaterYearID(_dbContext, model.YearChangesToTakeEffect);

            if (waterYearDto == null)
            {
                return(BadRequest("Invalid water year selected"));
            }

            var gdbFileContents = UploadedGdb.GetUploadedGdbFileContents(_dbContext, model.UploadedGDBID);

            using var disposableTempFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".gdb.zip");
            var gdbFile = disposableTempFile.FileInfo;

            System.IO.File.WriteAllBytes(gdbFile.FullName, gdbFileContents);
            try
            {
                var ogr2OgrCommandLineRunner = new Ogr2OgrCommandLineRunner(_rioConfiguration.Ogr2OgrExecutable,
                                                                            Ogr2OgrCommandLineRunner.DefaultCoordinateSystemId,
                                                                            250000000, false);
                var columns = model.ColumnMappings.Select(
                    x =>
                    $"{x.MappedColumnName} as {x.RequiredColumnName}").ToList();
                var geoJson = ogr2OgrCommandLineRunner.ImportFileGdbToGeoJson(gdbFile.FullName,
                                                                              model.ParcelLayerNameInGDB, columns, null, _logger, null, false);
                var featureCollection = GeoJsonHelpers.GetFeatureCollectionFromGeoJsonString(geoJson, 14);
                var expectedResults   = ParcelUpdateStaging.AddFromFeatureCollection(_dbContext, featureCollection, _rioConfiguration.ValidParcelNumberRegexPattern, _rioConfiguration.ValidParcelNumberPatternAsStringForDisplay, waterYearDto);
                return(Ok(expectedResults));
            }
            catch (System.ComponentModel.DataAnnotations.ValidationException e)
            {
                _logger.LogError(e.Message);

                return(BadRequest(e.Message));
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);

                return(BadRequest("Error generating preview of changes!"));
            }
        }
Example #18
0
        public FileContentResult CostShareAgreementPdf(ProjectPersonPrimaryKey projectPersonPrimaryKey)
        {
            string blankCostSharePdfFilePath = BlankCostSharePdfFilePath();

            byte[] binaryContentsOfOutputPdfFile;
            string outputFileName;

            ProjectPerson landownerProjectPerson = projectPersonPrimaryKey.EntityObject;
            Person        landownerPerson        = landownerProjectPerson.Person;

            Check.Ensure(landownerProjectPerson.ProjectPersonRelationshipType == ProjectPersonRelationshipType.PrivateLandowner, $"Only expecting Landowner contacts here. {landownerProjectPerson.Person.FullNameFirstLast} is a {landownerProjectPerson.ProjectPersonRelationshipType} on Project {landownerProjectPerson.Project.DisplayName}.");

            using (var outputPdfFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".pdf"))
            {
                PdfDocument pdf  = new PdfDocument(new PdfReader(blankCostSharePdfFilePath), new PdfWriter(outputPdfFile.FileInfo.FullName));
                PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
                IDictionary <String, PdfFormField> fields = form.GetFormFields();

                var landownerName = landownerPerson.FullNameFirstLast;
                outputFileName = $"CostShareAgreement-{landownerName.Replace(" ", "")}.pdf";

                fields.TryGetValue("Names", out var nameToSet);
                nameToSet?.SetValue(MakeEmptyStringForNullString(landownerName));

                fields.TryGetValue("Address1", out var address1);
                address1?.SetValue(MakeEmptyStringForNullString(landownerPerson.PersonAddress));

                fields.TryGetValue("Address2", out var address2);
                address2?.SetValue(MakeEmptyStringForNullString(string.Empty));

                fields.TryGetValue("PhoneNumber", out var phoneToSet);
                phoneToSet?.SetValue(MakeEmptyStringForNullString(landownerPerson.Phone));

                fields.TryGetValue("Email", out var emailToSet);
                emailToSet?.SetValue(MakeEmptyStringForNullString(landownerPerson.Email));

                form.FlattenFields();
                pdf.Close();

                binaryContentsOfOutputPdfFile = System.IO.File.ReadAllBytes(outputPdfFile.FileInfo.FullName);
            }

            return(File(binaryContentsOfOutputPdfFile, "application/pdf", outputFileName));
        }
        public static Tuple <double, double, double, double> GetExtentFromGeoJson(FileInfo ogrInfoFileInfo, string geoJson, double totalMilliseconds)
        {
            using (var geoJsonFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".json"))
            {
                File.WriteAllText(geoJsonFile.FileInfo.FullName, geoJson);

                var gdalDataDirectory    = new DirectoryInfo(Path.Combine(ogrInfoFileInfo.DirectoryName, "gdal-data"));
                var commandLineArguments = BuildOgrInfoCommandLineArgumentsGetExtent(geoJsonFile.FileInfo, gdalDataDirectory);
                var processUtilityResult = ProcessUtility.ShellAndWaitImpl(ogrInfoFileInfo.DirectoryName, ogrInfoFileInfo.FullName, commandLineArguments, true, Convert.ToInt32(totalMilliseconds));

                var lines = processUtilityResult.StdOut.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                if (lines.Any(x => x.Contains("Feature Count: 0")))
                {
                    return(null);
                }

                var extentTokens = lines.First(x => x.StartsWith("Extent:")).Split(new[] { ' ', '(', ')', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                return(new Tuple <double, double, double, double>(double.Parse(extentTokens[1]), double.Parse(extentTokens[2]), double.Parse(extentTokens[4]), double.Parse(extentTokens[5])));
            }
        }
Example #20
0
        public bool UpdateModel(Person currentPerson)
        {
            HttpRequestStorage.DatabaseEntities.DelineationStagings.DeleteDelineationStaging(currentPerson.DelineationStagingsWhereYouAreTheUploadedByPerson);
            HttpRequestStorage.DatabaseEntities.SaveChanges();

            using (var disposableTempFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".gdb.zip"))
            {
                var gdbFile = disposableTempFile.FileInfo;
                FileResourceData.SaveAs(gdbFile.FullName);

                var ogr2OgrCommandLineRunner = new Ogr2OgrCommandLineRunner(NeptuneWebConfiguration.Ogr2OgrExecutable,
                                                                            Ogr2OgrCommandLineRunner.DefaultCoordinateSystemId,
                                                                            NeptuneWebConfiguration.HttpRuntimeExecutionTimeout.TotalMilliseconds * 10);

                try
                {
                    var featureClassNames = OgrInfoCommandLineRunner.GetFeatureClassNamesFromFileGdb(new FileInfo(NeptuneWebConfiguration.OgrInfoExecutable),
                                                                                                     gdbFile,
                                                                                                     Ogr2OgrCommandLineRunner.DefaultTimeOut);
                    if (featureClassNames != null)
                    {
                        var columns = new List <string>
                        {
                            $"{currentPerson.PersonID} as UploadedByPersonID",
                            $"{TreatmentBMPNameField} as TreatmentBMPName",
                            $"{StormwaterJurisdictionID} as StormwaterJurisdictionID"
                        };
                        ogr2OgrCommandLineRunner.ImportFileGdbToMsSql(gdbFile, featureClassNames[0], "DelineationStaging", columns,
                                                                      NeptuneWebConfiguration.DatabaseConnectionString, true, Ogr2OgrCommandLineRunner.GEOMETRY_TYPE_POLYGON);
                    }
                }
                catch (Exception e)
                {
                    SitkaLogger.Instance.LogAbridgedErrorMessage(e);
                    return(false);
                }
            }

            return(true);
        }
        public FileResult Download(RegionalSubbasinRevisionRequestPrimaryKey regionalSubbasinRevisionRequestPrimaryKey)
        {
            var geometry = regionalSubbasinRevisionRequestPrimaryKey.EntityObject
                           .RegionalSubbasinRevisionRequestGeometry;

            var reprojectedGeometry = CoordinateSystemHelper.ProjectWebMercatorTo2230(geometry);

            var geoJson = DbGeometryToGeoJsonHelper.FromDbGeometryWithNoReproject(reprojectedGeometry);

            var serializedGeoJson = JsonConvert.SerializeObject(geoJson);

            var outputLayerName = $"BMP_{regionalSubbasinRevisionRequestPrimaryKey.EntityObject.TreatmentBMP.TreatmentBMPID}_RevisionRequest";

            using (var workingDirectory = new DisposableTempDirectory())
            {
                var outputPathForLayer =
                    Path.Combine(workingDirectory.DirectoryInfo.FullName, outputLayerName);


                var ogr2OgrCommandLineRunner = new Ogr2OgrCommandLineRunner(NeptuneWebConfiguration.Ogr2OgrExecutable,
                                                                            CoordinateSystemHelper.NAD_83_CA_ZONE_VI_SRID,
                                                                            NeptuneWebConfiguration.HttpRuntimeExecutionTimeout.TotalMilliseconds);

                ogr2OgrCommandLineRunner.ImportGeoJsonToFileGdb(serializedGeoJson, outputPathForLayer,
                                                                outputLayerName, false, true);

                using (var zipFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".zip"))
                {
                    ZipFile.CreateFromDirectory(workingDirectory.DirectoryInfo.FullName, zipFile.FileInfo.FullName);
                    var fileStream = zipFile.FileInfo.OpenRead();
                    var bytes      = fileStream.ReadFully();
                    fileStream.Close();
                    fileStream.Dispose();
                    return(File(bytes, "application/zip", $"{outputLayerName}.zip"));
                }
            }
        }
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var currentPerson = HttpRequestStorage.DatabaseEntities.People.Find(PersonID);

            HttpRequestStorage.DatabaseEntities.pLandUseBlockStagingDeleteByPersonID(currentPerson.PersonID);
            var errors = new List <ValidationResult>();

            FileResource.ValidateFileSize(FileResourceData, errors, GeneralUtility.NameOf(() => FileResourceData));

            using (var disposableTempFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".gdb.zip"))
            {
                var gdbFile = disposableTempFile.FileInfo;
                FileResourceData.SaveAs(gdbFile.FullName);

                var ogr2OgrCommandLineRunner = new Ogr2OgrCommandLineRunner(NeptuneWebConfiguration.Ogr2OgrExecutable,
                                                                            Ogr2OgrCommandLineRunner.DefaultCoordinateSystemId,
                                                                            NeptuneWebConfiguration.HttpRuntimeExecutionTimeout.TotalMilliseconds * 10);

                List <string> featureClassNames = null;
                try
                {
                    featureClassNames = OgrInfoCommandLineRunner.GetFeatureClassNamesFromFileGdb(new FileInfo(NeptuneWebConfiguration.OgrInfoExecutable),
                                                                                                 gdbFile,
                                                                                                 Ogr2OgrCommandLineRunner.DefaultTimeOut);
                }
                catch (Exception e)
                {
                    errors.Add(new ValidationResult("There was a problem uploading your file geodatabase. Verify it meets the requirements and is not corrupt."));
                    SitkaLogger.Instance.LogDetailedErrorMessage(e);
                }

                if (featureClassNames != null)
                {
                    if (featureClassNames.Count == 0)
                    {
                        errors.Add(new ValidationResult("The file geodatabase contained no feature class. Please upload a file geodatabase containing exactly one feature class."));
                        return(errors);
                    }

                    if (featureClassNames.Count != 1)
                    {
                        errors.Add(new ValidationResult("The file geodatabase contained more than one feature class. Please upload a file geodatabase containing exactly one feature class."));
                        return(errors);
                    }

                    try
                    {
                        var columns = new List <string>
                        {
                            "PLU_Cat as PriorityLandUseType",
                            "LU_Descr as LandUseDescription",
                            "TGR as TrashGenerationRate",
                            "LU_for_TGR as LandUseForTGR",
                            "MHI as MedianHouseHoldIncome",
                            "Jurisdic as StormwaterJurisdiction",
                            "Permit as PermitType",
                            $"{PersonID} as UploadedByPersonID"
                        };
                        ogr2OgrCommandLineRunner.ImportFileGdbToMsSql(gdbFile, featureClassNames[0],
                                                                      "LandUseBlockStaging", columns,
                                                                      NeptuneWebConfiguration.DatabaseConnectionString, true,
                                                                      Ogr2OgrCommandLineRunner.GEOMETRY_TYPE_POLYGON);
                    }
                    catch (Ogr2OgrCommandLineException e)
                    {
                        if (e.Message.Contains("column does not allow nulls",
                                               StringComparison.InvariantCultureIgnoreCase))
                        {
                            errors.Add(new ValidationResult("The upload contained features with null values. All fields are required."));
                        }
                        else if (e.Message.Contains("Unrecognised field name",
                                                    StringComparison.InvariantCultureIgnoreCase))
                        {
                            errors.Add(new ValidationResult("The columns in the uploaded file did not match the Land Use Block schema. The file is invalid and cannot be uploaded."));
                        }
                        else
                        {
                            errors.Add(new ValidationResult($"There was a problem processing the Feature Class \"{featureClassNames[0]}\". The file may be corrupted or invalid."));
                            SitkaLogger.Instance.LogDetailedErrorMessage(e);
                        }
                    }
                    catch (Exception e)
                    {
                        errors.Add(new ValidationResult($"There was a problem processing the Feature Class \"{featureClassNames[0]}\". Feature Classes must contain Polygon and/or Multi-Polygon features."));
                        SitkaLogger.Instance.LogDetailedErrorMessage(e);
                    }
                }
            }

            return(errors);
        }