Beispiel #1
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;
                }
            }
        }
Beispiel #3
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;
             }
         }
     }
 }
Beispiel #4
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;
         }
     }
 }
Beispiel #5
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;
         }
     }
 }
Beispiel #6
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;
         }
     }
 }
Beispiel #7
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;
         }
     }
 }
Beispiel #8
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;
         }
     }
 }
Beispiel #9
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;
                }
            }
        }
Beispiel #10
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;
                }
            }
        }
        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;
                }
            }
        }
Beispiel #12
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;
         }
     }
 }
Beispiel #13
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;
                }
            }
        }
Beispiel #14
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;
                }
            }
        }
Beispiel #15
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);
         }
     }
 }
Beispiel #16
0
 public Startup(IConfiguration configuration, IWebHostEnvironment environment)
 {
     using (SAEONLogs.MethodCall(GetType()))
     {
         try
         {
             Configuration = configuration;
             Environment   = environment;
         }
         catch (Exception ex)
         {
             SAEONLogs.Exception(ex);
             throw;
         }
     }
 }
Beispiel #17
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();
     }
 }
 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;
         }
     }
 }
Beispiel #19
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;
         }
     }
 }
Beispiel #20
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;
         }
     }
 }
Beispiel #21
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;
                }
            }
        }
Beispiel #22
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;
         }
     }
 }
Beispiel #23
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;
         }
     }
 }
Beispiel #24
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;
                }
            }
        }
Beispiel #25
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;
                }
            }
        }
