Example #1
0
        public static async Task <GenerationReturn> Validate(MapComponentDto mapComponent)
        {
            var rootDirectoryCheck = UserSettingsUtilities.ValidateLocalSiteRootDirectory();

            if (!rootDirectoryCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Root Directory: {rootDirectoryCheck.Item2}",
                                                    mapComponent.Map.ContentId));
            }

            var commonContentCheck = await CommonContentValidation.ValidateMapComponent(mapComponent);

            if (!commonContentCheck.valid)
            {
                return(await GenerationReturn.Error(commonContentCheck.explanation, mapComponent.Map.ContentId));
            }

            var updateFormatCheck =
                CommonContentValidation.ValidateUpdateContentFormat(mapComponent.Map.UpdateNotesFormat);

            if (!updateFormatCheck.isValid)
            {
                return(await GenerationReturn.Error(updateFormatCheck.explanation, mapComponent.Map.ContentId));
            }

            return(await GenerationReturn.Success("GeoJson Content Validation Successful"));
        }
Example #2
0
        public static async Task <GenerationReturn> Validate(LinkContent linkContent)
        {
            var rootDirectoryCheck = UserSettingsUtilities.ValidateLocalSiteRootDirectory();

            if (!rootDirectoryCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Root Directory: {rootDirectoryCheck.Item2}",
                                                    linkContent.ContentId));
            }

            if (linkContent == null)
            {
                return(await GenerationReturn.Error("Link Content is Null?"));
            }

            var(createdUpdatedValid, createdUpdatedValidationMessage) =
                CommonContentValidation.ValidateCreatedAndUpdatedBy(linkContent, linkContent.Id < 1);

            if (!createdUpdatedValid)
            {
                return(await GenerationReturn.Error(createdUpdatedValidationMessage, linkContent.ContentId));
            }

            var urlValidation =
                await CommonContentValidation.ValidateLinkContentLinkUrl(linkContent.Url, linkContent.ContentId);

            if (!urlValidation.isValid)
            {
                return(await GenerationReturn.Error(urlValidation.explanation, linkContent.ContentId));
            }

            return(await GenerationReturn.Success("Link Content Validation Successful"));
        }
Example #3
0
        public static async Task <GenerationReturn> Validate(ImageContent imageContent, FileInfo selectedFile)
        {
            var rootDirectoryCheck = UserSettingsUtilities.ValidateLocalSiteRootDirectory();

            if (!rootDirectoryCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Root Directory: {rootDirectoryCheck.Item2}",
                                                    imageContent.ContentId));
            }

            var mediaArchiveCheck = UserSettingsUtilities.ValidateLocalMediaArchive();

            if (!mediaArchiveCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Media Archive: {mediaArchiveCheck.Item2}",
                                                    imageContent.ContentId));
            }

            var commonContentCheck = await CommonContentValidation.ValidateContentCommon(imageContent);

            if (!commonContentCheck.valid)
            {
                return(await GenerationReturn.Error(commonContentCheck.explanation, imageContent.ContentId));
            }

            var updateFormatCheck = CommonContentValidation.ValidateUpdateContentFormat(imageContent.UpdateNotesFormat);

            if (!updateFormatCheck.isValid)
            {
                return(await GenerationReturn.Error(updateFormatCheck.explanation, imageContent.ContentId));
            }

            selectedFile.Refresh();

            if (!selectedFile.Exists)
            {
                return(await GenerationReturn.Error("Selected File doesn't exist?", imageContent.ContentId));
            }

            if (!FolderFileUtility.IsNoUrlEncodingNeeded(Path.GetFileNameWithoutExtension(selectedFile.Name)))
            {
                return(await GenerationReturn.Error("Limit File Names to A-Z a-z - . _", imageContent.ContentId));
            }

            if (!FolderFileUtility.PictureFileTypeIsSupported(selectedFile))
            {
                return(await GenerationReturn.Error("The file doesn't appear to be a supported file type.",
                                                    imageContent.ContentId));
            }

            if (await(await Db.Context()).ImageFilenameExistsInDatabase(selectedFile.Name, imageContent.ContentId))
            {
                return(await GenerationReturn.Error(
                           "This filename already exists in the database - image file names must be unique.",
                           imageContent.ContentId));
            }

            return(await GenerationReturn.Success("Image Content Validation Successful"));
        }
