Esempio n. 1
0
 public List <MapPointModel> GetMapData(FilterModel filters)
 {
     using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters {
         { "Filters", filters }
     }))
     {
         try
         {
             return(GetData(filters).Where(i => i.Latitude.HasValue && i.Longitude.HasValue).Select(i => new MapPointModel
             {
                 Id = i.Id,
                 Name = i.Name,
                 Url = $"Info/{i.Id}",
                 Link = $"<a href='Info/{i.Id}'>{i.Name}</a>",
                 Latitude = i.Latitude.Value,
                 Longitude = i.Longitude.Value
             }).ToList());
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
Esempio n. 2
0
 public IActionResult UpdateImage(ImageModel model)
 {
     using (SAEONLogs.MethodCall(GetType()))
     {
         {
             try
             {
                 SAEONLogs.Verbose("Model: {@Model}", model);
                 if (model is null)
                 {
                     throw new ArgumentNullException(nameof(model));
                 }
                 var estuary = dbContext.Estuaries.Include(i => i.Images).First(i => i.Id == model.EstuaryId);
                 var image   = dbContext.Images.First(i => i.Id == model.Id);
                 image.Type           = model.Type;
                 image.SubType        = model.SubType;
                 image.Name           = model.Name;
                 image.Notes          = model.Notes;
                 image.Source         = model.Source;
                 image.Link           = model.Link;
                 image.LinkHiRes      = model.LinkHiRes;
                 image.HiResImageSize = model.HiResImageSize;
                 dbContext.SaveChanges();
                 return(RedirectToAction(nameof(Images), new { id = model.EstuaryId }));
             }
             catch (Exception ex)
             {
                 SAEONLogs.Exception(ex);
                 throw;
             }
         }
     }
 }
Esempio n. 3
0
 public List <EstuaryModel> GetEstuaries(FilterModel filters)
 {
     using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters {
         { "Filters", filters }
     }))
     {
         try
         {
             return(GetData(filters).Select(i => new EstuaryModel
             {
                 Id = i.Id,
                 Name = $"<a href='Info/{i.Id}'>{i.Name}</a>",
                 Classification = i.Classification.Type,
                 Region = i.Region.Category,
                 Condition = i.Condition.Type,
                 Province = i.Province.Name
             }).ToList());
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
Esempio n. 4
0
 public IActionResult Index()
 {
     using (SAEONLogs.MethodCall(GetType()))
     {
         try
         {
             var model = new SearchViewModel
             {
                 Classifications = ListItems.SelectListFrom(dbContext.Classifications.Select(i => new IntListItem {
                     Id = i.Id, Text = i.Type
                 })),
                 Regions = ListItems.SelectListFrom(dbContext.Regions.Select(i => new IntListItem {
                     Id = i.Id, Text = i.Category
                 })),
                 Conditions = ListItems.SelectListFrom(dbContext.Conditions.Select(i => new IntListItem {
                     Id = i.Id, Text = i.Type
                 })),
                 Provinces = ListItems.SelectListFrom(dbContext.Provinces.Select(i => new IntListItem {
                     Id = i.Id, Text = i.Name
                 }))
             };
             return(View(model));
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
Esempio n. 5
0
        public IActionResult Estuaries()
        {
            var model = dbContext.Estuaries.OrderBy(i => i.Name).ToList();

            SAEONLogs.Verbose("Model: {@Model}", model);
            return(View(model));
        }
Esempio n. 6
0
 public JsonResult SiteMapErrors()
 {
     using (SAEONLogs.MethodCall(GetType()))
     {
         try
         {
             var errors = new List <string>();
             foreach (var estuary in dbContext.Estuaries.Include(i => i.Literatures.Where(i => i.Available != "N")).Include(i => i.Images.Where(i => i.Available != "N")).OrderBy(i => i.Name))
             {
                 foreach (var image in estuary.Images.Where(i => !string.IsNullOrWhiteSpace(i.Link) && i.Link.StartsWith("\\SAEDArchive\\")).OrderBy(i => i.Name))
                 {
                     var fileName = Path.Combine(env.ContentRootPath, image.Link.Replace("SAEDArchive", "Archive").TrimStart("\\"));
                     if (!System.IO.File.Exists(fileName))
                     {
                         errors.Add(fileName);
                     }
                 }
                 foreach (var literature in estuary.Literatures.Where(i => !string.IsNullOrWhiteSpace(i.Link) && i.Link.StartsWith("\\SAEDArchive\\")).OrderBy(i => i.Title))
                 {
                     var fileName = Path.Combine(env.ContentRootPath, literature.Link.Replace("SAEDArchive", "Archive").TrimStart("\\"));
                     if (!System.IO.File.Exists(fileName))
                     {
                         errors.Add(fileName);
                     }
                 }
             }
             return(Json(new { siteMapErrors = errors }));
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
Esempio n. 7
0
 public async Task <T> GetItemAsync(T item, Expression <Func <T, object> > partitionKeyExpression)
 {
     if (item is null)
     {
         throw new ArgumentNullException(nameof(item));
     }
     if (partitionKeyExpression is null)
     {
         throw new ArgumentNullException(nameof(partitionKeyExpression));
     }
     using (SAEONLogs.MethodCall <T>(GetType(), new MethodCallParameters {
         { "id", item.Id }, { "partitionKey", GetPartitionKeyValue(item, partitionKeyExpression) }
     }))
     {
         try
         {
             CheckItem(item);
             if (AutoEnsureContainer)
             {
                 await EnsureContainerAsync().ConfigureAwait(false);
             }
             return(await container.ReadItemAsync <T>(item.Id, GetPartitionKey(item, partitionKeyExpression)).ConfigureAwait(false));
         }
         catch (CosmosException ex) when(ex.StatusCode == HttpStatusCode.NotFound)
         {
             SAEONLogs.Verbose("Item with ID {ID} not found", item.Id);
             return(default);
Esempio n. 8
0
 public async Task<FileContentResult> GetLoRes(int id)
 {
     using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters { { nameof(id), id } }))
     {
         try
         {
             var image = await dbContext.Images.FirstOrDefaultAsync(i => i.Id == id);
             //Guard.IsNotNull(image, nameof(image));
             if (image == null)
             {
                 throw new ArgumentOutOfRangeException(nameof(id));
             }
             var fileName = Path.Combine(environment.ContentRootPath, image.Link.RemoveStartingBackSlash().RemoveStartingForwardSlash());
             using (MemoryStream outStream = new MemoryStream())
             using (var jpgImage = await SixLabors.ImageSharp.Image.LoadAsync(fileName))
             {
                 await jpgImage.SaveAsJpegAsync(outStream);
                 var imageBytes = outStream.ToArray();
                 var result = new FileContentResult(imageBytes, MediaTypeNames.Image.Jpeg);
                 var contentDisposition = new ContentDispositionHeaderValue("inline");
                 contentDisposition.FileName = Path.GetFileName(fileName);
                 Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
                 await RequestLogger.LogAsync(dbContext, Request, $"{image.Name}|{image.Link}");
                 return result;
             }
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
        private static SpreadsheetDocument CreateSpreadsheetDocument(SpreadsheetDocument document)
        {
            using (SAEONLogs.MethodCall(typeof(SpreadsheetDocument)))
            {
                try
                {
                    // Add a WorkbookPart to the document.
                    WorkbookPart workbookPart = document.AddWorkbookPart();
                    workbookPart.Workbook = new Workbook();

                    // Shared string table
                    SharedStringTablePart sharedStringTablePart = workbookPart.AddNewPart <SharedStringTablePart>();
                    sharedStringTablePart.SharedStringTable = new SharedStringTable();
                    sharedStringTablePart.SharedStringTable.Save();

                    // Stylesheet
                    WorkbookStylesPart workbookStylesPart = workbookPart.AddNewPart <WorkbookStylesPart>();
                    workbookStylesPart.Stylesheet = CreateStylesheet();
                    workbookStylesPart.Stylesheet.Save();

                    InsertSheet(document);
                    Save(document);
                    return(document);
                }
                catch (Exception ex)
                {
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }
Esempio n. 10
0
 public List <IssueModel> GetIssues(int id)
 {
     using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters {
         { "Id", id }
     }))
     {
         try
         {
             return(dbContext.Issues.Where(i => i.EstuaryId == id).Include(i => i.IssueType).OrderBy(i => i.IssueType.Type).ThenBy(i => i.Header).Select(i =>
                                                                                                                                                         new IssueModel
             {
                 Id = i.Id,
                 Type = i.IssueType.Type,
                 Header = i.Header,
                 Notes = i.Notes,
                 Responses = i.Responses
             }).ToList());
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
Esempio n. 11
0
        //public async Task LoadDatabaseAsync()
        //{
        //    if (database is not null)
        //    {
        //        return;
        //    }

        //    using (SAEONLogs.MethodCall<T>(GetType(), new MethodCallParameters { { "DatabaseId", DatabaseId } }))
        //    {
        //        try
        //        {
        //            SAEONLogs.Verbose("DatabaseUri: {DatabaseUri}", UriFactory.CreateDatabaseUri(DatabaseId));
        //            database = await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseId));
        //        }
        //        catch (Exception ex)
        //        {
        //            container = null;
        //            database = null;
        //            SAEONLogs.Exception(ex);
        //            throw;
        //        }
        //    }
        //}
        #endregion

        #region Container
        public async Task EnsureContainerAsync()
        {
            if (container is not null)
            {
                return;
            }

            using (SAEONLogs.MethodCall <T>(GetType(), new MethodCallParameters {
                { "DatabaseId", DatabaseId }, { "ContainerId", ContainerId }, { "PartitionKey", PartitionKey }
            }))
            {
                try
                {
                    await EnsureDatabaseAsync().ConfigureAwait(false);

                    var containerProperties = new ContainerProperties(ContainerId, PartitionKey);
                    containerProperties.IndexingPolicy.IndexingMode = IndexingMode.Consistent;
                    //// Defaults
                    //Container.IndexingPolicy.IncludedPaths.Add(
                    //    new IncludedPath
                    //    {
                    //        Path = "/*",
                    //        Indexes = new Container<Index> {
                    //            new HashIndex(DataType.String) { Precision = 3 },
                    //            new RangeIndex(DataType.Number) { Precision = -1 }
                    //        }
                    //    });
                    //foreach (var prop in typeof(T).GetProperties().Where(i => i.PropertyType == typeof(EpochDate)))
                    //{
                    //    var propName = prop.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName ?? prop.Name;
                    //    Container.IndexingPolicy.IncludedPaths.Add(new IncludedPath
                    //    {
                    //        Path = $"/{propName}/epoch/?",
                    //        Indexes = new Container<Index> { { new RangeIndex(DataType.Number, -1) } }
                    //    });
                    //};
                    //foreach (var subProp in typeof(T).GetProperties().Where(i => i.PropertyType == typeof(AzureSubDocument)))
                    //{
                    //    var subPropName = subProp.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName ?? subProp.Name;
                    //    foreach (var prop in subProp.GetType().GetProperties().Where(i => i.PropertyType == typeof(EpochDate)))
                    //    {
                    //        var propName = prop.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName ?? prop.Name;
                    //        Container.IndexingPolicy.IncludedPaths.Add(new IncludedPath
                    //        {
                    //            Path = $"/{subPropName}/{propName}/epoch/?",
                    //            Indexes = new Container<Index> { { new RangeIndex(DataType.Number, -1) } }
                    //        });
                    //    }
                    //};
                    container = await database.CreateContainerIfNotExistsAsync(containerProperties, Throughput).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    container = null;
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }
Esempio n. 12
0
        public IActionResult Index()
        {
            using (SAEONLogs.MethodCall(GetType()))
            {
                void GetFiles(string path, List <string> files)
                {
                    foreach (var content in _fileProvider.GetDirectoryContents(path))
                    {
                        if (!content.IsDirectory)
                        {
                            files.Add($"{path}/{content.Name}");
                        }
                        else
                        {
                            GetFiles($"{path}/{content.Name}", files);
                        }
                    }
                }

                var model = new MismatchModel();
                // Literature
                // Folder
                var folderLiteratures = new List <string>();
                GetFiles("Archive/Literature", folderLiteratures);
                //SAEONLogs.Verbose("folderLiteratures: {folderLiteratures}", folderLiteratures);
                // Database
                var dbLiteratures = new List <string>();
                dbLiteratures.AddRange(_dbContext.Literatures.Where(i => !string.IsNullOrWhiteSpace(i.Link) && i.Link.StartsWith("\\Archive\\")).Select(i => i.Link.Replace(@"\", "/").RemoveStartingBackSlash().RemoveStartingForwardSlash()));
                //SAEONLogs.Verbose("dbLiteratures: {dbLiteratures}", dbLiteratures);
                // Add folders missing from database
                model.Items.AddRange(folderLiteratures.Except(dbLiteratures).OrderBy(i => i).Select(i => new MismatchItemModel {
                    Type = "Literature", FileName = i, InDirectory = true, InDatabase = false
                }));
                // In directory not in database
                model.Items.AddRange(dbLiteratures.Except(folderLiteratures).OrderBy(i => i).Select(i => new MismatchItemModel {
                    Type = "Literature", FileName = i, InDirectory = false, InDatabase = true
                }));
                // Images
                // Folder
                var folderImages = new List <string>();
                GetFiles("Archive/Images", folderImages);
                //SAEONLogs.Verbose("folderImages: {folderImages}", folderImages);
                // Database
                var dbImages = new List <string>();
                //SAEONLogs.Verbose("dbImages: {dbImages}", dbImages);
                dbImages.AddRange(_dbContext.Images.Where(i => !string.IsNullOrWhiteSpace(i.Link) && i.Link.StartsWith("\\Archive\\")).Select(i => i.Link.Replace(@"\", "/").RemoveStartingBackSlash().RemoveStartingForwardSlash()));
                // Add folders missing from database
                model.Items.AddRange(folderImages.Except(dbImages).OrderBy(i => i).Select(i => new MismatchItemModel {
                    Type = "Image", FileName = i, InDirectory = true, InDatabase = false
                }));
                // In directory not in database
                model.Items.AddRange(dbImages.Except(folderImages).OrderBy(i => i).Select(i => new MismatchItemModel {
                    Type = "Image", FileName = i, InDirectory = false, InDatabase = true
                }));
                return(View(model));
            }
        }
Esempio n. 13
0
        public List <ImageModel> GetImages(int id, ImageFilterModel filters)
        {
            using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters {
                { "Id", id }, { "Filters", filters }
            }))
            {
                try
                {
                    SAEONLogs.Verbose("Filters: {@Filters}", filters);
                    var estuary = dbContext.Estuaries.Include(i => i.Images.Where(i => !string.IsNullOrWhiteSpace(i.Link) && i.Available != "N")).Where(i => i.Id == id).FirstOrDefault();
                    if (estuary is null)
                    {
                        return(new List <ImageModel>());
                    }

                    var query = estuary.Images.AsQueryable();
                    if (!string.IsNullOrWhiteSpace(filters?.Type))
                    {
                        query = query.Where(i => i.Type == filters.Type);
                    }
                    if (!string.IsNullOrWhiteSpace(filters?.SubType))
                    {
                        query = query.Where(i => i.SubType == filters.SubType);
                    }
                    return(query
                           .Where(i => System.IO.File.Exists(Path.Combine(env.ContentRootPath, i.Link.RemoveStartingBackSlash().RemoveStartingForwardSlash())))
                           .OrderBy(i => i.Type)
                           .ThenBy(i => i.SubType)
                           .ThenBy(i => i.DateTaken)
                           .ThenBy(i => i.Date)
                           .ThenBy(i => i.Name)
                           .Select(i =>
                                   new ImageModel
                    {
                        Id = i.Id,
                        Type = i.Type,
                        SubType = i.SubType,
                        Name = i.Name,
                        Date = i.Date,
                        Source = i.Source,
                        Reference = i.Reference,
                        Notes = i.Notes,
                        //Link = i.Link,
                        //LinkHiRes = i.LinkHiRes,
                        HiResImageSize = i.HiResImageSize
                    })
                           .ToList());
                }
                catch (Exception ex)
                {
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }
Esempio n. 14
0
 //[ResponseCache(Duration = 604800)]
 public IActionResult Index()
 {
     using (SAEONLogs.MethodCall(GetType()))
     {
         try
         {
             SAEONLogs.Verbose("ContentRoot: {contentRoot} WebRoot: {webRoot}", env.ContentRootPath, env.WebRootPath);
             List <SitemapNode> nodes = new List <SitemapNode>
             {
                 new SitemapNode(Url.Action("Index", "Home")),
                 new SitemapNode(Url.Action("Index", "Search")),
                 new SitemapNode(Url.Action("About", "Home")),
                 new SitemapNode(Url.Action("Acknowledgements", "Home")),
                 new SitemapNode(Url.Action("Background", "Home")),
                 new SitemapNode(Url.Action("Contact", "Home")),
                 new SitemapNode(Url.Action("Links", "Home")),
                 new SitemapNode(Url.Action("Privacy", "Home")),
                 new SitemapNode(Url.Action("Researchers", "Home")),
             };
             foreach (var estuary in dbContext.Estuaries.Include(i => i.Literatures.Where(i => !string.IsNullOrWhiteSpace(i.Link) && i.Available != "N")).Include(i => i.Images.Where(i => !string.IsNullOrWhiteSpace(i.Link) && i.Available != "N")).OrderBy(i => i.Name))
             {
                 var node   = new SitemapNode(Url.Action("Index", "Info", new { id = estuary.Id }));
                 var images = new List <SitemapImage>();
                 foreach (var image in estuary.Images.Where(i => i.Link.StartsWith("\\Archive\\")).OrderBy(i => i.Name))
                 {
                     var fileName = Path.Combine(env.ContentRootPath, image.Link.RemoveStartingBackSlash());
                     if (!System.IO.File.Exists(fileName))
                     {
                         SAEONLogs.Verbose("Cant find {fileName}", fileName);
                     }
                     else
                     {
                         var uri          = $"{Request.Scheme}://{Request.Host}/Image/LoRes/{image.Id}";
                         var sitemapImage = new SitemapImage(Uri.EscapeUriString(uri))
                         {
                             Title   = image.Name,
                             License = "https://creativecommons.org/licenses/by-nc-sa/4.0/"
                         };
                         images.Add(sitemapImage);
                     }
                 }
                 node.Images = images;
                 nodes.Add(node);
             }
             return(new SitemapProvider().CreateSitemap(new SitemapModel(nodes)));
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
        public static WorksheetPart InsertSheet(SpreadsheetDocument document, string sheetName = "")
        {
            using (SAEONLogs.MethodCall(typeof(WorksheetPart)))
            {
                try
                {
                    if (document is null)
                    {
                        throw new ArgumentNullException(nameof(document));
                    }
                    // Add a blank WorksheetPart.
                    WorksheetPart worksheetPart = document.WorkbookPart.AddNewPart <WorksheetPart>();
                    worksheetPart.Worksheet = new Worksheet(new SheetData());

                    Sheets sheets = document.WorkbookPart.Workbook.GetFirstChild <Sheets>();
                    if (sheets is null)
                    {
                        sheets = document.WorkbookPart.Workbook.AppendChild <Sheets>(new Sheets());
                    }
                    string relationshipId = document.WorkbookPart.GetIdOfPart(worksheetPart);
                    SAEONLogs.Verbose("relationshipId: {relationshipId}", relationshipId);

                    // Get a unique ID for the new worksheet.
                    uint sheetId = 1;
                    if (sheets.Elements <Sheet>().Any())
                    {
                        sheetId = sheets.Elements <Sheet>().Select(s => s.SheetId.Value).Max() + 1;
                    }
                    SAEONLogs.Verbose("sheetId: {sheetId}", sheetId);

                    // Give the new worksheet a name.
                    if (string.IsNullOrEmpty(sheetName))
                    {
                        sheetName = "Sheet" + sheetId;
                    }

                    SAEONLogs.Verbose("sheetName: {sheetName}", sheetName);

                    // Append the new worksheet and associate it with the workbook.
                    Sheet sheet = new Sheet()
                    {
                        Id = relationshipId, SheetId = sheetId, Name = sheetName
                    };
                    sheets.Append(sheet);
                    return(worksheetPart);
                }
                catch (Exception ex)
                {
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }
Esempio n. 16
0
        public static CsvWriter GetCsvWriter <T>(TextWriter writer, CsvConfiguration config, IEnumerable <T> list) where T : class
        {
            var result   = GetCsvWriter(writer, config);
            var type     = list.GetType();
            var itemType = type.GetGenericArguments().Length > 0 ? type.GetGenericArguments()[0] : type.GetElementType();
            var updates  = false;
            var ignores  = itemType.GetProperties().Where(property => property.GetCustomAttributes(true).OfType <JsonIgnoreAttribute>().Any()).ToList();

            SAEONLogs.Verbose("Type: {Type} IgnoreProperties: {@IgnoreProperties}", itemType, ignores);
#if NET5_0
            var names = itemType.GetProperties().Where(property => property.GetCustomAttributes(true).OfType <JsonPropertyNameAttribute>().Any()).ToList();
            SAEONLogs.Verbose("Names: {@Names}", names);
#endif
            if (ignores.Any() ||
#if NET5_0
                names.Any()
#else
                false
#endif
                )
            {
                var map = result.Context.AutoMap(itemType);
                foreach (var memberMap in map.MemberMaps)
                {
                    var propName = memberMap.Data.Member.Name;
                    if (ignores.Any(i => i.Name == propName))
                    {
                        memberMap.Ignore();
                        updates = true;
                    }
#if NET5_0
                    var name = names.FirstOrDefault(i => i.Name == propName);
                    if (name is not null)
                    {
                        var newName = name.GetCustomAttribute <JsonPropertyNameAttribute>(true).Name;
                        //SAEONLogs.Verbose("OldName: {OldName} NewName: {NewName}", propName, newName);
                        memberMap.Name(newName, propName);
                        updates = true;
                    }
#endif
                    //SAEONLogs.Verbose("MemberMap: {@MemberMap}", memberMap);
                }

                //SAEONLogs.Verbose("Map: {@Map}", map);
                if (updates)
                {
                    result.Context.RegisterClassMap(map);
                }
            }
            return(result);
        }
Esempio n. 17
0
        public List <DatasetModel> GetDatasets(int id, DatasetFilterModel filters)
        {
            using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters {
                { "Id", id }, { "Filters", filters }
            }))
            {
                try
                {
                    var estuary = dbContext.Estuaries
                                  .Include(i => i.Datasets)
                                  .ThenInclude(i => i.DatasetVariables)
                                  .Where(i => i.Id == id)
                                  .FirstOrDefault();
                    if (estuary is null)
                    {
                        return(new List <DatasetModel>());
                    }

                    var query = estuary.Datasets.SelectMany(i => i.DatasetVariables).AsQueryable();
                    if (!string.IsNullOrWhiteSpace(filters?.Type))
                    {
                        query = query.Where(i => i.Type == filters.Type);
                    }
                    if (!string.IsNullOrWhiteSpace(filters?.SubType))
                    {
                        query = query.Where(i => i.SubType == filters.SubType);
                    }
                    return(query
                           .OrderBy(i => i.Type)
                           .ThenBy(i => i.SubType)
                           .ThenBy(i => i.VariableName)
                           .ThenBy(i => i.Dataset.Date)
                           .ThenBy(i => i.Dataset.Name)
                           .Select(i =>
                                   new DatasetModel
                    {
                        Id = i.Id,
                        Type = i.Type,
                        SubType = i.SubType,
                        Variable = i.VariableName,
                        Date = i.Dataset.Date,
                        Dataset = string.IsNullOrWhiteSpace(i.Link) ? i.Dataset.Name : $"<a target='_blank' href='{i.Link.Replace("SAEDArchive", "Archive")}'>{i.Dataset.Name}</a>",
                    }).ToList());
                }
                catch (Exception ex)
                {
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }
Esempio n. 18
0
        public List <DocumentModel> GetLiterature(int id, LiteratureFilterModel filters)
        {
            using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters {
                { "Id", id }, { "Filters", filters }
            }))
            {
                try
                {
                    var estuary = dbContext.Estuaries.Include(i => i.Literatures.Where(i => !string.IsNullOrWhiteSpace(i.Link) && i.Available != "N")).Where(i => i.Id == id).FirstOrDefault();
                    if (estuary is null)
                    {
                        return(new List <DocumentModel>());
                    }

                    var query = estuary.Literatures.AsQueryable();
                    if (!string.IsNullOrWhiteSpace(filters?.Type))
                    {
                        query = query.Where(i => i.Type == filters.Type);
                    }
                    if (!string.IsNullOrWhiteSpace(filters?.SubType))
                    {
                        query = query.Where(i => i.SubType == filters.SubType);
                    }
                    return(query
                           .Where(i => System.IO.File.Exists(Path.Combine(env.ContentRootPath, i.Link.RemoveStartingBackSlash().RemoveStartingForwardSlash())))
                           .OrderBy(i => i.Type)
                           .ThenBy(i => i.SubType)
                           .ThenBy(i => i.Published)
                           .ThenBy(i => i.Year)
                           .ThenBy(i => i.Author)
                           .ThenBy(i => i.Title)
                           .Select(i =>
                                   new DocumentModel
                    {
                        Id = i.Id,
                        Type = i.Type,
                        SubType = i.SubType,
                        Author = i.Author,
                        Year = i.Year,
                        //Year = i.Published.ToShortDateString(),
                        Title = i.Title,
                        Link = i.Link
                    }).ToList());
                }
                catch (Exception ex)
                {
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }
Esempio n. 19
0
 public static async Task LogAsync(SAEISContext dbContext, HttpRequest request, string description = null)
 {
     using (SAEONLogs.MethodCall(typeof(RequestLogger)))
     {
         try
         {
             dbContext.RequestLogs.Add(await CreateRequestLog(request, description));
             await dbContext.SaveChangesAsync();
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
         }
     }
 }
Esempio n. 20
0
 public Startup(IConfiguration configuration, IWebHostEnvironment environment)
 {
     using (SAEONLogs.MethodCall(GetType()))
     {
         try
         {
             Configuration = configuration;
             Environment   = environment;
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
Esempio n. 21
0
 public static void Main(string[] args)
 {
     SAEONLogs.CreateConfiguration().Initialize();
     try
     {
         CreateHostBuilder(args).Build().Run();
     }
     catch (Exception ex)
     {
         SAEONLogs.Exception(ex);
         throw;
     }
     finally
     {
         SAEONLogs.ShutDown();
     }
 }
Esempio n. 22
0
        public async Task <FileContentResult> Get(int id, int width)
        {
            using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters {
                { nameof(id), id }, { nameof(width), width }
            }))
            {
                try
                {
                    var image = await dbContext.Images.FirstOrDefaultAsync(i => i.Id == id);

                    if (image == null)
                    {
                        throw new ArgumentOutOfRangeException(nameof(id));
                    }
                    var fileName = Path.Combine(environment.ContentRootPath, image.Link.RemoveStartingBackSlash().RemoveStartingForwardSlash());
                    // Try load from cache
                    var cacheKey = $"{id},{width}";
                    if (memoryCache.TryGetValue(cacheKey, out byte[] imageBytes))
 public static string ToCSV <T>(this List <T> list) where T : class
 {
     using (SAEONLogs.MethodCall(typeof(ListOfTExtensions)))
     {
         try
         {
             using var writer = new StringWriter();
             using var csv    = CsvWriterHelper.GetCsvWriter(writer, list);
             csv.WriteRecords(list);
             writer.Flush();
             return(writer.ToString());
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
Esempio n. 24
0
 public IActionResult ClaimsUser()
 {
     using (SAEONLogs.MethodCall(GetType()))
     {
         try
         {
             var result = HttpContext.UserInfo();
             SAEONLogs.Information("UserInfo: {@UserInfo}", result);
             return(new JsonResult(result, new JsonSerializerOptions {
                 WriteIndented = true
             }));
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
Esempio n. 25
0
 public List <MapModel> GetMaps(int id, MapFilterModel filters)
 {
     using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters {
         { "Id", id }, { "Filters", filters }
     }))
     {
         try
         {
             var estuary = dbContext.Estuaries.Include(i => i.Maps.Where(i => i.Available != "N")).Where(i => i.Id == id).FirstOrDefault();
             if (estuary is null)
             {
                 return(new List <MapModel>());
             }
             var query = estuary.Maps.AsQueryable();
             if (!string.IsNullOrWhiteSpace(filters?.Type))
             {
                 query = query.Where(i => i.Type == filters.Type);
             }
             if (!string.IsNullOrWhiteSpace(filters?.SubType))
             {
                 query = query.Where(i => i.SubType == filters.SubType);
             }
             return(query
                    .OrderBy(i => i.Type)
                    .ThenBy(i => i.SubType)
                    .ThenBy(i => i.Name)
                    .Select(i =>
                            new MapModel
             {
                 Id = i.Id,
                 Type = i.Type,
                 SubType = i.SubType,
                 Name = Helpers.LinkHtml(i.Link, i.Name),
             }).ToList());
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
Esempio n. 26
0
        public async Task <PhysicalFileResult> Get(int id)
        {
            using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters {
                { nameof(id), id }
            }))
            {
                try
                {
                    var literature = await dbContext.Literatures.FirstOrDefaultAsync(i => i.Id == id);

                    //Guard.IsNotNull(image, nameof(image));
                    if (literature == null)
                    {
                        throw new ArgumentOutOfRangeException(nameof(id));
                    }
                    var    fileName    = Path.Combine(environment.ContentRootPath, literature.Link.RemoveStartingBackSlash().RemoveStartingForwardSlash());
                    string contentType = MediaTypeNames.Application.Octet;
                    if (Path.GetExtension(fileName) == ".pdf")
                    {
                        contentType = MediaTypeNames.Application.Pdf;
                    }
                    else if (Path.GetExtension(fileName) == ".doc")
                    {
                        contentType = "application/msword";
                    }
                    var result             = new PhysicalFileResult(fileName, contentType);
                    var contentDisposition = new ContentDispositionHeaderValue("inline")
                    {
                        FileName = Path.GetFileName(fileName)
                    };
                    Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
                    await RequestLogger.LogAsync(dbContext, Request, $"{literature.Title}|{literature.Link}");

                    return(result);
                }
                catch (Exception ex)
                {
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }
Esempio n. 27
0
 public static byte[] ToExcel <T>(this List <T> list, bool useAttributes = false) where T : class
 {
     using (SAEONLogs.MethodCall(typeof(ListOfTExtensions)))
     {
         try
         {
             using (var ms = new MemoryStream())
             {
                 using (var doc = ExcelSaxHelper.CreateSpreadsheet(ms, list, useAttributes))
                 {
                     doc.Save();
                 }
                 return(ms.ToArray());
             }
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
Esempio n. 28
0
 private IQueryable <Estuary> GetData(FilterModel filters)
 {
     using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters {
         { "Filters", filters }
     }))
     {
         try
         {
             var query = dbContext.Estuaries.AsQueryable();
             if (!string.IsNullOrWhiteSpace(filters?.Name))
             {
                 query = query.Where(i => EF.Functions.Like(i.Name, $"%{filters.Name}%"));
             }
             if (filters?.Classification.HasValue ?? false)
             {
                 query = query.Where(i => i.ClassificationId == filters.Classification);
             }
             if (filters?.Region.HasValue ?? false)
             {
                 query = query.Where(i => i.RegionId == filters.Region);
             }
             if (filters?.Condition.HasValue ?? false)
             {
                 query = query.Where(i => i.ConditionId == filters.Condition);
             }
             if (filters?.Province.HasValue ?? false)
             {
                 query = query.Where(i => i.ProvinceId == filters.Province);
             }
             return(query.OrderBy(i => i.Name));
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
Esempio n. 29
0
        public AzureCosmosDB(string databaseId, string containerId, string partitionKey, bool allowBulkExecution = false)
        {
            using (SAEONLogs.MethodCall <T>(GetType()))
            {
                try
                {
                    var cosmosDBUrl = ConfigurationManager.AppSettings["AzureCosmosDBUrl"];
                    if (string.IsNullOrWhiteSpace(cosmosDBUrl))
                    {
                        throw new ArgumentNullException("AppSettings.AzureCosmosDBUrl cannot be null");
                    }

                    var authKey = ConfigurationManager.AppSettings["AzureCosmosDBAuthKey"];
                    if (string.IsNullOrWhiteSpace(authKey))
                    {
                        throw new ArgumentNullException("AppSettings.AzureCosmosDBAuthKey cannot be null");
                    }
                    var clientOptions = new CosmosClientOptions
                    {
                        AllowBulkExecution = allowBulkExecution,
                        MaxRetryAttemptsOnRateLimitedRequests = int.Parse(ConfigurationManager.AppSettings["AzureCosmosDBRetries"] ?? DefaultRetries.ToString()),
                        MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromSeconds(int.Parse(ConfigurationManager.AppSettings["AzureCosmosDBRetryWaitSecs"] ?? DefaultRetryWaitSecs.ToString()))
                    };
                    client       = new CosmosClient(cosmosDBUrl, authKey, clientOptions);
                    DatabaseId   = databaseId;
                    ContainerId  = containerId;
                    PartitionKey = partitionKey;
                    Throughput   = int.Parse(ConfigurationManager.AppSettings["AzureCosmosDBThroughput"] ?? DefaultThroughput.ToString());
                    SAEONLogs.Information("CosmosDbUrl: {CosmosDbUrl} Database: {DatabaseId} Container: {ContainerId} PartitionKey: {PartitionKey} Throughput: {Throughput} BulkExecution: {BulkExection}",
                                          cosmosDBUrl, DatabaseId, ContainerId, PartitionKey, Throughput, allowBulkExecution);
                }
                catch (Exception ex)
                {
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }
Esempio n. 30
0
        public async Task EnsureDatabaseAsync()
        {
            if (database is not null)
            {
                return;
            }

            using (SAEONLogs.MethodCall <T>(GetType(), new MethodCallParameters {
                { "DatabaseId", DatabaseId }
            }))
            {
                try
                {
                    database = await client.CreateDatabaseIfNotExistsAsync(DatabaseId).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    database = null;
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }