Example #1
0
        /// <summary>
        /// Creates a species observation CSV file and stores it on the server in the
        /// Temp/Export/ folder.
        /// This can be used in workflow scenarios.
        ///
        /// </summary>
        /// <returns>JSON data with information about the URL to the generated file.</returns>
        public JsonNetResult SpeciesObservationGridAsCsvStoreFileOnServer()
        {
            JsonModel jsonModel;
            SpeciesObservationGridCalculator resultCalculator = null;
            SpeciesObservationGridResult     result           = null;

            try
            {
                IUserContext currentUser = GetCurrentUser();
                if (currentUser.IsAuthenticated() && !currentUser.IsCurrentRolePrivatePerson())
                {
                    throw new Exception(Resource.ResultWorkflowCurrentRoleIsNotPrivatePerson);
                }

                resultCalculator = new SpeciesObservationGridCalculator(currentUser, SessionHandler.MySettings);
                result           = resultCalculator.GetSpeciesObservationGridResultFromCacheIfAvailableOrElseCalculate();
                string filename = FileExportManager.CreateSpeciesObservationGridAsCsvAndStoreOnServer(currentUser, result);
                string url      = FileSystemManager.ExportFolderUrl + filename;
                jsonModel = JsonModel.CreateFromObject(url);
            }
            catch (Exception ex)
            {
                jsonModel = JsonModel.CreateFailure(ex.Message);
            }

            return(new JsonNetResult(jsonModel));
        }
        /// <summary>
        /// Writes species observation grid result as comma separated format (CSV) to a stream.
        /// </summary>
        /// <param name="stream">The stream to be written to.</param>
        /// <param name="data">The data to write.</param>
        /// <param name="toCoordinateSystem">The coordinate system the coordinates should be converted to.</param>
        /// <param name="taxaName">Summary of species names.</param>
        public void WriteDataToStream(Stream stream, SpeciesObservationGridResult data, CoordinateSystem toCoordinateSystem, string taxaName)
        {
            CoordinateSystem fromCoordinateSystem = new CoordinateSystem((CoordinateSystemId)data.GridCellCoordinateSystemId);
            CsvConfiguration csvConfiguration     = new CsvConfiguration();

            csvConfiguration.QuoteAllFields = true;
            csvConfiguration.Delimiter      = ",";
            csvConfiguration.Encoding       = Encoding.UTF8;
            using (var streamWriter = new StreamWriter(stream, Encoding.UTF8))
                using (CsvWriter writer = new CsvWriter(streamWriter, csvConfiguration))
                {
                    writer.WriteField("occurrenceID");
                    writer.WriteField("nameComplete");
                    writer.WriteField("decimalLatitude");
                    writer.WriteField("decimalLongitude");
                    writer.NextRecord();

                    for (int i = 0; i < data.Cells.Count; i++)
                    {
                        SpeciesObservationGridCellResult gridCell = data.Cells[i];
                        writer.WriteField(string.Format("Grid Cell {0}", i + 1));
                        Point convertedPoint =
                            GisTools.CoordinateConversionManager.GetConvertedPoint(
                                new Point(gridCell.OriginalCentreCoordinateX, gridCell.OriginalCentreCoordinateY),
                                fromCoordinateSystem,
                                toCoordinateSystem);
                        writer.WriteField(taxaName);
                        writer.WriteField(convertedPoint.Y.ToString(CultureInfo.InvariantCulture));
                        writer.WriteField(convertedPoint.X.ToString(CultureInfo.InvariantCulture));
                        writer.NextRecord();
                    }
                }
        }
Example #3
0
        private JsonModel GetGridResult(CancellationToken ct)
        {
            JsonModel jsonModel;

            try
            {
                if (ct.IsCancellationRequested)
                {
                    return(null);
                }
                MySettings mySettings = Session["mySettings"] as MySettings;
                //                mySettings.Filter.Taxa.TaxonIds = new ObservableCollection<int>() { 5, 7, 8, 11, 14, 16 };
                //mySettings.Filter.Taxa.TaxonIds = new ObservableCollection<int>() { 5, 7, 8, 11, 14, 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };

                mySettings.Filter.Taxa.IsActive = true;
                IUserContext userContext = CoreData.UserManager.GetCurrentUser();
                IList <IGridCellSpeciesObservationCount> res   = GetSpeciesObservationGridCellResultFromWebService(userContext, mySettings);
                SpeciesObservationGridResult             model = SpeciesObservationGridResult.Create(res);
                //SpeciesObservationGridResult model = resultsManager.GetSpeciesObservationGridCellResult();
                jsonModel = JsonModel.CreateFromObject(model);
            }
            catch (Exception ex)
            {
                jsonModel = JsonModel.CreateFailure(ex.Message);
            }
            return(jsonModel);
        }
Example #4
0
 /// <summary>
 /// Adds the headers.
 /// </summary>
 /// <param name="worksheet">The worksheet.</param>
 /// <param name="data">Data</param>
 private void AddHeaders(ExcelWorksheet worksheet, SpeciesObservationGridResult data)
 {
     worksheet.Cells[1, 1].Value = "Id";
     worksheet.Cells[1, 2].Value = Resource.GridStatisticsObservationCount;
     worksheet.Cells[1, 3].Value = String.Format("Centre coordinate X ({0})", data.GridCellCoordinateSystem);
     worksheet.Cells[1, 4].Value = String.Format("Centre coordinate Y ({0})", data.GridCellCoordinateSystem);
     worksheet.Cells[1, 5].Value = String.Format("Centre coordinate X ({0})", CoordinateSystem);
     worksheet.Cells[1, 6].Value = String.Format("Centre coordinate Y ({0})", CoordinateSystem);
     worksheet.Cells[1, 7].Value = "Grid cell width (metres)";
 }
        public override void Execute()
        {
            System.Diagnostics.Debug.WriteLine("CalculateDefaultGridCellObservationsTask started");
            IUserContext userContext = CoreData.UserManager.GetCurrentUser();

            MySettings.MySettings            mySettings       = new MySettings.MySettings();
            SpeciesObservationGridCalculator resultCalculator = new SpeciesObservationGridCalculator(userContext, mySettings);
            SpeciesObservationGridResult     result           = resultCalculator.CalculateSpeciesObservationGridResult(mySettings);

            DefaultResultsManager.AddGridCellObservations(result);
            System.Diagnostics.Debug.WriteLine("CalculateDefaultGridCellObservationsTask finished");
        }
Example #6
0
        public SpeciesObservationGridResult CalculateSpeciesObservationGridEx(double bottom, double left, double right, double top, int zoom, int?gridSize)
        {
            List <int> taxonIds = null;

            if (MySettings.Filter.Taxa.IsActive)
            {
                taxonIds = MySettings.Filter.Taxa.TaxonIds.ToList();
            }

            IList <IGridCellSpeciesObservationCount> result = CalculateSpeciesObservationGrid(taxonIds, null, bottom, left, right, top, zoom, gridSize);

            return(SpeciesObservationGridResult.Create(result));
        }
Example #7
0
        private SpeciesObservationGridResult CreateSpeciesObservationGridResultSampleData()
        {
            SpeciesObservationGridResult speciesObservationGridResult = new SpeciesObservationGridResult();

            speciesObservationGridResult.GridCellCoordinateSystem   = "SWEREF99_TM";
            speciesObservationGridResult.GridCellCoordinateSystemId = (int)CoordinateSystemId.SWEREF99_TM; // 3
            speciesObservationGridResult.GridCellSize = 10000;
            speciesObservationGridResult.Cells        = new List <SpeciesObservationGridCellResult>
            {
                CreateSpeciesObservationGridCellResultSampleData1(),
                CreateSpeciesObservationGridCellResultSampleData2()
            };
            return(speciesObservationGridResult);
        }
Example #8
0
        private void AddContentData(ExcelWorksheet worksheet, SpeciesObservationGridResult data)
        {
            var rowIndex = 2;

            foreach (var row in data.Cells)
            {
                worksheet.Cells[rowIndex, 1].Value = row.Identifier;
                worksheet.Cells[rowIndex, 2].Value = row.ObservationCount;
                worksheet.Cells[rowIndex, 3].Value = row.OriginalCentreCoordinateX;
                worksheet.Cells[rowIndex, 4].Value = row.OriginalCentreCoordinateY;
                worksheet.Cells[rowIndex, 5].Value = row.CentreCoordinateX;
                worksheet.Cells[rowIndex, 6].Value = row.CentreCoordinateY;
                worksheet.Cells[rowIndex, 7].Value = data.GridCellSize;

                rowIndex++;
            }
        }