Example #4
0
        public static FileInfo ContentToExcelFileAsTable(List <object> toDisplay, string fileName,
                                                         bool openAfterSaving = true, bool limitRowHeight = true, IProgress <string> progress = null)
        {
            progress?.Report($"Starting transfer of {toDisplay.Count} to Excel");

            var file = new FileInfo(Path.Combine(UserSettingsUtilities.TempStorageDirectory().FullName,
                                                 $"{DateTime.Now:yyyy-MM-dd--HH-mm-ss}---{FolderFileUtility.TryMakeFilenameValid(fileName)}.xlsx"));

            progress?.Report($"File Name: {file.FullName}");

            progress?.Report("Creating Workbook");

            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add("Exported Data");

            progress?.Report("Inserting Data");

            ws.Cell(1, 1).InsertTable(toDisplay);

            progress?.Report("Applying Formatting");

            ws.Columns().AdjustToContents();

            foreach (var loopColumn in ws.ColumnsUsed().Where(x => x.Width > 70))
            {
                loopColumn.Width = 70;
                loopColumn.Style.Alignment.WrapText = true;
            }

            ws.Rows().AdjustToContents();

            if (limitRowHeight)
            {
                foreach (var loopRow in ws.RowsUsed().Where(x => x.Height > 70))
                {
                    loopRow.Height = 70;
                }
            }

            progress?.Report($"Saving Excel File {file.FullName}");

            wb.SaveAs(file.FullName);

            if (openAfterSaving)
            {
                progress?.Report($"Opening Excel File {file.FullName}");

                var ps = new ProcessStartInfo(file.FullName)
                {
                    UseShellExecute = true, Verb = "open"
                };
                Process.Start(ps);
            }

            return(file);
        }
        public static async Task AllPhotoMetadataToHtml(FileInfo selectedFile, StatusControlContext statusContext)
        {
            await ThreadSwitcher.ResumeBackgroundAsync();

            if (selectedFile == null)
            {
                statusContext.ToastError("No photo...");
                return;
            }

            selectedFile.Refresh();

            if (!selectedFile.Exists)
            {
                statusContext.ToastError($"File {selectedFile.FullName} doesn't exist?");
                return;
            }

            var photoMetaTags = ImageMetadataReader.ReadMetadata(selectedFile.FullName);

            var tagHtml = photoMetaTags.SelectMany(x => x.Tags).OrderBy(x => x.DirectoryName).ThenBy(x => x.Name)
                          .ToList().Select(x => new
            {
                DataType = x.Type.ToString(),
                x.DirectoryName,
                Tag      = x.Name,
                TagValue = ObjectDumper.Dump(x.Description)
            }).ToHtmlTable(new { @class = "pure-table pure-table-striped" });

            var xmpDirectory = ImageMetadataReader.ReadMetadata(selectedFile.FullName).OfType <XmpDirectory>()
                               .FirstOrDefault();

            var xmpMetadata = xmpDirectory?.GetXmpProperties().Select(x => new { XmpKey = x.Key, XmpValue = x.Value })
                              .ToHtmlTable(new { @class = "pure-table pure-table-striped" });

            await ThreadSwitcher.ResumeForegroundAsync();

            var file = new FileInfo(Path.Combine(UserSettingsUtilities.TempStorageDirectory().FullName,
                                                 $"PhotoMetadata-{Path.GetFileNameWithoutExtension(selectedFile.Name)}-{DateTime.Now:yyyy-MM-dd---HH-mm-ss}.htm"));

            var htmlString =
                ($"<h1>Metadata Report:</h1><h1>{HttpUtility.HtmlEncode(selectedFile.FullName)}</h1><br><h1>Metadata - Part 1</h1><br>" +
                 tagHtml + "<br><br><h1>XMP - Part 2</h1><br>" + xmpMetadata)
                .ToHtmlDocumentWithPureCss("Photo Metadata", "body {margin: 12px;}");

            await File.WriteAllTextAsync(file.FullName, htmlString);

            var ps = new ProcessStartInfo(file.FullName)
            {
                UseShellExecute = true, Verb = "open"
            };

            Process.Start(ps);
        }
        public FileInfo WriteHtmlToTempFolder(IProgress <string> progress)
        {
            var possibleFileName = FolderFileUtility.TryMakeFilenameValid(ContentTitle);

            var possibleFile = new FileInfo(Path.Combine(UserSettingsUtilities.TempStorageDirectory().FullName,
                                                         $"HistoricEntries-{possibleFileName}-{DateTime.Now:yyyy-MM-dd---HH-mm-ss}.htm"));

            progress?.Report($"Writing File - {possibleFile.FullName}");

            File.WriteAllText(possibleFile.FullName, GenerateHtml(progress));

            possibleFile.Refresh();

            return(possibleFile);
        }
        public async Task A00_CreateTestSite()
        {
            var outSettings =
                await UserSettingsUtilities.SetupNewSite($"IronwoodForestTestSite-{DateTime.Now:yyyy-MM-dd-HH-mm-ss}",
                                                         DebugProgressTracker());

            TestSiteSettings                  = outSettings;
            TestSiteSettings.SiteName         = TestSiteName;
            TestSiteSettings.DefaultCreatedBy = TestDefaultCreatedBy;
            TestSiteSettings.SiteAuthors      = TestSiteAuthors;
            TestSiteSettings.SiteEmailTo      = TestSiteEmailTo;
            TestSiteSettings.SiteKeywords     = TestSiteKeywords;
            TestSiteSettings.SiteSummary      = TestSummary;
            TestSiteSettings.SiteUrl          = "IronwoodTest.com";
            await TestSiteSettings.EnsureDbIsPresent(DebugProgressTracker());
        }
        public static void ContentToExcelFileAsTable(List <object> toDisplay, string fileName)
        {
            var file = new FileInfo(Path.Combine(UserSettingsUtilities.TempStorageDirectory().FullName,
                                                 $"PhotoMetadata-{FolderFileUtility.TryMakeFilenameValid(fileName)}-{DateTime.Now:yyyy-MM-dd---HH-mm-ss}.xlsx"));

            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add("PW Data");

            ws.Cell(1, 1).InsertTable(toDisplay);
            wb.SaveAs(file.FullName);

            var ps = new ProcessStartInfo(file.FullName)
            {
                UseShellExecute = true, Verb = "open"
            };

            Process.Start(ps);
        }
        public static async Task <GenerationReturn> Validate(PhotoContent photoContent, FileInfo selectedFile)
        {
            var rootDirectoryCheck = UserSettingsUtilities.ValidateLocalSiteRootDirectory();

            if (!rootDirectoryCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Root Directory: {rootDirectoryCheck.Item2}",
                                                    photoContent.ContentId));
            }

            var mediaArchiveCheck = UserSettingsUtilities.ValidateLocalMediaArchive();

            if (!mediaArchiveCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Media Archive: {mediaArchiveCheck.Item2}",
                                                    photoContent.ContentId));
            }

            var commonContentCheck = await CommonContentValidation.ValidateContentCommon(photoContent);

            if (!commonContentCheck.valid)
            {
                return(await GenerationReturn.Error(commonContentCheck.explanation, photoContent.ContentId));
            }

            var updateFormatCheck = CommonContentValidation.ValidateUpdateContentFormat(photoContent.UpdateNotesFormat);

            if (!updateFormatCheck.isValid)
            {
                return(await GenerationReturn.Error(updateFormatCheck.explanation, photoContent.ContentId));
            }

            selectedFile.Refresh();

            var photoFileValidation =
                await CommonContentValidation.PhotoFileValidation(selectedFile, photoContent?.ContentId);

            if (!photoFileValidation.isValid)
            {
                return(await GenerationReturn.Error(photoFileValidation.explanation, photoContent.ContentId));
            }

            return(await GenerationReturn.Success("Photo Content Validation Successful"));
        }
