Example #1
0
        public WaterYearReport(TimeSeriesDatabase db,
                               string siteid, string parameter,
                               int start = 0, int end = 0, string format = "usgs-html")
        {
            this.db        = db;
            this.siteid    = siteid;
            this.parameter = parameter;
            this.format    = format;
            Validation(siteid, parameter);

            if (start <= 0)
            { // default start
                start = DateTime.Now.Date.Year;

                if (DateTime.Now.Date.Month >= 10)
                {
                    start = DateTime.Now.Date.Year + 1;
                }
            }
            if (end <= 0)
            {
                end = DateTime.Now.Date.Year;
            }

            //creates a water year time range between the selected dates y1, y2
            r = new TimeRange(
                WaterYear.BeginningOfWaterYear(new DateTime(start, 1, 1)),
                WaterYear.EndOfWaterYear(new DateTime(end, 1, 1)));
        }
Example #2
0
        private static TimeRange GetDateRange(NameValueCollection collection)
        {
            var start = "";

            if (collection.AllKeys.Contains("start"))
            {
                start = collection["start"];
            }
            var end = "";

            if (collection.AllKeys.Contains("end"))
            {
                end = collection["end"];
            }

            int y1 = 0, y2 = 0;

            if (!int.TryParse(start, out y1) || !int.TryParse(end, out y2))
            {
                StopWithError("Error with year range");
            }
            //creates a water year time range between the selected dates y1, y2
            var rval = new TimeRange(
                WaterYear.BeginningOfWaterYear(new DateTime(y1, 1, 1)),
                WaterYear.EndOfWaterYear(new DateTime(y2, 1, 1)));

            return(rval);
        }
Example #3
0
        public ActionResult <ParcelDto> GetByParcelID([FromRoute] int parcelID)
        {
            var currentUser = UserContext.GetUserFromHttpContext(_dbContext, HttpContext);

            if (currentUser == null)
            {
                return(Forbid());
            }

            if (currentUser != null &&
                currentUser.Role.RoleID == (int)RoleEnum.LandOwner)
            {
                var currentYear    = WaterYear.GetDefaultYearToDisplay(_dbContext);
                var parcelsForUser = Parcel.ListByUserID(_dbContext, currentUser.UserID, currentYear.Year);

                if (!parcelsForUser.Any() || parcelsForUser.All(x => x.ParcelID != parcelID))
                {
                    return(Forbid());
                }
            }

            var parcelDto = Parcel.GetByParcelID(_dbContext, parcelID);

            return(RequireNotNullThrowNotFound(parcelDto, "Parcel", parcelID));
        }
Example #4
0
        public ActionResult <IEnumerable <ParcelOwnershipDto> > ChangeOwner([FromRoute] int parcelID, [FromBody] ParcelChangeOwnerDto parcelChangeOwnerDto)
        {
            var parcelDto = Parcel.GetByParcelID(_dbContext, parcelID);

            if (ThrowNotFound(parcelDto, "Parcel", parcelID, out var actionResult))
            {
                return(actionResult);
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var waterYearsToUpdate = parcelChangeOwnerDto.ApplyToSubsequentYears
                ? WaterYear.GetSubsequentWaterYearsInclusive(_dbContext, parcelChangeOwnerDto.EffectiveWaterYearID).Select(x => x.WaterYearID)
                : new List <int> {
                parcelChangeOwnerDto.EffectiveWaterYearID
            };

            AccountParcelWaterYear.ChangeParcelOwnerForWaterYears(_dbContext, parcelChangeOwnerDto.ParcelID, waterYearsToUpdate, parcelChangeOwnerDto.AccountID);

            Parcel.UpdateParcelStatus(_dbContext, parcelChangeOwnerDto.ParcelID, parcelChangeOwnerDto.AccountID.HasValue ? (int)ParcelStatusEnum.Active : (int)ParcelStatusEnum.Inactive);

            //If the Parcel was in the AccountReconciliation table, we can remove it
            AccountReconciliation.DeleteByParcelID(_dbContext, parcelID);

            return(Ok());
        }
Example #5
0
        public ActionResult <List <WaterYearDto> > GetWaterYearForCurrentYearAndVariableYearsBack([FromRoute] int numYearsBackToInclude)
        {
            var endYear    = DateTime.Now.Year;
            var startYear  = endYear - numYearsBackToInclude;
            var waterYears = WaterYear.ListBetweenYears(_dbContext, startYear, endYear);

            return(Ok(waterYears));
        }
Example #6
0
        public ActionResult <WaterYearDto> FinalizeWaterYear([FromBody] int waterYearID)
        {
            var waterYearDto = WaterYear.GetByWaterYearID(_dbContext, waterYearID);

            if (ThrowNotFound(waterYearDto, "Water Year", waterYearID, out var actionResult))
            {
                return(actionResult);
            }

            var finalizedWaterYearDto = WaterYear.Finalize(_dbContext, waterYearID);

            return(Ok(finalizedWaterYearDto));
        }
Example #7
0
        public ActionResult <List <OpenETSyncHistoryDto> > GetAbbreviatedSyncHistoryForWaterYears()
        {
            var waterYears = WaterYear.List(_dbContext);

            if (waterYears == null || waterYears.Count == 0)
            {
                //We just have no water years
                return(Ok(null));
            }

            var waterYearQuickOpenETHistoryDtos =
                waterYears.Select(x => OpenETSyncHistory.GetQuickHistoryForWaterYear(_dbContext, x.WaterYearID)).ToList();

            return(Ok(waterYearQuickOpenETHistoryDtos));
        }
Example #8
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 #9
0
        public ActionResult <int> GetDefaultWaterYearToDisplay()
        {
            var waterYearToDisplay = WaterYear.GetDefaultYearToDisplay(_dbContext);

            return(Ok(waterYearToDisplay));
        }
Example #10
0
        public ActionResult <List <WaterYearDto> > GetNonFinalizedWaterYears()
        {
            var nonFinalizedWaterYears = WaterYear.ListNonFinalized(_dbContext);

            return(Ok(nonFinalizedWaterYears));
        }
Example #11
0
        public ActionResult <List <WaterYearDto> > GetWaterYears()
        {
            var waterYears = WaterYear.List(_dbContext);

            return(Ok(waterYears));
        }
Example #12
0
        public static HttpResponseMessage TriggerOpenETGoogleBucketRefresh(RioConfiguration rioConfiguration,
                                                                           RioDbContext rioDbContext, int waterYearID)
        {
            if (!rioConfiguration.AllowOpenETSync)
            {
                return(new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.BadRequest,
                    Content = new StringContent("Syncing with OpenET is not enabled at this time")
                });
            }

            var waterYearDto = WaterYear.GetByWaterYearID(rioDbContext, waterYearID);

            if (waterYearDto == null)
            {
                return(new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.BadRequest,
                    Content = new StringContent("Requested Water Year not found")
                });
            }

            var year = waterYearDto.Year;

            if (rioDbContext.OpenETSyncHistory
                .Include(x => x.WaterYear)
                .Any(x => x.WaterYear.Year == year && x.OpenETSyncResultTypeID == (int)OpenETSyncResultTypeEnum.InProgress))
            {
                return(new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.BadRequest,
                    Content = new StringContent($"Sync already in progress for {year}")
                });
            }

            var newSyncHistory = OpenETSyncHistory.New(rioDbContext, year);

            if (!RasterUpdatedSinceMinimumLastUpdatedDate(rioConfiguration, rioDbContext, year, newSyncHistory))
            {
                return(new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.UnprocessableEntity,
                    Content = new StringContent($"The request was successful, however the sync for {year} will not be completed for the following reason: {OpenETSyncHistory.GetByOpenETSyncHistoryID(rioDbContext, newSyncHistory.OpenETSyncHistoryID).OpenETSyncResultType.OpenETSyncResultTypeDisplayName}")
                });
            }

            var openETRequestURL =
                $"{rioConfiguration.OpenETTriggerTimeSeriesBaseURL}?shapefile_fn={rioConfiguration.OpenETShapefilePath}&start_date={new DateTime(year, 1, 1):yyyy-MM-dd}&end_date={new DateTime(year, 12, 31):yyyy-MM-dd}&model=ensemble&vars=et&aggregation_type=mean&api_key={rioConfiguration.OpenETAPIKey}&to_cloud=openet_raster_api_storage&suffix={newSyncHistory.GetFileSuffixForOpenETSyncHistoryDto(rioConfiguration.LeadOrganizationShortName)}&out_columns=ParcelNumb";

            var httpClient = new HttpClient
            {
                Timeout = new TimeSpan(60 * TimeSpan.TicksPerSecond)
            };

            var responseResult = httpClient.GetAsync(openETRequestURL).Result;

            if (!responseResult.IsSuccessStatusCode)
            {
                OpenETSyncHistory.UpdateSyncResultByID(rioDbContext, newSyncHistory.OpenETSyncHistoryID,
                                                       OpenETSyncResultTypeEnum.Failed);
            }

            return(responseResult);
        }
