Example #1
0
        /// <summary>
        /// Get the species observation count from web service
        /// </summary>
        /// <returns>No of observations that matches my settings.</returns>
        private TimeStepSpeciesObservationCountList GetSpeciesObservationCountFromWebService(IUserContext userContext, int periodicityId)
        {
            var searchCriteriaManager = new SpeciesObservationSearchCriteriaManager(userContext);
            SpeciesObservationSearchCriteria searchCriteria = searchCriteriaManager.CreateSearchCriteria(MySettings);

            if (userContext.CurrentRole.IsNull() && userContext.CurrentRoles.Count > 0)
            {
                userContext.CurrentRole = userContext.CurrentRoles[0];
            }

            var displayCoordinateSystem = MySettings.Presentation.Map.DisplayCoordinateSystem;

            //TODO: undersök om detta kan tas bort. Fråga Agneta varför Id istället för de faktiska enum
            Periodicity timeStepType = Periodicity.Yearly;

            foreach (Periodicity value in Enum.GetValues(typeof(Periodicity)))
            {
                if ((int)value == periodicityId)
                {
                    timeStepType = value;
                    break;
                }
            }

            TimeStepSpeciesObservationCountList speciesObservationCount = CoreData.AnalysisManager.GetTimeSpeciesObservationCounts(userContext, searchCriteria, timeStepType, displayCoordinateSystem);

            return(speciesObservationCount);
        }
        public void GetTaxa()
        {
            DarwinCoreList    speciesObservations;
            ICoordinateSystem coordinateSystem;
            ISpeciesObservationSearchCriteria    searchCriteria;
            SpeciesObservationFieldSortOrderList sortOrder;
            TaxonList taxa;

            speciesObservations = new DarwinCoreList();
            taxa = speciesObservations.GetTaxa(GetUserContext());
            Assert.IsTrue(taxa.IsEmpty());

            searchCriteria = new SpeciesObservationSearchCriteria();
            searchCriteria.AddTaxon((Int32)(TaxonId.Mammals));
            searchCriteria.ObservationDateTime          = new DateTimeSearchCriteria();
            searchCriteria.ObservationDateTime.Begin    = new DateTime(2015, 3, 1);
            searchCriteria.ObservationDateTime.End      = new DateTime(2015, 3, 2);
            searchCriteria.ObservationDateTime.Operator = CompareOperator.Excluding;
            coordinateSystem    = new CoordinateSystem();
            coordinateSystem.Id = CoordinateSystemId.SWEREF99_TM;
            sortOrder           = null;
            speciesObservations = CoreData.SpeciesObservationManager.GetDarwinCore(GetUserContext(), searchCriteria, coordinateSystem, sortOrder);
            taxa = speciesObservations.GetTaxa(GetUserContext());
            Assert.IsTrue(taxa.IsNotEmpty());
            foreach (IDarwinCore specieObservation in speciesObservations)
            {
                Assert.IsTrue(taxa.Contains(specieObservation.Taxon.DyntaxaTaxonID));
            }
        }
Example #3
0
        protected long CalculateTotalCount(int?taxonId, Polygon bbox)
        {
            var searchCriteriaManager = new SpeciesObservationSearchCriteriaManager(UserContext);
            SpeciesObservationSearchCriteria searchCriteria = searchCriteriaManager.CreateSearchCriteria(MySettings);

            if (taxonId.HasValue)
            {
                searchCriteria.TaxonIds = new List <int> {
                    taxonId.Value
                };
            }
            if (bbox != null)
            {
                searchCriteria.Polygons = new List <IPolygon> {
                    bbox
                };
            }

            if (UserContext.CurrentRole.IsNull() && UserContext.CurrentRoles.Count > 0)
            {
                UserContext.CurrentRole = UserContext.CurrentRoles[0];
            }

            var  displayCoordinateSystem = MySettings.Presentation.Map.DisplayCoordinateSystem;
            long speciesObservationCount = CoreData.AnalysisManager.GetSpeciesObservationCountBySearchCriteria(UserContext, searchCriteria, displayCoordinateSystem);

            return(speciesObservationCount);
        }
Example #4
0
        public IList <IGridCellSpeciesObservationCount> GetSpeciesObservationGridCellResultFromWebService(IUserContext userContext, MySettings mySettings)
        {
            var speciesObservationSearchCriteriaManager     = new SpeciesObservationSearchCriteriaManager(userContext);
            SpeciesObservationSearchCriteria searchCriteria = speciesObservationSearchCriteriaManager.CreateSearchCriteria(mySettings);
            ICoordinateSystem coordinateSystem = new CoordinateSystem();

            coordinateSystem.Id = CoordinateSystemId.GoogleMercator;
            GridStatisticsSetting gridStatisticsSetting = mySettings.Calculation.GridStatistics;
            IGridSpecification    gridSpecification     = new GridSpecification();

            if (gridStatisticsSetting.CoordinateSystemId.HasValue)
            {
                gridSpecification.GridCoordinateSystem = (GridCoordinateSystem)gridStatisticsSetting.CoordinateSystemId;
            }
            else
            {
                gridSpecification.GridCoordinateSystem = GridCoordinateSystem.SWEREF99_TM;
            }

            if (gridStatisticsSetting.GridSize.HasValue)
            {
                gridSpecification.GridCellSize            = gridStatisticsSetting.GridSize.Value;
                gridSpecification.IsGridCellSizeSpecified = true;
            }
            IList <IGridCellSpeciesObservationCount> gridCellObservations = CoreData.AnalysisManager.GetGridSpeciesObservationCounts(userContext, searchCriteria, gridSpecification, coordinateSystem);

            // Add result to cache
            return(gridCellObservations);
        }