Example #10
0
        public static async Task <GenerationReturn> Validate(NoteContent noteContent)
        {
            var rootDirectoryCheck = UserSettingsUtilities.ValidateLocalSiteRootDirectory();

            if (!rootDirectoryCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Root Directory: {rootDirectoryCheck.Item2}",
                                                    noteContent.ContentId));
            }

            var commonContentCheck = await CommonContentValidation.ValidateContentCommon(noteContent);

            if (!commonContentCheck.valid)
            {
                return(await GenerationReturn.Error(commonContentCheck.explanation, noteContent.ContentId));
            }

            return(await GenerationReturn.Success("Note Content Validation Successful"));
        }
Example #11
0
        public async Task A00_CreateTestSite()
        {
            var outSettings = await UserSettingsUtilities.SetupNewSite(
                $"TrailNotesTestSite-{DateTime.Now:yyyy-MM-dd-HH-mm-ss}", DebugTrackers.DebugProgressTracker());

            TestSiteSettings                  = outSettings;
            TestSiteSettings.SiteName         = TestSiteName;
            TestSiteSettings.DefaultCreatedBy = TestDefaultCreatedBy;
            TestSiteSettings.SiteAuthors      = TestSiteAuthors;
            TestSiteSettings.SiteEmailTo      = TestSiteEmailTo;
            TestSiteSettings.SiteKeywords     = TestSiteKeywords;
            TestSiteSettings.SiteSummary      = TestSummary;
            TestSiteSettings.SiteUrl          = "localhost";
            await TestSiteSettings.EnsureDbIsPresent(DebugTrackers.DebugProgressTracker());

            await TestSiteSettings.WriteSettings();

            UserSettingsSingleton.CurrentSettings().InjectFrom(TestSiteSettings);
        }