Example #13
0
        public ActionResult EnactGDBChanges([FromBody] int waterYearID)
        {
            var waterYearDto = WaterYear.GetByWaterYearID(_dbContext, waterYearID);

            if (waterYearDto == null)
            {
                return(BadRequest(
                           "There was an error applying these changes to the selected Water Year. Please try again, and if the problem persists contact support."));
            }

            var currentWaterYearDto = WaterYear.GetDefaultYearToDisplay(_dbContext);

            if (currentWaterYearDto.Year - waterYearDto.Year > 1)
            {
                return(BadRequest(
                           "Changes may only be applied to the current year or the previous year. Please update Water Year selection and try again."));
            }

            if (waterYearDto.Year != currentWaterYearDto.Year && currentWaterYearDto.ParcelLayerUpdateDate != null)
            {
                return(BadRequest(
                           "Because changes have been applied to the current year previously, you may only select the current year to apply these changes to. Please update Water Year selection and try again."));
            }

            using var dbContextTransaction = _dbContext.Database.BeginTransaction();

            try
            {
                var expectedResults = ParcelUpdateStaging.GetExpectedResultsDto(_dbContext, waterYearDto);

                if (expectedResults.NumAccountsToBeInactivated > 0 || expectedResults.NumAccountsToBeCreated > 0)
                {
                    var currentDifferencesForAccounts =
                        _dbContext.vParcelLayerUpdateDifferencesInParcelsAssociatedWithAccount.Where(x =>
                                                                                                     !x.WaterYearID.HasValue || x.WaterYearID == waterYearDto.WaterYearID);

                    var accountNamesToCreate = currentDifferencesForAccounts
                                               .Where(
                        x =>
                        !x.AccountAlreadyExists.Value)
                                               .Select(x => x.AccountName)
                                               .ToList();

                    Account.BulkCreateWithListOfNames(_dbContext, _rioConfiguration.VerificationKeyChars,
                                                      accountNamesToCreate);

                    var accountNamesToInactivate = currentDifferencesForAccounts
                                                   .Where(x => (x.AccountAlreadyExists.Value &&
                                                                !IsNullOrEmpty(x.ExistingParcels) && IsNullOrEmpty(x.UpdatedParcels)) || (!x.AccountAlreadyExists.Value && IsNullOrEmpty(x.UpdatedParcels))).Select(x => x.AccountName).ToList();
                    Account.BulkInactivate(_dbContext, _dbContext.Account
                                           .Where(x => accountNamesToInactivate.Contains(x.AccountName))
                                           .ToList());
                }

                _dbContext.Database.ExecuteSqlRaw(
                    "EXECUTE dbo.pUpdateParcelLayerAddParcelsUpdateAccountParcelAndUpdateParcelGeometry {0}", waterYearDto.WaterYearID);

                WaterYear.UpdateParcelLayerUpdateDateForID(_dbContext, waterYearID);

                dbContextTransaction.Commit();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                dbContextTransaction.Rollback();
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }

            return(Ok());
        }