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 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 RenameSelectedFile(FileInfo selectedFile, StatusControlContext statusContext, Action <FileInfo> setSelectedFile) { if (selectedFile == null || !selectedFile.Exists) { statusContext.ToastWarning("No file to rename?"); return; } var newName = await statusContext.ShowStringEntry("Rename File", $"Rename {Path.GetFileNameWithoutExtension(selectedFile.Name)} - " + "File Names must be limited to A-Z a-z 0-9 - . _ :", Path.GetFileNameWithoutExtension(selectedFile.Name)); if (!newName.Item1) { return; } var cleanedName = newName.Item2.TrimNullToEmpty(); if (string.IsNullOrWhiteSpace(cleanedName)) { statusContext.ToastError("Can't rename the file to an empty string..."); return; } var noExtensionCleaned = Path.GetFileNameWithoutExtension(cleanedName); if (string.IsNullOrWhiteSpace(noExtensionCleaned)) { statusContext.ToastError("Not a valid filename..."); return; } if (!FolderFileUtility.IsNoUrlEncodingNeeded(noExtensionCleaned)) { statusContext.ToastError("File Names must be limited to A - Z a - z 0 - 9 - . _"); return; } var moveToName = Path.Combine(selectedFile.Directory?.FullName ?? string.Empty, $"{noExtensionCleaned}{Path.GetExtension(selectedFile.Name)}"); try { File.Copy(selectedFile.FullName, moveToName); } catch (Exception e) { await EventLogContext.TryWriteExceptionToLog(e, statusContext.StatusControlContextId.ToString(), "Exception while trying to rename file."); statusContext.ToastError($"Error Copying File: {e.Message}"); return; } var finalFile = new FileInfo(moveToName); if (!finalFile.Exists) { statusContext.ToastError("Unknown error renaming file - original file still selected."); return; } try { setSelectedFile(finalFile); } catch (Exception e) { statusContext.ToastError($"Error setting selected file - {e.Message}"); return; } statusContext.ToastSuccess($"Selected file now {selectedFile.FullName}"); }
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 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); }
public void NoEncodingShouldPassTest(string toFail) { Assert.True(FolderFileUtility.IsNoUrlEncodingNeededLowerCase(toFail)); }
public void NoEncodingLowerShouldFailTest(string toFail) { Assert.False(FolderFileUtility.IsNoUrlEncodingNeededLowerCase(toFail)); }
/// <summary> /// </summary> /// <param name="userFilename">File Name for the </param> /// <param name="progress"></param> /// <returns></returns> public static async Task <UserSettings> SetupNewSite(string userFilename, IProgress <string> progress) { if (!FolderFileUtility.IsValidWindowsFileSystemFilename(userFilename)) { throw new InvalidDataException("New site input must be a valid filename."); } var newSettings = new UserSettings(); var rootDirectory = new DirectoryInfo(Path.Combine(StorageDirectory().FullName, userFilename)); progress?.Report("Creating new settings - looking for home..."); var fileNumber = 1; while (rootDirectory.Exists) { rootDirectory = new DirectoryInfo(Path.Combine(StorageDirectory().FullName, $"{userFilename}-{fileNumber}")); rootDirectory.Refresh(); progress?.Report($"Trying {rootDirectory.FullName}..."); fileNumber++; } rootDirectory.Create(); var siteRoot = new DirectoryInfo(Path.Combine(rootDirectory.FullName, "GeneratedSite")); newSettings.LocalSiteRootDirectory = siteRoot.FullName; progress?.Report($"Local Site Root set to {siteRoot.FullName}"); newSettings.DatabaseFile = Path.Combine(rootDirectory.FullName, $"PointlessWaymarksCmsDatabase-{userFilename}.db"); var mediaDirectory = new DirectoryInfo(Path.Combine(rootDirectory.FullName, "MediaArchive")); newSettings.LocalMediaArchive = mediaDirectory.FullName; progress?.Report("Adding fake default values..."); newSettings.DefaultCreatedBy = "Pointless Waymarks CMS"; newSettings.SiteName = userFilename; newSettings.SiteUrl = "localhost.com"; newSettings.SiteKeywords = "new,site"; newSettings.SiteSummary = "A new site."; newSettings.SiteAuthors = "Pointless Waymarks CMS"; newSettings.SiteEmailTo = "*****@*****.**"; SettingsFileName = Path.Combine(rootDirectory.FullName, $"PointlessWaymarksCmsSettings-{userFilename}.json"); progress?.Report("Writing Settings"); await WriteSettings(newSettings); progress?.Report("Setting up directory structure."); newSettings.VerifyOrCreateAllTopLevelFolders(progress); return(newSettings); }