public override void UpdateReferences(ReferencesData data) { using (EventLogContext _context = EventLogContext.Create(_databaseOptions, _databaseActions)) { _context.FillReferencesToSave(_system, data); _context.SaveChanges(); if (_referencesCache == null) { _referencesCache = new ReferencesDataCache(_system); } _referencesCache.FillByDatabaseContext(_context); } }
public EventLogExportMasterTests() { string configFilePath = GetConfigFile(); _settings = new CommonTestSettings( configFilePath, new EventLogPostgreSQLActions()); _optionsBuilder = new DbContextOptionsBuilder <EventLogContext>(); _optionsBuilder.UseNpgsql(_settings.ConnectionString); using (EventLogContext context = EventLogContext.Create(_optionsBuilder.Options, _settings.DBMSActions)) context.Database.EnsureDeleted(); }
public override EventLogPosition GetLastPosition() { if (_lastEventLogFilePosition != null) { return(_lastEventLogFilePosition); } EventLogPosition position; using (EventLogContext _context = EventLogContext.Create(_databaseOptions, _databaseActions)) position = _context.GetLastPosition(_system); _lastEventLogFilePosition = position; return(position); }
private static async Task <List <CoordinateZ> > OpenTopoElevation(HttpClient client, string openTopoDataSet, List <CoordinateZ> coordinates, IProgress <string>?progress) { if (!coordinates.Any()) { return(coordinates); } var partitionedCoordinates = coordinates.Partition(100).ToList(); var resultList = new List <ElevationResult>(); progress?.Report( $"{coordinates.Count} Coordinates for Elevation - querying in {partitionedCoordinates.Count} groups..."); foreach (var loopCoordinateGroups in partitionedCoordinates) { var requestUri = $"https://api.opentopodata.org/v1/{openTopoDataSet}?locations={string.Join("|", loopCoordinateGroups.Select(x => $"{x.Y},{x.X}"))}"; progress?.Report($"Sending request to {requestUri}"); var elevationReturn = await client.GetStringAsync(requestUri); progress?.Report($"Parsing Return from {requestUri}"); var elevationParsed = JsonSerializer.Deserialize <ElevationResponse>(elevationReturn); if (elevationParsed == null) { throw await EventLogContext.TryWriteExceptionToLog( new Exception("Could not parse information from the Elevation Service"), "Elevation Service", "requestUri: {requestUri}"); } resultList.AddRange(elevationParsed.Elevations); } progress?.Report("Assigning results to Coordinates"); foreach (var loopResults in resultList) { coordinates.Where(x => x.X == loopResults.Location.Longitude && x.Y == loopResults.Location.Latitude) .ToList().ForEach(x => x.Z = loopResults.Elevation ?? 0); } return(coordinates); }
public static bool HandleApplicationException(Exception ex) { EventLogContext.TryWriteExceptionToLogBlocking(ex, "App.xaml.cs", "AppDomain.CurrentDomain.UnhandledException"); var msg = $"Something went wrong...\r\n\r\n{ex.Message}\r\n\r\n" + "The error has been logged...\r\n\r\n" + "Do you want to continue?"; var res = MessageBox.Show(msg, "PointlessWaymarksCms App Error", MessageBoxButton.YesNo, MessageBoxImage.Error, MessageBoxResult.Yes); if (res.HasFlag(MessageBoxResult.No)) { return(false); } return(true); }
public static uint GetDpi(IntPtr hwnd, DpiType dpiType) { var screen = Screen.FromHandle(hwnd); var screenPoint = new Point((int)screen.Bounds.Left, (int)screen.Bounds.Top); var monitor = MonitorFromPoint(screenPoint, 2 /*MONITOR_DEFAULTTONEAREST*/); uint dpiX = 96; try { GetDpiForMonitor(monitor, dpiType, out dpiX, out _); } catch (Exception ex) { EventLogContext.TryWriteExceptionToLogBlocking(ex, "MainWindow.xaml.cs", "Failed to Get Dpi from Shcore.dll private static extern IntPtr GetDpiForMonitor"); } return(dpiX); }
private void ConfigureMongoDbDataAccess(ContainerBuilder builder) { builder.Register <IMongoDatabase>(x => EventLogContext.GetDatabase()) .Keyed <IMongoDatabase>(DataSourceType.InfrastructureMongo) .SingleInstance(); builder.Register((x, y) => new MongoDbDataSource(x.ResolveKeyed <IMongoDatabase>(DataSourceType.InfrastructureMongo))) .Keyed <IDataSource>(DataSourceType.InfrastructureMongo); builder.Register((x, y) => new GenericRepository(x.ResolveKeyed <IDataSource>(DataSourceType.InfrastructureMongo))) .Keyed <GenericRepository>(DataSourceType.InfrastructureMongo); builder.Register((x, y) => new GenericRepository(x.ResolveKeyed <IDataSource>(DataSourceType.InfrastructureMongo))) .Keyed <IGenericRepository>(DataSourceType.InfrastructureMongo) .As <IGenericRepository>(); builder.Register((x, y) => new GenericRepository(x.ResolveKeyed <IDataSource>(DataSourceType.InfrastructureMongo))) .Keyed <IAsyncGenericRepository>(DataSourceType.InfrastructureMongo) .As <IAsyncGenericRepository>(); }
public static async Task EnsureDbIsPresent(this UserSettings settings, IProgress <string> progress) { var possibleDbFile = new FileInfo(settings.DatabaseFile); if (possibleDbFile.Exists) { var sc = new ServiceCollection() // Add common FluentMigrator services .AddFluentMigratorCore().ConfigureRunner(rb => rb // Add SQLite support to FluentMigrator .AddSQLite() // Set the connection string .WithGlobalConnectionString($"Data Source={settings.DatabaseFile}") // Define the assembly containing the migrations .ScanIn(typeof(PointlessWaymarksContext).Assembly).For.Migrations()) // Enable logging to console in the FluentMigrator way .AddLogging(lb => lb.AddFluentMigratorConsole()) // Build the service provider .BuildServiceProvider(false); // Instantiate the runner var runner = sc.GetRequiredService <IMigrationRunner>(); // Execute the migrations runner.MigrateUp(); } progress?.Report("Checking for database files..."); var log = Db.Log().Result; await log.Database.EnsureCreatedAsync(); await EventLogContext.TryWriteStartupMessageToLog( $"Ensure Db Is Present - Settings File {SettingsFileName}", "User Settings Utilities"); var db = Db.Context().Result; await db.Database.EnsureCreatedAsync(); }
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 override void SetInformationSystem(InformationSystemsBase system) { using (EventLogContext _context = EventLogContext.Create(_databaseOptions, _databaseActions)) _system = _context.CreateOrUpdateInformationSystem(system); }
private void AssociatedObjectOnMouseDoubleClick(object sender, MouseButtonEventArgs e) { if (!(sender is TextBox textBox)) { return; } if (string.IsNullOrWhiteSpace(textBox.Text)) { return; } var mousePoint = Mouse.GetPosition(textBox); var characterPosition = AssociatedObject.GetCharacterIndexFromPoint(mousePoint, true); if (characterPosition < 0) { return; } var text = textBox.Text; var startingCharacter = text[characterPosition]; if (startingCharacter.IsWhiteSpaceCharacter()) { return; } var before = new List <char>(); for (var i = characterPosition - 1; i >= 0; i--) { var newCharacter = text[i]; if (newCharacter.IsWhiteSpaceCharacter()) { break; } before.Add(newCharacter); } before.Reverse(); var after = new List <char>(); for (var i = characterPosition; i < text.Length; i++) { var newCharacter = text[i]; if (newCharacter.IsWhiteSpaceCharacter()) { break; } after.Add(newCharacter); } var finalString = new string(before.Concat(after).ToArray()); if (finalString.Length < 3) { return; } var removeOuterContainers = true; while (removeOuterContainers) { var removal = StripContainerCharacters(finalString); if (removal.removed) { finalString = removal.returnString; if (finalString.Length < 3) { return; } } else { removeOuterContainers = false; } } (bool removed, string returnString) StripContainerCharacters(string toCheck) { if (toCheck.StartsWith("(") && toCheck.EndsWith(")")) { return(true, toCheck.Substring(1, toCheck.Length - 2).TrimNullToEmpty()); } if (toCheck.StartsWith("[") && toCheck.EndsWith("]")) { return(true, toCheck.Substring(1, toCheck.Length - 2).TrimNullToEmpty()); } if (toCheck.StartsWith("{") && toCheck.EndsWith("}")) { return(true, toCheck.Substring(1, toCheck.Length - 2).TrimNullToEmpty()); } if (toCheck.StartsWith("\"") && toCheck.EndsWith("\"")) { return(true, toCheck.Substring(1, toCheck.Length - 2).TrimNullToEmpty()); } if (toCheck.StartsWith("'") && toCheck.EndsWith("'")) { return(true, toCheck.Substring(1, toCheck.Length - 2).TrimNullToEmpty()); } if (toCheck.StartsWith(",") && toCheck.EndsWith(",")) { return(true, toCheck.Substring(1, toCheck.Length - 2).TrimNullToEmpty()); } return(false, toCheck); } var firstHttpUrlMatch = Regex.Match(finalString, @"\b(https?)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]", RegexOptions.IgnoreCase); if (firstHttpUrlMatch.Success) { Application.Current.Dispatcher.BeginInvoke(new Action(() => { try { var ps = new ProcessStartInfo(firstHttpUrlMatch.Value) { UseShellExecute = true, Verb = "open" }; Process.Start(ps); } catch (Exception ex) { EventLogContext.TryWriteExceptionToLogBlocking(ex, "TextBoxDoubleClickLauncher", $"Trying to process start {finalString}"); } })); } var firstFileMatch = Regex.Match(finalString, @"(?<drive> \b[a-z]:\\) (?<folder>(?>[^\\/:*?""<>|\x00-\x1F]{0,254}[^.\\/:*?""<>|\x00-\x1F]\\)*) (?<file> (?>[^\\/:*?""<>|\x00-\x1F]{0,254}[^.\\/:*?""<>|\x00-\x1F])?)" , RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); if (!firstFileMatch.Success || !firstFileMatch.Groups["drive"].Success || !firstFileMatch.Groups["folder"].Success) { return; } try { var directory = new DirectoryInfo(Path.Combine(firstFileMatch.Groups["drive"].Captures[0].Value, firstFileMatch.Groups["folder"].Captures[0].Value)); if (!directory.Exists) { return; } Application.Current.Dispatcher.BeginInvoke(new Action(() => { try { var ps = new ProcessStartInfo(directory.FullName) { UseShellExecute = true, Verb = "open" }; Process.Start(ps); } catch (Exception ex) { EventLogContext.TryWriteExceptionToLogBlocking(ex, "TextBoxDoubleClickLauncher", $"Trying to process start {finalString}"); } })); } catch (Exception ex) { EventLogContext.TryWriteExceptionToLogBlocking(ex, "TextBoxDoubleClickLauncher", $"Trying to process start {finalString}"); } }
public static async Task <ExcelContentTableImportResults> ImportExcelContentTable(IXLRange toProcess, IProgress <string> progress) { if (toProcess == null || toProcess.Rows().Count() < 2) { return new ExcelContentTableImportResults { HasError = true, ErrorNotes = "Nothing to process", ToUpdate = new List <ExcelImportContentUpdateSuggestion>() } } ; var headerInfo = new ExcelHeaderRow(toProcess.Row(1)); var errorNotes = new List <string>(); var updateList = new List <ExcelImportContentUpdateSuggestion>(); var db = await Db.Context(); var lastRow = toProcess.Rows().Last().RowNumber(); progress?.Report($"{lastRow} to Process"); foreach (var loopRow in toProcess.Rows().Skip(1)) { var importResult = await ImportContentFromExcelRow(headerInfo, loopRow); if (importResult.hasError) { errorNotes.Add($"Excel Row {loopRow.RowNumber()} - {importResult.errorNotes}"); continue; } try { Db.DefaultPropertyCleanup(importResult.processContent); importResult.processContent.Tags = Db.TagListCleanup(importResult.processContent.Tags); } catch { await EventLogContext.TryWriteDiagnosticMessageToLog( $"Excel Row {loopRow.RowNumber()} - Excel Import via dynamics - Tags threw an error on ContentId {importResult.processContent.ContentId ?? "New Entry"} - property probably not present", "Excel Import"); continue; } Guid contentId = importResult.processContent.ContentId; int contentDbId = importResult.processContent.Id; string differenceString; if (contentDbId > 0) { var currentDbEntry = await db.ContentFromContentId(contentId); var compareLogic = new CompareLogic { Config = { MembersToIgnore = new List <string> { "LastUpdatedBy" }, MaxDifferences= 100 } }; ComparisonResult comparisonResult = compareLogic.Compare(currentDbEntry, importResult.processContent); if (comparisonResult.AreEqual) { progress?.Report( $"Excel Row {loopRow.RowNumber()} of {lastRow} - No Changes - Title: {currentDbEntry.Title}"); continue; } var friendlyReport = new UserFriendlyReport(); differenceString = friendlyReport.OutputString(comparisonResult.Differences); importResult.processContent.LastUpdatedOn = DateTime.Now; } else { differenceString = "New Entry"; } GenerationReturn validationResult; switch (importResult.processContent) { case PhotoContent p: validationResult = await PhotoGenerator.Validate(p, UserSettingsSingleton.CurrentSettings().LocalMediaArchivePhotoContentFile(p)); break; case FileContent f: validationResult = await FileGenerator.Validate(f, UserSettingsSingleton.CurrentSettings().LocalMediaArchiveFileContentFile(f)); break; case ImageContent i: validationResult = await ImageGenerator.Validate(i, UserSettingsSingleton.CurrentSettings().LocalMediaArchiveImageContentFile(i)); break; case PointContentDto pc: validationResult = await PointGenerator.Validate(pc); break; case PostContent pc: validationResult = await PostGenerator.Validate(pc); break; case LinkContent l: validationResult = await LinkGenerator.Validate(l); break; case NoteContent n: validationResult = await NoteGenerator.Validate(n); break; default: validationResult = await GenerationReturn.Error("Excel Import - No Content Type Generator found?"); break; } if (validationResult.HasError) { errorNotes.Add($"Excel Row {loopRow.RowNumber()} - {validationResult.GenerationNote}"); progress?.Report($"Excel Row {loopRow.RowNumber()} of {lastRow} - Validation Error."); continue; } updateList.Add(new ExcelImportContentUpdateSuggestion { DifferenceNotes = differenceString, Title = importResult.processContent.Title, ToUpdate = importResult.processContent }); progress?.Report( $"Excel Row {loopRow.RowNumber()} of {lastRow} - Adding To Changed List ({updateList.Count}) - Title: {importResult.processContent.Title}"); } if (!errorNotes.Any()) { var internalContentIdDuplicates = updateList.Select(x => x.ToUpdate).GroupBy(x => x.ContentId) .Where(x => x.Count() > 1).Select(x => x.Key).Cast <Guid>().ToList(); if (internalContentIdDuplicates.Any()) { return new ExcelContentTableImportResults { HasError = true, ErrorNotes = $"Content Ids can only appear once in an update list - {string.Join(", ", internalContentIdDuplicates)}", ToUpdate = updateList } } ; var internalSlugDuplicates = updateList.Select(x => x.ToUpdate).Where(x => !(x is LinkContent)) .GroupBy(x => x.Slug).Where(x => x.Count() > 1).Select(x => x.Key).Cast <string>().ToList(); if (internalSlugDuplicates.Any()) { return new ExcelContentTableImportResults { HasError = true, ErrorNotes = $"This import appears to create duplicate slugs - {string.Join(", ", internalSlugDuplicates)}", ToUpdate = updateList } } ; } return(new ExcelContentTableImportResults { HasError = errorNotes.Any(), ErrorNotes = string.Join(Environment.NewLine, errorNotes), ToUpdate = updateList }); }
public AppService() { logContext = EventLogContext.Current; }