Example #12
0
        public App()
        {
            Tracker = new Tracker(new JsonFileStore(UserSettingsUtilities.StorageDirectory().FullName));

            Tracker.Configure <Window>()
            .Id(w => w.Name, SystemInformation.VirtualScreen.Size)     // <-- include the screen resolution in the id
            .Properties(w => new
            {
                w.Top,
                w.Width,
                w.Height,
                w.Left,
                w.WindowState
            }).PersistOn(nameof(Window.Closing)).StopTrackingOn(nameof(Window.Closing));

            Tracker.Configure <MainWindow>().Properties(x => new { x.RecentSettingsFilesNames });
#if !DEBUG
            DispatcherUnhandledException += App_DispatcherUnhandledException;
#endif
        }
Example #13
0
        public static async Task PdfPageToImageWithPdfToCairo(StatusControlContext statusContext,
                                                              List <FileContent> selected, int pageNumber)
        {
            await ThreadSwitcher.ThreadSwitcher.ResumeBackgroundAsync();


            var pdfToCairoDirectoryString = UserSettingsSingleton.CurrentSettings().PdfToCairoExeDirectory;

            if (string.IsNullOrWhiteSpace(pdfToCairoDirectoryString))
            {
                statusContext.ToastError(
                    "Sorry - this function requires that pdftocairo.exe be on the system - please set the directory... ");
                return;
            }

            var pdfToCairoDirectory = new DirectoryInfo(pdfToCairoDirectoryString);

            if (!pdfToCairoDirectory.Exists)
            {
                statusContext.ToastError(
                    $"{pdfToCairoDirectory.FullName} doesn't exist? Check your pdftocairo bin directory setting.");
                return;
            }

            var pdfToCairoExe = new FileInfo(Path.Combine(pdfToCairoDirectory.FullName, "pdftocairo.exe"));

            if (!pdfToCairoExe.Exists)
            {
                statusContext.ToastError(
                    $"{pdfToCairoExe.FullName} doesn't exist? Check your pdftocairo bin directory setting.");
                return;
            }

            var toProcess = new List <(FileInfo targetFile, FileInfo destinationFile, FileContent content)>();

            foreach (var loopSelected in selected)
            {
                var targetFile = new FileInfo(Path.Combine(
                                                  UserSettingsSingleton.CurrentSettings().LocalSiteFileContentDirectory(loopSelected).FullName,
                                                  loopSelected.OriginalFileName));

                if (!targetFile.Exists)
                {
                    continue;
                }

                if (!targetFile.Extension.ToLower().Contains("pdf"))
                {
                    continue;
                }

                FileInfo destinationFile;
                if (pageNumber == 1)
                {
                    destinationFile = new FileInfo(Path.Combine(UserSettingsUtilities.TempStorageDirectory().FullName,
                                                                $"{Path.GetFileNameWithoutExtension(targetFile.Name)}-CoverPage.jpg"));

                    if (destinationFile.Exists)
                    {
                        destinationFile.Delete();
                        destinationFile.Refresh();
                    }
                }
                else
                {
                    destinationFile = new FileInfo(Path.Combine(UserSettingsUtilities.TempStorageDirectory().FullName,
                                                                $"{Path.GetFileNameWithoutExtension(targetFile.Name)}-Page.jpg"));
                }

                toProcess.Add((targetFile, destinationFile, loopSelected));
            }

            if (!toProcess.Any())
            {
                statusContext.ToastError("No PDFs found? This process can only generate PDF previews...");
                return;
            }

            foreach (var loopSelected in toProcess)
            {
                if (loopSelected.destinationFile.Directory == null)
                {
                    statusContext.ToastError(
                        $"Problem with {loopSelected.destinationFile.FullName} - Directory is Null?");
                    continue;
                }

                var executionParameters = pageNumber == 1
                    ? $"-jpeg -singlefile \"{loopSelected.targetFile.FullName}\" \"{Path.Combine(loopSelected.destinationFile.Directory.FullName, Path.GetFileNameWithoutExtension(loopSelected.destinationFile.FullName))}\""
                    : $"-jpeg -f {pageNumber} -l {pageNumber} \"{loopSelected.targetFile.FullName}\" \"{Path.Combine(loopSelected.destinationFile.Directory.FullName, Path.GetFileNameWithoutExtension(loopSelected.destinationFile.FullName))}\"";

                var(success, _, errorOutput) = ProcessHelpers.ExecuteProcess(pdfToCairoExe.FullName,
                                                                             executionParameters, statusContext.ProgressTracker());

                if (!success)
                {
                    if (await statusContext.ShowMessage("PDF Generation Problem",
                                                        $"Execution Failed for {loopSelected.content.Title} - Continue??{Environment.NewLine}{errorOutput}",
                                                        new List <string> {
                        "Yes", "No"
                    }) == "No")
                    {
                        return;
                    }

                    continue;
                }

                FileInfo updatedDestination = null;

                if (pageNumber == 1)
                {
                    //With the singlefile option pdftocairo uses your filename directly
                    loopSelected.destinationFile.Refresh();
                    updatedDestination = loopSelected.destinationFile;
                }
                else
                {
                    var directoryToSearch = loopSelected.destinationFile.Directory;

                    var possibleFiles = directoryToSearch
                                        .EnumerateFiles($"{Path.GetFileNameWithoutExtension(loopSelected.destinationFile.Name)}-*.jpg")
                                        .ToList();

                    foreach (var loopFiles in possibleFiles)
                    {
                        var fileNamePageNumber = loopFiles.Name.Split("-Page-").ToList().Last().Replace(".jpg", "");

                        if (int.TryParse(fileNamePageNumber, out var possiblePageNumber) &&
                            possiblePageNumber == pageNumber)
                        {
                            updatedDestination = loopFiles;
                            break;
                        }
                    }
                }

                if (updatedDestination == null || !updatedDestination.Exists)
                {
                    if (await statusContext.ShowMessage("PDF Generation Problem",
                                                        $"Execution Failed for {loopSelected.content.Title} - Continue??{Environment.NewLine}{errorOutput}",
                                                        new List <string> {
                        "Yes", "No"
                    }) == "No")
                    {
                        return;
                    }

                    continue;
                }

                await ThreadSwitcher.ThreadSwitcher.ResumeForegroundAsync();

                var newImage = new ImageContent {
                    ContentId = Guid.NewGuid()
                };

                if (pageNumber == 1)
                {
                    newImage.Title   = $"{loopSelected.content.Title} Cover Page";
                    newImage.Summary = $"Cover Page from {loopSelected.content.Title}.";
                }
                else
                {
                    newImage.Title   = $"{loopSelected.content.Title} - Page {pageNumber}";
                    newImage.Summary = $"Page {pageNumber} from {loopSelected.content.Title}.";
                }

                newImage.ShowInSearch      = false;
                newImage.Folder            = loopSelected.content.Folder;
                newImage.Tags              = loopSelected.content.Tags;
                newImage.Slug              = SlugUtility.Create(true, newImage.Title);
                newImage.BodyContentFormat = ContentFormatDefaults.Content.ToString();
                newImage.BodyContent       = $"Generated by pdftocairo from {BracketCodeFiles.Create(loopSelected.content)}.";
                newImage.UpdateNotesFormat = ContentFormatDefaults.Content.ToString();

                var editor = new ImageContentEditorWindow(newImage, updatedDestination);
                editor.Show();

                await ThreadSwitcher.ThreadSwitcher.ResumeBackgroundAsync();
            }
        }