Example #5
0
        /// <summary>
        /// Calculates the combined grid result.
        /// </summary>
        /// <param name="calculationCoordinateSystemId">The calculation coordinate system id.</param>
        /// <param name="gridCellSize">Size of the grid cell.</param>
        /// <param name="wfsLayerId">The WFS layer id.</param>
        /// <returns>Combined grid cell statistics.</returns>
        public CombinedGridStatisticsResult CalculateCombinedGridResult(int calculationCoordinateSystemId, int gridCellSize, int wfsLayerId)
        {
            GridSpecification gridSpecification       = new GridSpecification();
            CoordinateSystem  displayCoordinateSystem = MySettings.Presentation.Map.DisplayCoordinateSystem;

            gridSpecification.GridCoordinateSystem    = (GridCoordinateSystem)calculationCoordinateSystemId;
            gridSpecification.GridCellSize            = gridCellSize;
            gridSpecification.IsGridCellSizeSpecified = true;
            gridSpecification.GridCellGeometryType    = GridCellGeometryType.Polygon;
            if (MySettings.Filter.Spatial.IsActive)
            {
                // Create bounding box from spatial filter
                ObservableCollection <DataPolygon> polygons = MySettings.Filter.Spatial.Polygons;
                if (polygons.Count > 0)
                {
                    BoundingBox      boundingBox                 = polygons.GetBoundingBox();
                    CoordinateSystem toCoordinateSystem          = CoordinateSystemHelper.GetCoordinateSystemFromGridCoordinateSystem(gridSpecification.GridCoordinateSystem);
                    IPolygon         convertedBoundingBoxPolygon = GisTools.CoordinateConversionManager.GetConvertedBoundingBox(boundingBox, MySettings.Filter.Spatial.PolygonsCoordinateSystem, toCoordinateSystem);
                    BoundingBox      convertedBoundingBox        = convertedBoundingBoxPolygon.GetBoundingBox();
                    gridSpecification.BoundingBox = convertedBoundingBox;
                }
            }

            WfsLayerSetting wfsLayer              = SessionHandler.MySettings.DataProvider.MapLayers.WfsLayers.FirstOrDefault(l => l.Id == wfsLayerId);
            string          featuresUrl           = "";
            string          featureCollectionJson = null;

            if (wfsLayer.IsFile)
            {
                featureCollectionJson = JObject.FromObject(MySettingsManager.GetMapDataFeatureCollection(UserContext, wfsLayer.GeometryName, gridSpecification.GridCoordinateSystem.GetCoordinateSystemId())).ToString();
            }
            else
            {
                if (string.IsNullOrEmpty(wfsLayer.Filter))
                {
                    featuresUrl = string.Format("{0}?service=wfs&version=1.1.0&request=GetFeature&typeName={1}",
                                                wfsLayer.ServerUrl, wfsLayer.TypeName);
                }
                else
                {
                    featuresUrl =
                        string.Format("{0}?service=wfs&version=1.1.0&request=GetFeature&typeName={1}&filter={2}",
                                      wfsLayer.ServerUrl, wfsLayer.TypeName, wfsLayer.Filter);
                }
            }
            var speciesObservationSearchCriteriaManager        = new SpeciesObservationSearchCriteriaManager(UserContext);
            SpeciesObservationSearchCriteria    searchCriteria = speciesObservationSearchCriteriaManager.CreateSearchCriteria(MySettings);
            IList <IGridCellCombinedStatistics> gridCells      = CoreData.AnalysisManager.GetGridCellFeatureStatisticsCombinedWithSpeciesObservationCounts(UserContext, gridSpecification, searchCriteria, null, featuresUrl, featureCollectionJson, displayCoordinateSystem);

            if (MySettings.Calculation.GridStatistics.GenerateAllGridCells)
            {
                gridCells = AddEmptyGridCells(gridCells, gridSpecification, displayCoordinateSystem);
                gridCells = RemoveGridCellsOutsideBounds(gridCells, gridSpecification);
            }

            gridCells = gridCells.OrderBy(x => x.Identifier).ToList();
            return(CombinedGridStatisticsResult.Create(
                       (CoordinateSystemId)calculationCoordinateSystemId, displayCoordinateSystem.Id, gridCellSize, gridCells));
        }