Example #9
0
        public void WriteData_DataWithTwoCellResults_DataIsWrittenCsvFormatted()
        {
            SpeciesObservationGridCsv    speciesObservationGridCsv = new SpeciesObservationGridCsv();
            SpeciesObservationGridResult data = CreateSpeciesObservationGridResultSampleData();
            CoordinateSystem             toCoordinateSystem = new CoordinateSystem(CoordinateSystemId.WGS84);
            const string taxaName = "All taxa";

            using (MemoryStream memoryStream = new MemoryStream())
            {
                speciesObservationGridCsv.WriteDataToStream(memoryStream, data, toCoordinateSystem, taxaName);

                string actual = Encoding.UTF8.GetString(memoryStream.ToArray());

                string expectedResult =
                    @"""occurrenceID"",""nameComplete"",""decimalLatitude"",""decimalLongitude""
""Grid Cell 1"",""All taxa"",""67.4331616673203"",""21.665551487154""
""Grid Cell 2"",""All taxa"",""63.6149937978252"",""16.5126895276083""
";
                Assert.AreEqual(expectedResult, RemoveBOM(actual));
            }
        }
Example #10
0
        /// <summary>
        /// Calculates a species observation grid and creates a Feature Collection.
        /// </summary>
        /// <returns>A feature collection containing all grid cells.</returns>
        public FeatureCollection GetSpeciesObservationGridAsFeatureCollection()
        {
            SpeciesObservationGridResult speciesObservationGridResult = GetSpeciesObservationGridResultFromCacheIfAvailableOrElseCalculate();

            List <Feature> features = new List <Feature>();

            foreach (SpeciesObservationGridCellResult gridCell in speciesObservationGridResult.Cells)
            {
                Dictionary <string, object> properties = new Dictionary <string, object>();
                properties.Add("Id", gridCell.Identifier);
                properties.Add("ObservationCount", gridCell.ObservationCount);
                properties.Add("CentreCoordinateX", gridCell.CentreCoordinateX);
                properties.Add("CentreCoordinateY", gridCell.CentreCoordinateY);
                properties.Add("OriginalCentreCoordinateX", gridCell.OriginalCentreCoordinateX);
                properties.Add("OriginalCentreCoordinateY", gridCell.OriginalCentreCoordinateY);

                List <GeographicPosition> coordinates = new List <GeographicPosition>();
                coordinates.Add(new GeographicPosition(gridCell.BoundingBox[0][0], gridCell.BoundingBox[0][1]));
                coordinates.Add(new GeographicPosition(gridCell.BoundingBox[1][0], gridCell.BoundingBox[1][1]));
                coordinates.Add(new GeographicPosition(gridCell.BoundingBox[2][0], gridCell.BoundingBox[2][1]));
                coordinates.Add(new GeographicPosition(gridCell.BoundingBox[3][0], gridCell.BoundingBox[3][1]));
                coordinates.Add(new GeographicPosition(gridCell.BoundingBox[0][0], gridCell.BoundingBox[0][1]));

                LineString lineString = new LineString(coordinates);

                List <LineString> linearRings = new List <LineString>();
                linearRings.Add(lineString);
                ArtDatabanken.GIS.GeoJSON.Net.Geometry.Polygon polygon = new ArtDatabanken.GIS.GeoJSON.Net.Geometry.Polygon(linearRings);

                Feature feature = new Feature(polygon, properties);
                features.Add(feature);
            }

            FeatureCollection featureCollection = new FeatureCollection(features);

            featureCollection.CRS = new NamedCRS(MySettings.Presentation.Map.PresentationCoordinateSystemId.EpsgCode());

            return(featureCollection);
        }
Example #11
0
        public SpeciesObservationGridResult CalculateSpeciesObservationGridResult(MySettings.MySettings mySettings)
        {
            var result = CalculateSpeciesObservationGrid(mySettings.Filter.Taxa.TaxonIds.ToList(), null);

            return(SpeciesObservationGridResult.Create(result));
        }
Example #12
0
 public SpeciesObservationGridResult CalculateSpeciesObservationGridResult()
 {
     return(SpeciesObservationGridResult.Create(CalculateSpeciesObservationGrid()));
 }
 /// <summary>
 /// Writes species observation grid result as comma separated format (CSV) to a file.
 /// </summary>
 /// <param name="filePath">The file path.</param>
 /// <param name="data">The data to write.</param>
 /// <param name="toCoordinateSystem">The coordinate system the coordinates should be converted to.</param>
 /// <param name="taxaName">Summary of species names.</param>
 public void WriteDataToFile(string filePath, SpeciesObservationGridResult data, CoordinateSystem toCoordinateSystem, string taxaName)
 {
     WriteDataToStream(new FileStream(filePath, FileMode.Create), data, toCoordinateSystem, taxaName);
 }
 public static CalculatedDataItem <SpeciesObservationGridResult> AddGridCellObservations(SpeciesObservationGridResult data)
 {
     return(CalculatedDataItemCollection.AddCalculatedDataItem(CalculatedDataItemType.GridCellObservations, data));
 }
Example #15
0
        /// <summary>
        /// Creates the species observation grid as a comma separated file (CSV) and saves it on the server.
        /// </summary>
        /// <param name="userContext">The user context.</param>
        /// <param name="data">The data.</param>
        /// <returns>The filename.</returns>
        public static string CreateSpeciesObservationGridAsCsvAndStoreOnServer(IUserContext userContext, SpeciesObservationGridResult data)
        {
            var speciesObservationGridCsv = new SpeciesObservationGridCsv();
            var path             = "~/Temp/Export/";
            var filename         = FileSystemManager.CreateRandomFilenameWithPrefix("data", ".csv");
            var absoluteFilePath = FileSystemManager.GetAbsoluteFilePath(path, filename);
            var taxaName         = ((TaxaSettingSummary)MySettingsSummaryItemManager.GetItem(MySettingsSummaryItemIdentifier.FilterTaxa)).GetShortDescription();

            FileSystemManager.EnsureFolderExists(path);
            speciesObservationGridCsv.WriteDataToFile(absoluteFilePath, data, new CoordinateSystem(CoordinateSystemId.WGS84), taxaName);
            return(filename);
        }