Beispiel #26
0
        public IActionResult Index(int?id)
        {
            using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters {
                { "Id", id }
            }))
            {
                try
                {
                    if (!id.HasValue)
                    {
                        return(RedirectToAction("Index", "Search"));
                    }

                    var estuary = dbContext.Estuaries
                                  .Include(i => i.Classification)
                                  .Include(i => i.Condition)
                                  .Include(i => i.Region)
                                  .Include(i => i.Geomorphology)
                                  .Include(i => i.InfoAvailable)
                                  .Include(i => i.WaterQuality)
                                  .Include(i => i.ManagementClassification)
                                  .Include(i => i.SanctuaryProtection)
                                  .Include(i => i.UndevelopedMargin)
                                  .Include(i => i.WaterRequirement)
                                  .Include(i => i.PriorityForRehabilitation)
                                  .FirstOrDefault(i => i.Id == id.Value);
                    if (estuary is null)
                    {
                        return(RedirectToAction("Index", "Search"));
                    }
                    var model = new InfoViewModel
                    {
                        Estuary         = estuary,
                        LiteratureTypes = ListItems.SelectListFrom(dbContext.Literatures.Where(i => !string.IsNullOrWhiteSpace(i.Type)).Select(i => new StringListItem {
                            Text = i.Type
                        }).Distinct()),
                        LiteratureSubTypes = ListItems.SelectListFrom(dbContext.Literatures.Where(i => !string.IsNullOrWhiteSpace(i.SubType)).Select(i => new StringListItem {
                            Text = i.SubType
                        }).Distinct()),
                        MapTypes = ListItems.SelectListFrom(dbContext.Maps.Where(i => !string.IsNullOrWhiteSpace(i.Type)).Select(i => new StringListItem {
                            Text = i.Type
                        }).Distinct()),
                        MapSubTypes = ListItems.SelectListFrom(dbContext.Maps.Where(i => !string.IsNullOrWhiteSpace(i.SubType)).Select(i => new StringListItem {
                            Text = i.SubType
                        }).Distinct()),
                        ImageTypes = ListItems.SelectListFrom(dbContext.Images.Where(i => !string.IsNullOrWhiteSpace(i.Type)).Select(i => new StringListItem {
                            Text = i.Type
                        }).Distinct()),
                        ImageSubTypes = ListItems.SelectListFrom(dbContext.Images.Where(i => !string.IsNullOrWhiteSpace(i.SubType)).Select(i => new StringListItem {
                            Text = i.SubType
                        }).Distinct()),
                        DatasetTypes = ListItems.SelectListFrom(dbContext.Datasets.SelectMany(i => i.DatasetVariables).Where(i => !string.IsNullOrWhiteSpace(i.Type)).Select(i => new StringListItem {
                            Text = i.Type
                        }).Distinct()),
                        DatasetSubTypes = ListItems.SelectListFrom(dbContext.Datasets.SelectMany(i => i.DatasetVariables).Where(i => !string.IsNullOrWhiteSpace(i.SubType)).Select(i => new StringListItem {
                            Text = i.SubType
                        }).Distinct())
                    };
                    return(View(model));
                }
                catch (Exception ex)
                {
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            using (SAEONLogs.MethodCall(GetType()))
            {
                try
                {
                    SAEONLogs.Debug("IntrospectionUrl: {IntrospectionUrl}", Options.IntrospectionUrl);
                    var token = Request.GetBearerToken();
                    if (string.IsNullOrWhiteSpace(token))
                    {
                        SAEONLogs.Error("ODPAuthorization Failed, no token");
                        return(AuthenticateResult.Fail("No token"));
                    }
                    SAEONLogs.Debug("Token: {Token}", token);
                    // Validate token
                    using (var client = new HttpClient())
                    {
                        client.SetBearerToken(token);
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json));
                        using (var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("token", token) }))
                        {
                            var response = await client.PostAsync(new Uri(Options.IntrospectionUrl), formContent).ConfigureAwait(false);

                            if (!response.IsSuccessStatusCode)
                            {
                                SAEONLogs.Error("HttpError: {StatusCode} {Reason}", response.StatusCode, response.ReasonPhrase);
                                SAEONLogs.Error("Response: {Response}", await response.Content.ReadAsStringAsync().ConfigureAwait(false));
                            }
                            response.EnsureSuccessStatusCode();
                            var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                            SAEONLogs.Information("Response: {Response}", json);
                            var jObj     = JObject.Parse(json);
                            var isActive = jObj.Value <bool>("active");
                            if (!isActive)
                            {
                                SAEONLogs.Error("ODPAuthorization, invalid token {Token}", token);
                                return(AuthenticateResult.Fail("Invalid token"));
                            }
                            if (jObj["ext"] is null)
                            { // Access token
                                var clientId = jObj.Value <string>("client_id");
                                var claims   = new List <Claim> {
                                    new Claim(ODPAuthenticationDefaults.ClientIdClaim, clientId),
                                    new Claim(ODPAuthenticationDefaults.AccessTokenClaim, token)
                                };
                                var identity  = new ClaimsIdentity(claims, ODPAuthenticationDefaults.AuthenticationScheme);
                                var principal = new ClaimsPrincipal(identity);
                                var ticket    = new AuthenticationTicket(principal, ODPAuthenticationDefaults.AuthenticationScheme);
                                SAEONLogs.Debug("ODPAuthentication access token succeeded Claims: {@Claims}", claims.ToClaimsList());
                                return(AuthenticateResult.Success(ticket));
                            }
                            else
                            {
                                var clientId  = jObj.Value <string>("client_id");
                                var userId    = jObj["ext"].Value <string>("user_id");
                                var userEmail = jObj["ext"].Value <string>("email");
                                var userRoles = from r in jObj["ext"]["access_rights"] select(string) r["role_name"];
                                SAEONLogs.Debug("User Id: {Id} Email: {Email}, Roles: {Role}", userId, userEmail, userRoles);
                                var claims = new List <Claim> {
                                    new Claim(ODPAuthenticationDefaults.ClientIdClaim, clientId),
                                    new Claim(ODPAuthenticationDefaults.IdTokenClaim, token),
                                    new Claim(ClaimTypes.NameIdentifier, userId),
                                    new Claim(ClaimTypes.Email, userId)
                                };
                                foreach (var userRole in userRoles)
                                {
                                    claims.Add(new Claim(ClaimTypes.Role, userRole));
                                }
                                if (userRoles.Contains("admin") || userRoles.Contains("Admin"))
                                {
                                    claims.Add(new Claim(ODPAuthenticationDefaults.AdminTokenClaim, true.ToString()));
                                }
                                var identity  = new ClaimsIdentity(claims, ODPAuthenticationDefaults.AuthenticationScheme);
                                var principal = new ClaimsPrincipal(identity);
                                var ticket    = new AuthenticationTicket(principal, ODPAuthenticationDefaults.AuthenticationScheme);
                                SAEONLogs.Debug("ODPAuthentication id token succeeded Claims: {@Claims}", claims.ToClaimsList());
                                return(AuthenticateResult.Success(ticket));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }
Beispiel #28
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            using (SAEONLogs.MethodCall(GetType()))
            {
                try
                {
                    //SAEONLogs.Information("ContentRoot: {contentRoot} WebRoot: {webRoot}", env.ContentRootPath, env.WebRootPath);
                    SAEONLogs.Information("Development: {IsDevelopment}", env.IsDevelopment());
                    if (env.IsDevelopment())
                    {
                        app.UseDeveloperExceptionPage();
                    }
                    else
                    {
                        app.UseExceptionHandler("/Home/Error");
                    }
                    app.UseHttpsRedirection();

                    app.UseResponseCompression();
                    app.UseResponseCaching();
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        OnPrepareResponse = ctx =>
                        {
                            ctx.Context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = $"public,max-age={Defaults.CacheDuration}";
                        }
                    });
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "node_modules")),
                        RequestPath  = "/node_modules",
                    });
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        FileProvider      = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Archive")),
                        RequestPath       = "/Archive",
                        OnPrepareResponse = ctx =>
                        {
                            ctx.Context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = $"public,max-age={Defaults.CacheDuration}";
                        }
                    });
                    var supportedCultures = new[]
                    {
                        new CultureInfo("en-GB")
                    };

                    app.UseRequestLocalization(new RequestLocalizationOptions
                    {
                        DefaultRequestCulture = new RequestCulture("en-GB"),
                        // Formatting numbers, dates, etc.
                        SupportedCultures = supportedCultures,
                        // UI strings that we have localized.
                        SupportedUICultures = supportedCultures
                    });

                    app.UseRouting();
                    app.UseCookiePolicy();
                    app.UseCors("SAEIS");
                    app.UseAuthentication();
                    app.UseAuthorization();

                    app.UseEndpoints(endpoints =>
                    {
                        endpoints.MapHealthChecks("/health");
                        endpoints.MapDefaultControllerRoute();
                        //endpoints.MapControllerRoute(
                        //    name: "default",
                        //    pattern: "{controller=Home}/{action=Index}/{id?}");
                        endpoints.MapRazorPages();
                    });
                }
                catch (Exception ex)
                {
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }
Beispiel #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            using (SAEONLogs.MethodCall(GetType()))
            {
                try
                {
                    SAEONLogs.Information("Configuring services");
                    services.AddApplicationInsightsTelemetry();
                    services.AddMemoryCache();
                    services.Configure <CookiePolicyOptions>(options =>
                    {
                        //SAEONLogs.Verbose("Options 1: {@Options}", options);
                        //options.CheckConsentNeeded = context => true;
                        options.Secure   = CookieSecurePolicy.Always;
                        options.HttpOnly = HttpOnlyPolicy.Always;
                        options.MinimumSameSitePolicy = SameSiteMode.None;
                        //options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                        //SAEONLogs.Verbose("Options 2: {@Options}", options);
                    });
                    //services.AddCors(options => options.AddPolicy("SAEIS", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
                    services.AddCors(options => options.AddPolicy("SAEIS", p => p.WithOrigins("https://*****:*****@Options}", options);
                    });
                    services.AddAuthorization();

                    services.AddControllers();
                    services.AddControllersWithViews();
                    services.AddRazorPages();

                    IFileProvider physicalProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory());
                    services.AddSingleton <IFileProvider>(physicalProvider);
                }
                catch (Exception ex)
                {
                    SAEONLogs.Exception(ex);
                    throw;
                }
            }
        }