Example #6
0
        /// <summary>
        /// Calculates the species observation grid.
        /// </summary>
        /// <param name="taxonIds">The taxon ids.</param>
        /// <param name="gridCoordinateSystem">The grid coordinate system.</param>
        /// <returns>List of grid cells data.</returns>
        public IList <IGridCellSpeciesObservationCount> CalculateSpeciesObservationGrid(List <int> taxonIds, GridCoordinateSystem?gridCoordinateSystem)
        {
            var speciesObservationSearchCriteriaManager     = new SpeciesObservationSearchCriteriaManager(UserContext);
            SpeciesObservationSearchCriteria searchCriteria = speciesObservationSearchCriteriaManager.CreateSearchCriteria(MySettings);

            searchCriteria.TaxonIds = taxonIds;

            CoordinateSystem displayCoordinateSystem = MySettings.Presentation.Map.DisplayCoordinateSystem;
            //CoordinateSystem displayCoordinateSystem = new CoordinateSystem(MapSettings.CoordinateSystemId); // todo - såhär borde det se ut
            GridStatisticsSetting gridStatisticsSetting = MySettings.Calculation.GridStatistics;
            GridSpecification     gridSpecification     = new GridSpecification();

            if (gridCoordinateSystem.HasValue)
            {
                gridSpecification.GridCoordinateSystem = gridCoordinateSystem.Value;
            }
            else
            {
                if (gridStatisticsSetting.CoordinateSystemId.HasValue)
                {
                    gridSpecification.GridCoordinateSystem = (GridCoordinateSystem)gridStatisticsSetting.CoordinateSystemId;
                }
                else
                {
                    gridSpecification.GridCoordinateSystem = GridCoordinateSystem.SWEREF99_TM;
                }
            }

            if (gridStatisticsSetting.GridSize.HasValue)
            {
                gridSpecification.GridCellSize            = gridStatisticsSetting.GridSize.Value;
                gridSpecification.IsGridCellSizeSpecified = true;
            }

            gridSpecification.GridCellGeometryType = GridCellGeometryType.Polygon;

            // todo - implement check that the number of possible grid cells aren't too large.
            // todo - perhaps this check should be in the service
            ////long numberOfGridCellsThatWillBeGenerated = GisTools.GridCellManager.CalculateNumberOfGridCells(gridSpecification, searchCriteria.Polygons, searchCriteria.RegionGuids);
            ////if (numberOfGridCellsThatWillBeGenerated > MAX_NUMBER_OF_GRID_CELLS)
            ////{
            ////    throw new ArgumentException(string.Format("The cell size is too small, which would have resulted in possibly {0} grid cells. The limit lies at {1}.", numberOfGridCellsThatWillBeGenerated, MAX_NUMBER_OF_GRID_CELLS));
            ////}

            var gridCellObservations = CoreData.AnalysisManager.GetGridSpeciesObservationCounts(UserContext, searchCriteria, gridSpecification, displayCoordinateSystem);

            if (MySettings.Calculation.GridStatistics.GenerateAllGridCells)
            {
                gridCellObservations = AddEmptyGridCells(gridCellObservations, gridSpecification, displayCoordinateSystem);
                gridCellObservations = RemoveGridCellsOutsideBounds(gridCellObservations, gridSpecification);
            }

            gridCellObservations = gridCellObservations.OrderBy(x => x.Identifier).ToList();
            return(gridCellObservations);
        }
Example #7
0
        /// <summary>
        /// Calculates species observation count per polygon and taxa.
        /// </summary>
        /// <param name="taxonIds">The taxon ids.</param>
        /// <returns>
        /// A dictionary where the key is a polygon description.
        /// The value is a dictionary where the key is TaxonId and the value is species observation count.
        /// </returns>
        public TaxonSpecificSpeciesObservationCountPerPolygonResult CalculateSpeciesObservationCountPerPolygonAndTaxa(List <int> taxonIds)
        {
            Dictionary <string, Dictionary <int, long> > speciesObservationData = new Dictionary <string, Dictionary <int, long> >();
            FeatureCollection featureCollection = GetFeatureCollection();
            List <int>        taxonIdList       = new List <int>(taxonIds);

            if (taxonIdList.IsEmpty())
            {
                taxonIdList.Add(0);
            }

            if (MySettings.Calculation.SummaryStatistics.WfsSummaryStatisticsLayerId.HasValue &&
                featureCollection != null && featureCollection.Features.Count > 0)
            {
                SpeciesObservationSearchCriteriaManager searchCriteriaManager =
                    new SpeciesObservationSearchCriteriaManager(UserContext);
                SpeciesObservationSearchCriteria searchCriteria = searchCriteriaManager.CreateSearchCriteria(MySettings);
                DataContext      dataContext             = new DataContext(UserContext);
                CoordinateSystem displayCoordinateSystem = MySettings.Presentation.Map.DisplayCoordinateSystem;

                foreach (Feature feature in featureCollection.Features)
                {
                    string             featureDescription = GetFeatureDescription(feature);
                    List <DataPolygon> dataPolygons       = GetDataPolygons(feature);
                    searchCriteria.Polygons = dataPolygons.ToPolygons(dataContext);

                    foreach (int taxonId in taxonIdList)
                    {
                        searchCriteria.TaxonIds = new List <int>();
                        searchCriteria.TaxonIds.Add(taxonId);

                        long speciesObservationCount = CoreData.AnalysisManager.GetSpeciesObservationCountBySearchCriteria(UserContext, searchCriteria, displayCoordinateSystem);
                        if (!speciesObservationData.ContainsKey(featureDescription))
                        {
                            speciesObservationData.Add(featureDescription, new Dictionary <int, long>());
                        }

                        speciesObservationData[featureDescription].Add(taxonId, speciesObservationCount);
                    }
                }
            }

            TaxonList             taxonList = CoreData.TaxonManager.GetTaxa(UserContext, taxonIdList);
            List <TaxonViewModel> taxaList  = taxonList.GetGenericList().ToTaxonViewModelList();
            TaxonSpecificSpeciesObservationCountPerPolygonResult result = new TaxonSpecificSpeciesObservationCountPerPolygonResult()
            {
                Taxa = taxaList,
                SpeciesObservationCountPerPolygon = speciesObservationData
            };

            return(result);
        }
Example #8
0
        /// <summary>
        /// Get the species count from web service
        /// </summary>
        /// <returns>No of species that matches my settings.</returns>
        private long GetSpeciesCountFromWebService(IUserContext userContext)
        {
            var searchCriteriaManager = new SpeciesObservationSearchCriteriaManager(userContext);
            SpeciesObservationSearchCriteria searchCriteria = searchCriteriaManager.CreateSearchCriteria(MySettings);

            if (userContext.CurrentRole.IsNull() && userContext.CurrentRoles.Count > 0)
            {
                userContext.CurrentRole = userContext.CurrentRoles[0];
            }

            var  displayCoordinateSystem = MySettings.Presentation.Map.DisplayCoordinateSystem;
            long speciesCount            = CoreData.AnalysisManager.GetSpeciesCountBySearchCriteria(userContext, searchCriteria, displayCoordinateSystem);

            return(speciesCount);
        }
Example #9
0
        /// <summary>
        /// Get the species observation provenances from web service.
        /// </summary>
        /// <returns>List of provenances that matches my settings.</returns>
        private List <SpeciesObservationProvenance> CalculateProvenances()
        {
            var searchCriteriaManager = new SpeciesObservationSearchCriteriaManager(UserContext);
            SpeciesObservationSearchCriteria searchCriteria = searchCriteriaManager.CreateSearchCriteria(MySettings);

            if (UserContext.CurrentRole.IsNull() && UserContext.CurrentRoles.Count > 0)
            {
                UserContext.CurrentRole = UserContext.CurrentRoles[0];
            }

            var displayCoordinateSystem          = MySettings.Presentation.Map.DisplayCoordinateSystem;
            var speciesObservationProvenanceList = CoreData.AnalysisManager.GetSpeciesObservationProvenancesBySearchCriteria(UserContext, searchCriteria, displayCoordinateSystem);

            speciesObservationProvenanceList = CreateOrderedSpeciesObservationProvenanceList(speciesObservationProvenanceList);
            return(speciesObservationProvenanceList);
        }
Example #10
0
        public List <TaxonSpeciesObservationCountViewModel> CalculateResult()
        {
            var searchCriteriaManager = new SpeciesObservationSearchCriteriaManager(UserContext);
            SpeciesObservationSearchCriteria searchCriteria = searchCriteriaManager.CreateSearchCriteria(MySettings);

            if (UserContext.CurrentRole.IsNull() && UserContext.CurrentRoles.Count > 0)
            {
                UserContext.CurrentRole = UserContext.CurrentRoles[0];
            }

            var displayCoordinateSystem = MySettings.Presentation.Map.DisplayCoordinateSystem;
            TaxonSpeciesObservationCountList             taxonSpeciesObservationCountList = CoreData.AnalysisManager.GetTaxaWithSpeciesObservationCountsBySearchCriteria(UserContext, searchCriteria, displayCoordinateSystem);
            List <TaxonSpeciesObservationCountViewModel> taxaSpeciesObservationCountList  = taxonSpeciesObservationCountList.GetGenericList().ToTaxonSpeciesObservationCountViewModelList();

            return(taxaSpeciesObservationCountList);
        }
Example #11
0
        protected SpeciesObservationList GetPagedSpeciesObservationList(int start, int pageSize, int?taxonId, Polygon bbox)
        {
            SpeciesObservationPageSpecification pageSpecification = new SpeciesObservationPageSpecification();

            pageSpecification.Size      = pageSize;
            pageSpecification.Start     = start;
            pageSpecification.SortOrder = new SpeciesObservationFieldSortOrderList();
            SpeciesObservationFieldSortOrder sortOrderOne = new SpeciesObservationFieldSortOrder();

            sortOrderOne.SortOrder   = SortOrder.Descending;
            sortOrderOne.Class       = new SpeciesObservationClass();
            sortOrderOne.Class.Id    = SpeciesObservationClassId.Event;
            sortOrderOne.Property    = new SpeciesObservationProperty();
            sortOrderOne.Property.Id = SpeciesObservationPropertyId.Start;
            pageSpecification.SortOrder.Add(sortOrderOne);

            var searchCriteriaManager = new SpeciesObservationSearchCriteriaManager(UserContext);
            SpeciesObservationSearchCriteria searchCriteria = searchCriteriaManager.CreateSearchCriteria(MySettings);

            if (taxonId.HasValue)
            {
                searchCriteria.TaxonIds = new List <int> {
                    taxonId.Value
                };
            }
            if (bbox != null)
            {
                searchCriteria.Polygons = new List <IPolygon> {
                    bbox
                };
            }

            if (UserContext.CurrentRole.IsNull() && UserContext.CurrentRoles.Count > 0)
            {
                UserContext.CurrentRole = UserContext.CurrentRoles[0];
            }

            var displayCoordinateSystem = MySettings.Presentation.Map.DisplayCoordinateSystem;
            // Todo Add more pecifice page information

            //SpeciesObservationList speciesObservationList = CoreData.SpeciesObservationManager.GetSpeciesObservations(UserContext, searchCriteria, displayCoordinateSystem);
            SpeciesObservationList speciesObservationList = CoreData.SpeciesObservationManager.GetSpeciesObservations(UserContext, searchCriteria, displayCoordinateSystem, pageSpecification);

            return(speciesObservationList);
        }
Example #12
0
        /// <summary>
        /// Calculates summary statistics per polygon.
        /// </summary>
        /// <returns>
        /// A list of statistics in form of pairs.
        /// </returns>
        private List <SpeciesObservationsCountPerPolygon> CalculateSummaryStatisticsPerPolygon()
        {
            List <SpeciesObservationsCountPerPolygon> result = new List <SpeciesObservationsCountPerPolygon>();

            if (MySettings.Calculation.SummaryStatistics.WfsSummaryStatisticsLayerId.HasValue)
            {
                var searchCriteriaManager = new SpeciesObservationSearchCriteriaManager(UserContext);
                SpeciesObservationSearchCriteria searchCriteria = searchCriteriaManager.CreateSearchCriteria(MySettings);
                FeatureCollection featureCollection             = GetFeatureCollection();
                DataContext       dataContext             = new DataContext(this.UserContext);
                CoordinateSystem  displayCoordinateSystem = MySettings.Presentation.Map.DisplayCoordinateSystem;

                searchCriteria.Polygons = new List <IPolygon>();
                foreach (Feature feature in featureCollection.Features)
                {
                    long               speciesObservationCount = -1; // -1 means user did not choose to display the number of species observation
                    long               speciesCount            = -1; // -1 means user did not choose to display the number of species
                    string             featureDescription      = GetFeatureDescription(feature);
                    List <DataPolygon> dataPolygons            = GetDataPolygons(feature);
                    searchCriteria.Polygons = dataPolygons.ToPolygons(dataContext);

                    if (MySettings.Calculation.SummaryStatistics.CalculateNumberOfObservationsfromObsData)
                    {
                        speciesObservationCount = CoreData.AnalysisManager.GetSpeciesObservationCountBySearchCriteria(this.UserContext, searchCriteria, displayCoordinateSystem);
                    }

                    if (MySettings.Calculation.SummaryStatistics.CalculateNumberOfSpeciesfromObsData)
                    {
                        speciesCount = CoreData.AnalysisManager.GetSpeciesCountBySearchCriteria(this.UserContext, searchCriteria, displayCoordinateSystem);
                    }

                    result.Add(new SpeciesObservationsCountPerPolygon
                    {
                        Properties = featureDescription,
                        SpeciesObservationsCount = speciesObservationCount == -1 ? "-" : Convert.ToString(speciesObservationCount),
                        SpeciesCount             = speciesCount == -1 ? "-" : Convert.ToString(speciesCount)
                    });
                }
            }

            return(result);
        }
Example #13
0
        /// <summary>
        /// Calculates the species observation grid.
        /// </summary>
        /// <param name="taxonIds">The taxon ids.</param>
        /// <param name="gridCoordinateSystem">The grid coordinate system.</param>
        /// <param name="bottom"></param>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <param name="top"></param>
        /// <param name="zoom"></param>
        /// <param name="gridSize"></param>
        /// <returns>List of grid cells data.</returns>
        public IList <IGridCellSpeciesObservationCount> CalculateSpeciesObservationGrid(List <int> taxonIds, GridCoordinateSystem?gridCoordinateSystem, double bottom, double left, double right, double top, int zoom, int?gridSize)
        {
            var speciesObservationSearchCriteriaManager     = new SpeciesObservationSearchCriteriaManager(UserContext);
            SpeciesObservationSearchCriteria searchCriteria = speciesObservationSearchCriteriaManager.CreateSearchCriteria(MySettings);

            // remove spatial filter?
            searchCriteria.Polygons    = null;
            searchCriteria.RegionGuids = null;
            searchCriteria.TaxonIds    = taxonIds;

            CoordinateSystem      displayCoordinateSystem = MySettings.Presentation.Map.DisplayCoordinateSystem;
            GridStatisticsSetting gridStatisticsSetting   = MySettings.Calculation.GridStatistics;
            GridSpecification     gridSpecification       = new GridSpecification();

            if (gridCoordinateSystem.HasValue)
            {
                gridSpecification.GridCoordinateSystem = gridCoordinateSystem.Value;
            }
            else
            {
                if (gridStatisticsSetting.CoordinateSystemId.HasValue)
                {
                    gridSpecification.GridCoordinateSystem = (GridCoordinateSystem)gridStatisticsSetting.CoordinateSystemId;
                }
                else
                {
                    gridSpecification.GridCoordinateSystem = GridCoordinateSystem.SWEREF99_TM;
                }
            }

            gridSpecification.GridCellSize            = gridSize.HasValue ? gridSize.Value : ZoomMappings[zoom];
            gridSpecification.IsGridCellSizeSpecified = true;
            gridSpecification.GridCellGeometryType    = GridCellGeometryType.Polygon;
            searchCriteria.Polygons = new List <IPolygon>();
            searchCriteria.Polygons.Add(GetPolygon(bottom, left, right, top));
            IList <IGridCellSpeciesObservationCount> gridCellObservations = CoreData.AnalysisManager.GetGridSpeciesObservationCounts(UserContext, searchCriteria, gridSpecification, displayCoordinateSystem);

            gridCellObservations = gridCellObservations.OrderBy(x => x.Identifier).ToList();
            return(gridCellObservations);
        }
        /// <summary>
        /// Generate species observation properties to a text file.
        /// </summary>
        /// <returns></returns>
        public ActionResult GenerateObservationProperties()
        {
            string filePath = string.Empty;

            try
            {
                IUserContext userContext = CoreData.UserManager.GetApplicationContext();
                // Serach griffelblomfluga to extract properties from
                var obsSearchCriteria = new SpeciesObservationSearchCriteria {
                    TaxonIds = new List <int> {
                        100573
                    }, IncludePositiveObservations = true
                };
                var coordinateSystem = new CoordinateSystem {
                    Id = CoordinateSystemId.WGS84
                };

                userContext.CurrentRole = userContext.CurrentRoles[0];
                var obsList = new SpeciesObservationList();
                SpeciesObservationFieldList fieldList = new SpeciesObservationFieldList();
                if (obsSearchCriteria.TaxonIds.Count > 0)
                {
                    obsList = CoreData.SpeciesObservationManager.GetSpeciesObservations(userContext, obsSearchCriteria, coordinateSystem);
                }

                ISpeciesObservation observation = obsList[0];

                Dictionary <string, string> tableData = new Dictionary <string, string>();
                tableData = ExtractProperties(observation);
                filePath  = GetFilePath("SpeciesObservationProperties" + System.DateTime.Now.ToShortDateString());
                SaveFileToDisk(filePath, tableData);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            ViewData["FilePath"] = filePath;
            return(View());
        }
        public JsonNetResult GetObservations()
        {
            JsonModel jsonModel;

            try
            {
                IUserContext user = CoreData.UserManager.GetCurrentUser();
                var          obsSearchCriteria = new SpeciesObservationSearchCriteria
                {
                    TaxonIds = new List <int> {
                        100573
                    }, IncludePositiveObservations = true
                };
                var coordinateSystem = new CoordinateSystem {
                    Id = CoordinateSystemId.GoogleMercator
                };
                //CoordinateSystemId.SWEREF99

                user.CurrentRole = user.CurrentRoles[0];
                var obsList = new SpeciesObservationList();
                SpeciesObservationFieldList fieldList = new SpeciesObservationFieldList();
                if (obsSearchCriteria.TaxonIds.Count > 0)
                {
                    obsList = CoreData.SpeciesObservationManager.GetSpeciesObservations(user, obsSearchCriteria, coordinateSystem);
                }

                IList <ISpeciesObservation> resultList = obsList.GetGenericList();

                var observationObject = GetObservationsObject(resultList);

                jsonModel = JsonModel.CreateFromObject(observationObject);
            }
            catch (Exception ex)
            {
                jsonModel = JsonModel.CreateFailure(ex.Message);
            }
            return(new JsonNetResult(jsonModel));
        }
        /// <summary>
        /// Creates the search criteria based on filter settings.
        /// </summary>
        /// <param name="mySettings">
        /// The my settings object.
        /// </param>
        /// <returns>
        /// The <see cref="SpeciesObservationSearchCriteria"/>.
        /// </returns>
        public SpeciesObservationSearchCriteria CreateSearchCriteria(
            MySettings.MySettings mySettings,
            ICoordinateSystem coordinateSystem)
        {
            var searchCriteria = new SpeciesObservationSearchCriteria();

            // Default settings
            searchCriteria.IncludePositiveObservations = true;

            // Taxa filter
            if (mySettings.Filter.Taxa.IsActive && mySettings.Filter.Taxa.HasSettings)
            {
                searchCriteria.TaxonIds = mySettings.Filter.Taxa.TaxonIds.ToList();
            }

            // Temporal filter
            if (mySettings.Filter.Temporal.IsActive)
            {
                // Observation date
                if (mySettings.Filter.Temporal.ObservationDate.UseSetting)
                {
                    searchCriteria.ObservationDateTime          = new DateTimeSearchCriteria();
                    searchCriteria.ObservationDateTime.Operator = CompareOperator.Excluding;
                    if (mySettings.Filter.Temporal.ObservationDate.Annually)
                    {
                        searchCriteria.ObservationDateTime.Begin      = new DateTime(1800, 1, 1);
                        searchCriteria.ObservationDateTime.End        = DateTime.Now.AddDays(1);
                        searchCriteria.ObservationDateTime.PartOfYear = new List <IDateTimeInterval>();
                        IDateTimeInterval dateTimeInterval = new DateTimeInterval();
                        dateTimeInterval.Begin = mySettings.Filter.Temporal.ObservationDate.StartDate;
                        dateTimeInterval.End   = mySettings.Filter.Temporal.ObservationDate.EndDate;
                        searchCriteria.ObservationDateTime.PartOfYear.Add(dateTimeInterval);
                    }
                    else
                    {
                        searchCriteria.ObservationDateTime.Begin = mySettings.Filter.Temporal.ObservationDate.StartDate;
                        searchCriteria.ObservationDateTime.End   = mySettings.Filter.Temporal.ObservationDate.EndDate;
                    }
                }

                // Registration date
                if (mySettings.Filter.Temporal.RegistrationDate.UseSetting)
                {
                    searchCriteria.ReportedDateTime          = new DateTimeSearchCriteria();
                    searchCriteria.ReportedDateTime.Operator = CompareOperator.Excluding;
                    if (mySettings.Filter.Temporal.RegistrationDate.Annually)
                    {
                        searchCriteria.ReportedDateTime.Begin      = new DateTime(1800, 1, 1);
                        searchCriteria.ReportedDateTime.End        = DateTime.Now.AddDays(1);
                        searchCriteria.ReportedDateTime.PartOfYear = new List <IDateTimeInterval>();
                        IDateTimeInterval dateTimeInterval = new DateTimeInterval();
                        dateTimeInterval.Begin = mySettings.Filter.Temporal.RegistrationDate.StartDate;
                        dateTimeInterval.End   = mySettings.Filter.Temporal.RegistrationDate.EndDate;
                        searchCriteria.ReportedDateTime.PartOfYear.Add(dateTimeInterval);
                    }
                    else
                    {
                        searchCriteria.ReportedDateTime.Begin = mySettings.Filter.Temporal.RegistrationDate.StartDate;
                        searchCriteria.ReportedDateTime.End   = mySettings.Filter.Temporal.RegistrationDate.EndDate;
                    }
                }

                // Change date
                if (mySettings.Filter.Temporal.ChangeDate.UseSetting)
                {
                    searchCriteria.ChangeDateTime          = new DateTimeSearchCriteria();
                    searchCriteria.ChangeDateTime.Operator = CompareOperator.Excluding;
                    if (mySettings.Filter.Temporal.ChangeDate.Annually)
                    {
                        searchCriteria.ChangeDateTime.Begin      = new DateTime(1800, 1, 1);
                        searchCriteria.ChangeDateTime.End        = DateTime.Now.AddDays(1);
                        searchCriteria.ChangeDateTime.PartOfYear = new List <IDateTimeInterval>();
                        IDateTimeInterval dateTimeInterval = new DateTimeInterval();
                        dateTimeInterval.Begin = mySettings.Filter.Temporal.ChangeDate.StartDate;
                        dateTimeInterval.End   = mySettings.Filter.Temporal.ChangeDate.EndDate;
                        searchCriteria.ChangeDateTime.PartOfYear.Add(dateTimeInterval);
                    }
                    else
                    {
                        searchCriteria.ChangeDateTime.Begin = mySettings.Filter.Temporal.ChangeDate.StartDate;
                        searchCriteria.ChangeDateTime.End   = mySettings.Filter.Temporal.ChangeDate.EndDate;
                    }
                }
            }

            // Accuracy filter
            if (mySettings.Filter.Accuracy.IsActive)
            {
                if (mySettings.Filter.Accuracy.IsCoordinateAccuracyActive)
                {
                    searchCriteria.Accuracy             = mySettings.Filter.Accuracy.MaxCoordinateAccuracy;
                    searchCriteria.IsAccuracyConsidered = mySettings.Filter.Accuracy.Inclusive;
                }
                else
                {
                    searchCriteria.Accuracy             = null;
                    searchCriteria.IsAccuracyConsidered = false;
                }
            }

            // Spatial filter
            if (mySettings.Filter.Spatial.IsActive)
            {
                if (mySettings.Filter.Spatial.Polygons.Count > 0)
                {
                    var dataContext = new DataContext(_userContext);
                    ICoordinateSystem fromCoordinateSystem = mySettings.Filter.Spatial.PolygonsCoordinateSystem;
                    //ICoordinateSystem toCoordinateSystem = mySettings.Presentation.Map.DisplayCoordinateSystem;
                    ICoordinateSystem toCoordinateSystem = coordinateSystem;
                    List <IPolygon>   polygons           = mySettings.Filter.Spatial.Polygons.ToList().ToPolygons(dataContext);
                    polygons = GisTools.CoordinateConversionManager.GetConvertedPolygons(polygons, fromCoordinateSystem, toCoordinateSystem);

                    GeometryTools geometryTools = new GeometryTools();
                    foreach (IPolygon polygon in polygons)
                    {
                        var polygonStatus = geometryTools.ValidateGeometry(polygon);
                        if (!polygonStatus.IsValid)
                        {
                            throw new Exception(string.Format("Polygon error! {0}", polygonStatus.Description));
                        }
                    }

                    searchCriteria.Polygons = polygons;
                }

                if (mySettings.Filter.Spatial.RegionIds.Count > 0)
                {
                    searchCriteria.RegionGuids = new List <string>();
                    RegionList regions = CoreData.RegionManager.GetRegionsByIds(_userContext, mySettings.Filter.Spatial.RegionIds.ToList());
                    foreach (IRegion region in regions)
                    {
                        searchCriteria.RegionGuids.Add(region.GUID);
                    }
                }

                // Locality name search
                if (!string.IsNullOrEmpty(mySettings.Filter.Spatial.Locality.LocalityName))
                {
                    searchCriteria.LocalityNameSearchString = new StringSearchCriteria();
                    searchCriteria.LocalityNameSearchString.SearchString     = mySettings.Filter.Spatial.Locality.LocalityName;
                    searchCriteria.LocalityNameSearchString.CompareOperators = new List <StringCompareOperator>();
                    searchCriteria.LocalityNameSearchString.CompareOperators.Add(mySettings.Filter.Spatial.Locality.CompareOperator);
                }
            }

            // Occurrence filter
            if (mySettings.Filter.Occurrence.IsActive)
            {
                searchCriteria.IncludeNeverFoundObservations      = mySettings.Filter.Occurrence.IncludeNeverFoundObservations;
                searchCriteria.IncludeNotRediscoveredObservations = mySettings.Filter.Occurrence.IncludeNotRediscoveredObservations;
                searchCriteria.IncludePositiveObservations        = mySettings.Filter.Occurrence.IncludePositiveObservations;

                if (mySettings.Filter.Occurrence.IsNaturalOccurrence ==
                    mySettings.Filter.Occurrence.IsNotNaturalOccurrence)
                {
                    // TODO: Set ignore IsNaturalOccurence
                }
                else
                {
                    searchCriteria.IsNaturalOccurrence = mySettings.Filter.Occurrence.IsNaturalOccurrence;
                }
            }

            // Data providers
            if (mySettings.DataProvider.DataProviders.IsActive && mySettings.DataProvider.DataProviders.HasSettings)
            {
                //Get all data providers
                bool providersWithObservationDisabled;
                var  dataProviders = DataProviderManager.GetAllDataProviders(_userContext, out providersWithObservationDisabled);

                //If all providers are selected and we don't have any providers with observation disabled, we don't set data source guids since it will decrease performance
                //All existing providers will be used if the property is not set and the performance is better compared to setting all providers explicit
                if (providersWithObservationDisabled || dataProviders.Count != mySettings.DataProvider.DataProviders.DataProvidersGuids.Count)
                {
                    searchCriteria.DataSourceGuids = new List <string>();
                    foreach (var guid in mySettings.DataProvider.DataProviders.DataProvidersGuids)
                    {
                        searchCriteria.DataSourceGuids.Add(guid);
                    }
                }
            }

            // Field filter
            if (mySettings.Filter.Field.IsActive && mySettings.Filter.Field.HasSettings)
            {
                searchCriteria.FieldSearchCriteria = new SpeciesObservationFieldSearchCriteriaList();

                foreach (var fieldFilterExpression in mySettings.Filter.Field.FieldFilterExpressions)
                {
                    searchCriteria.FieldSearchCriteria.Add(fieldFilterExpression);
                }

                searchCriteria.FieldLogicalOperator = mySettings.Filter.Field.FieldLogicalOperator;
            }

            return(searchCriteria);
        }