Example #14
0
        public static async Task <GenerationReturn> Validate(LineContent lineContent)
        {
            var rootDirectoryCheck = UserSettingsUtilities.ValidateLocalSiteRootDirectory();

            if (!rootDirectoryCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Root Directory: {rootDirectoryCheck.Item2}",
                                                    lineContent.ContentId));
            }

            var commonContentCheck = await CommonContentValidation.ValidateContentCommon(lineContent);

            if (!commonContentCheck.valid)
            {
                return(await GenerationReturn.Error(commonContentCheck.explanation, lineContent.ContentId));
            }

            var updateFormatCheck = CommonContentValidation.ValidateUpdateContentFormat(lineContent.UpdateNotesFormat);

            if (!updateFormatCheck.isValid)
            {
                return(await GenerationReturn.Error(updateFormatCheck.explanation, lineContent.ContentId));
            }

            try
            {
                var serializer = GeoJsonSerializer.Create(SpatialHelpers.Wgs84GeometryFactory(), 3);

                using var stringReader = new StringReader(lineContent.Line);
                using var jsonReader   = new JsonTextReader(stringReader);
                var featureCollection = serializer.Deserialize <FeatureCollection>(jsonReader);
                if (featureCollection.Count < 1)
                {
                    return(await GenerationReturn.Error(
                               "The GeoJson for the line appears to have an empty Feature Collection?", lineContent.ContentId));
                }
                if (featureCollection.Count > 1)
                {
                    return(await GenerationReturn.Error(
                               "The GeoJson for the line appears to contain multiple elements? It should only contain 1 line...",
                               lineContent.ContentId));
                }
                if (featureCollection[0].Geometry is not LineString)
                {
                    return(await GenerationReturn.Error(
                               "The GeoJson for the line has one element but it isn't a LineString?", lineContent.ContentId));
                }
                var lineString = featureCollection[0].Geometry as LineString;
                if (lineString == null || lineString.Count < 1 || lineString.Length == 0)
                {
                    return(await GenerationReturn.Error("The LineString doesn't have any points or is zero length?",
                                                        lineContent.ContentId));
                }
            }
            catch (Exception e)
            {
                return(await GenerationReturn.Error(
                           $"Error parsing the FeatureCollection and/or problems checking the LineString {e.Message}",
                           lineContent.ContentId));
            }

            return(await GenerationReturn.Success("Line Content Validation Successful"));
        }
Example #15
0
        public static FileInfo PointContentToExcel(List <PointContentDto> toDisplay, string fileName,
                                                   bool openAfterSaving = true, IProgress <string> progress = null)
        {
            if (toDisplay == null || !toDisplay.Any())
            {
                return(null);
            }

            progress?.Report("Setting up list to transfer to Excel");

            var transformedList = toDisplay.Select(x => new PointContent().InjectFrom(x)).Cast <PointContent>().ToList();

            var detailList = new List <(Guid, string)>();

            foreach (var loopContent in toDisplay)
            {
                progress?.Report($"Processing {loopContent.Title} with {loopContent.PointDetails.Count} details");
                // ! This content format is used by ExcelContentImports !
                // Push the content into a compromise format that is ok for human generation (the target here is not creating 'by
                //  hand in Excel' rather taking something like GNIS data and concatenating/text manipulating the data into
                //  shape) and still ok for parsing in code
                foreach (var loopDetail in loopContent.PointDetails)
                {
                    detailList.Add((loopContent.ContentId,
                                    $"ContentId:{loopDetail.ContentId}||{Environment.NewLine}Type:{loopDetail.DataType}||{Environment.NewLine}Data:{loopDetail.StructuredDataAsJson}"));
                }
            }

            var file = new FileInfo(Path.Combine(UserSettingsUtilities.TempStorageDirectory().FullName,
                                                 $"{DateTime.Now:yyyy-MM-dd--HH-mm-ss}---{FolderFileUtility.TryMakeFilenameValid(fileName)}.xlsx"));

            progress?.Report($"File Name {file.FullName} - creating Excel Workbook");

            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add("Exported Data");

            progress?.Report("Inserting Content Data");

            var insertedTable = ws.Cell(1, 1).InsertTable(transformedList);

            progress?.Report("Adding Detail Columns...");

            var contentIdColumn = insertedTable.Row(1).Cells().Single(x => x.GetString() == "ContentId")
                                  .WorksheetColumn().ColumnNumber();

            //Create columns to the right of the existing table to hold the Point Details and expand the table
            var neededDetailColumns = detailList.GroupBy(x => x.Item1).Max(x => x.Count());

            var firstDetailColumn = insertedTable.Columns().Last().WorksheetColumn().ColumnNumber() + 1;

            for (var i = firstDetailColumn; i < firstDetailColumn + neededDetailColumns; i++)
            {
                ws.Cell(1, i).Value = $"PointDetail {i - firstDetailColumn + 1}";
            }

            if (neededDetailColumns > 0)
            {
                insertedTable.Resize(ws.RangeUsed());
            }

            //Match in the point details (match rather than assume list/excel ordering)
            foreach (var loopRow in insertedTable.Rows().Skip(1))
            {
                var rowContentId = Guid.Parse(loopRow.Cell(contentIdColumn).GetString());
                var matchedData  = detailList.Where(x => x.Item1 == rowContentId);

                var currentColumn = firstDetailColumn;

                foreach (var loopDetail in matchedData)
                {
                    loopRow.Cell(currentColumn).Value = loopDetail.Item2;
                    currentColumn++;
                }
            }

            progress?.Report("Applying Formatting");

            //Format
            ws.Columns().AdjustToContents();

            foreach (var loopColumn in ws.ColumnsUsed().Where(x => x.Width > 70))
            {
                loopColumn.Width = 70;
                loopColumn.Style.Alignment.WrapText = true;
            }

            ws.Rows().AdjustToContents();

            foreach (var loopRow in ws.RowsUsed().Where(x => x.Height > 100))
            {
                loopRow.Height = 100;
            }

            progress?.Report($"Saving Excel File {file.FullName}");

            wb.SaveAs(file.FullName);

            if (openAfterSaving)
            {
                progress?.Report($"Opening Excel File {file.FullName}");

                var ps = new ProcessStartInfo(file.FullName)
                {
                    UseShellExecute = true, Verb = "open"
                };
                Process.Start(ps);
            }

            return(file);
        }
Example #16
0
        public static async Task <GenerationReturn> Validate(PointContentDto pointContent)
        {
            var rootDirectoryCheck = UserSettingsUtilities.ValidateLocalSiteRootDirectory();

            if (!rootDirectoryCheck.Item1)
            {
                return(await GenerationReturn.Error($"Problem with Root Directory: {rootDirectoryCheck.Item2}",
                                                    pointContent.ContentId));
            }

            var commonContentCheck = await CommonContentValidation.ValidateContentCommon(pointContent);

            if (!commonContentCheck.valid)
            {
                return(await GenerationReturn.Error(commonContentCheck.explanation, pointContent.ContentId));
            }

            var latitudeCheck = CommonContentValidation.LatitudeValidation(pointContent.Latitude);

            if (!latitudeCheck.isValid)
            {
                return(await GenerationReturn.Error(latitudeCheck.explanation, pointContent.ContentId));
            }

            var longitudeCheck = CommonContentValidation.LongitudeValidation(pointContent.Longitude);

            if (!longitudeCheck.isValid)
            {
                return(await GenerationReturn.Error(longitudeCheck.explanation, pointContent.ContentId));
            }

            var elevationCheck = CommonContentValidation.ElevationValidation(pointContent.Elevation);

            if (!elevationCheck.isValid)
            {
                return(await GenerationReturn.Error(elevationCheck.explanation, pointContent.ContentId));
            }

            var updateFormatCheck = CommonContentValidation.ValidateUpdateContentFormat(pointContent.UpdateNotesFormat);

            if (!updateFormatCheck.isValid)
            {
                return(await GenerationReturn.Error(updateFormatCheck.explanation, pointContent.ContentId));
            }

            foreach (var loopDetails in pointContent.PointDetails)
            {
                if (loopDetails.ContentId == Guid.Empty)
                {
                    return(await GenerationReturn.Error("Point Detail Data must have a valid Content Id",
                                                        loopDetails.ContentId));
                }
                if (loopDetails.PointContentId != pointContent.ContentId)
                {
                    return(await GenerationReturn.Error(
                               $"{loopDetails.DataType} Point Detail isn't assigned to the current point?",
                               loopDetails.ContentId));
                }
                if (string.IsNullOrWhiteSpace(loopDetails.DataType))
                {
                    return(await GenerationReturn.Error("Point Detail Data Type doesn't have a value",
                                                        loopDetails.ContentId));
                }
                if (string.IsNullOrWhiteSpace(loopDetails.StructuredDataAsJson))
                {
                    return(await GenerationReturn.Error($"{loopDetails.DataType} Point Detail doesn't have any data?",
                                                        loopDetails.ContentId));
                }
                try
                {
                    var content =
                        Db.PointDetailDataFromIdentifierAndJson(loopDetails.DataType, loopDetails.StructuredDataAsJson);
                    var contentValidation = content.Validate();

                    if (!contentValidation.isValid)
                    {
                        return(await GenerationReturn.Error(
                                   $"{loopDetails.DataType} Point Detail: {contentValidation.validationMessage}",
                                   pointContent.ContentId));
                    }
                }
                catch (Exception e)
                {
                    return(await GenerationReturn.Error(
                               $"Exception loading the Structured Data for {loopDetails.DataType} Point Detail {e.Message}",
                               pointContent.ContentId));
                }
            }

            return(await GenerationReturn.Success("Point Content Validation Successful"));
        }
Example #17
0
 public static UserSettings CurrentSettings()
 {
     return(_userSettings ??= UserSettingsUtilities.ReadSettings(null).Result);
 }