Ejemplo n.º 1
0
        public static void Save()
        {
            if (_lockFile == null)
            {
                TraceLog.WriteLine("Lock file has not been acquired. Work document collection cannot be saved. ");
                return;
            }

            lock (Instance)
            {
                CleanEmptyBindVariables();

                _allowBackupOverwrite &= File.Exists(_fileName);
                if (_allowBackupOverwrite)
                {
                    File.Copy(_fileName, _backupFileName, true);
                }

                using (var file = File.Create(_fileName))
                {
                    Serializer.Serialize(file, Instance);
                }

                if (_allowBackupOverwrite)
                {
                    File.Delete(_backupFileName);
                }
            }
        }
Ejemplo n.º 2
0
        static MetadataCache()
        {
            if (!Directory.Exists(ConfigurationProvider.FolderNameMetadataCache))
            {
                Directory.CreateDirectory(ConfigurationProvider.FolderNameMetadataCache);
            }

            if (!File.Exists(CacheConfigrationFileName))
            {
                DatabaseModelCacheConfiguration = new DatabaseModelCacheConfiguration();
            }
            else
            {
                try
                {
                    using (var stream = File.OpenRead(CacheConfigrationFileName))
                    {
                        DatabaseModelCacheConfiguration = (DatabaseModelCacheConfiguration)Serializer.Deserialize(stream);
                    }
                }
                catch
                {
                    try
                    {
                        File.Delete(CacheConfigrationFileName);
                        DatabaseModelCacheConfiguration = new DatabaseModelCacheConfiguration();
                    }
                    catch (Exception e)
                    {
                        TraceLog.WriteLine("DatabaseModelCacheConfiguration deserialization failed: " + e);
                    }
                }
            }
        }
Ejemplo n.º 3
0
        private async Task ExportNextBatch(IDataExportContext exportContext, ExportResultInfo exportResultInfo, CancellationToken cancellationToken)
        {
            Task <IReadOnlyList <object[]> > innerTask = null;
            var batchSize = ConfigurationProvider.Configuration.ResultGrid.FetchRowsBatchSize - exportContext.CurrentRowIndex % ConfigurationProvider.Configuration.ResultGrid.FetchRowsBatchSize;
            var exception = await App.SafeActionAsync(() => innerTask = _outputViewer.ConnectionAdapter.FetchRecordsAsync(exportResultInfo.ResultInfo, (int)batchSize, cancellationToken));

            if (exception != null)
            {
                var errorMessage = Messages.GetExceptionErrorMessage(exception);
                _outputViewer.AddExecutionLog(DateTime.Now, $"Row retrieval failed: {errorMessage}");
                Messages.ShowError(errorMessage);
            }
            else
            {
                try
                {
                    await exportContext.AppendRowsAsync(innerTask.Result);
                }
                catch (OperationCanceledException)
                {
                    TraceLog.WriteLine("User has canceled export operation. ");
                    return;
                }
                finally
                {
                    exportResultInfo.RowCount = exportContext.CurrentRowIndex;
                    exportResultInfo.RefreshFileSize();
                }

                await _outputViewer.UpdateExecutionStatisticsIfEnabled();
            }
        }
Ejemplo n.º 4
0
        public static void StoreDatabaseModelCache(string cacheKey, Action <Stream> storeAction)
        {
            if (DatabaseModelCacheConfiguration == null)
            {
                return;
            }

            lock (DatabaseModelCacheConfiguration)
            {
                if (!DatabaseModelCacheConfiguration.Files.TryGetValue(cacheKey, out CacheFile cacheFile))
                {
                    DatabaseModelCacheConfiguration.Files[cacheKey] =
                        cacheFile = new CacheFile {
                        FileName = Thread.CurrentThread.ManagedThreadId + DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture) + ".dat"
                    };
                }

                var timer    = Stopwatch.StartNew();
                var fileName = GetFullFileName(cacheFile.FileName);
                using (var stream = File.Create(fileName))
                {
                    storeAction(stream);
                }

                timer.Stop();

                TraceLog.WriteLine($"Cache for '{cacheKey}' stored to '{fileName}' ({DataSpaceConverter.PrettyPrint(new FileInfo(fileName).Length, CultureInfo.InvariantCulture)}) in {timer.Elapsed}. ");

                using (var stream = File.Create(CacheConfigrationFileName))
                {
                    Serializer.Serialize(stream, DatabaseModelCacheConfiguration);
                }
            }
        }
Ejemplo n.º 5
0
        public static void CancelOnEscape(this CancellationTokenSource cancellationTokenSource, Key key)
        {
            if (key != Key.Escape)
            {
                return;
            }

            TraceLog.WriteLine("Action is about to cancel. ");
            cancellationTokenSource.Cancel();
        }
Ejemplo n.º 6
0
        internal void SaveWorkingDocuments()
        {
            foreach (var document in AllDocuments)
            {
                document.SaveWorkingDocument();
                document.WorkDocument.TabIndex = DocumentTabControl.Items.IndexOf(document.TabItem);
            }

            WorkDocumentCollection.StoreWindowProperties(this);
            WorkDocumentCollection.Save();

            TraceLog.WriteLine($"Working document collection saved. ");
        }
        private void IsVisibleChangedHandler(object sender, DependencyPropertyChangedEventArgs args)
        {
            _refreshTimer.IsEnabled = (bool)args.NewValue;

            if (_sessionDetailViewer != null)
            {
                _sessionDetailViewer.AutoRefreshEnabled = _refreshTimer.IsEnabled;
            }

            var timerState = _refreshTimer.IsEnabled ? "enabled" : "disabled";

            TraceLog.WriteLine($"Session monitor auto-refresh has been {timerState}. ");
        }
Ejemplo n.º 8
0
        private static void UnhandledExceptionHandlerInternal(object exceptionObject)
        {
            CreateErrorLog(exceptionObject);

            try
            {
                var mainWindow = (MainWindow)Current.MainWindow;
                mainWindow.SaveWorkingDocuments();
            }
            catch (Exception exception)
            {
                TraceLog.WriteLine($"Working documents save failed: {exception}");
            }
        }
Ejemplo n.º 9
0
        public void Validate()
        {
            if (!ResultGrid.FetchRowsBatchSizeSpecified || ResultGrid.FetchRowsBatchSize == 0)
            {
                ResultGrid.FetchRowsBatchSize = DefaultRowBatchSize;
            }

            if (String.IsNullOrEmpty(ResultGrid.NullPlaceholder))
            {
                ResultGrid.NullPlaceholder = DefaultNullValuePlaceholder;
            }

            editorField = editorField ?? new ConfigurationEditor();

            if (!editorField.IndentationSizeSpecified || editorField.IndentationSize == 0)
            {
                editorField.IndentationSize = DefaultIndentationSize;
            }

            miscellaneousField = miscellaneousField ?? new ConfigurationMiscellaneous();

            if (!miscellaneousField.MaximumHistoryEntriesSpecified || miscellaneousField.MaximumHistoryEntries == 0)
            {
                miscellaneousField.MaximumHistoryEntries = DefaultMaximumHistoryEntries;
            }

            if (!miscellaneousField.MaximumHistoryEntrySizeSpecified || miscellaneousField.MaximumHistoryEntrySize == 0)
            {
                miscellaneousField.MaximumHistoryEntrySize = DefaultMaximumHistoryEntrySize;
            }

            if (String.IsNullOrEmpty(resultGridField.DateFormat))
            {
                return;
            }

            try
            {
                TraceLog.WriteLine($"DateTime format test '{resultGridField.DateFormat}' => {DateTime.Now.ToString(resultGridField.DateFormat)} succeeded. ");
            }
            catch
            {
                var dateFormat = CultureInfo.CurrentUICulture.DateTimeFormat.UniversalSortableDateTimePattern;
                TraceLog.WriteLine($"DateFormat mask '{resultGridField.DateFormat}' is invalid. Using system UI culture - {dateFormat} ({DateTime.Now}). ");
                resultGridField.DateFormat = dateFormat;
            }
        }
Ejemplo n.º 10
0
        public static void CloseDocument(WorkDocument workDocument)
        {
            ValidateWorkingDocument(workDocument);

            AddRecentDocument(workDocument);

            try
            {
                Instance._workingDocuments.Remove(workDocument.DocumentId);

                Save();
            }
            catch (Exception e)
            {
                TraceLog.WriteLine("Close working document failed: " + e);
            }
        }
Ejemplo n.º 11
0
        static App()
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
            var assembly = typeof(App).Assembly;

            Version = assembly.GetName().Version.ToString();
            var buildInfo = assembly.GetCustomAttribute <AssemblyBuildInfo>();

            VersionTimestamp = buildInfo.VersionTimestampString;
            Title            = $"SQL Pad {Version} ALPHA ({VersionTimestamp})";
            TraceLog.WriteLine(Title);

            if (WorkDocumentCollection.WorkingDocuments.Count > 0)
            {
                AdjustThreadPool(WorkDocumentCollection.WorkingDocuments.Count);
            }
        }
Ejemplo n.º 12
0
        public void AddStatementExecution(StatementExecutionHistoryEntry entry)
        {
            var maximumHistoryEntries = ConfigurationProvider.Configuration.Miscellaneous.MaximumHistoryEntries;

            if (!StatementExecutionHistory.Remove(entry) && StatementExecutionHistory.Count >= maximumHistoryEntries)
            {
                var recordsToRemove = StatementExecutionHistory.OrderByDescending(r => r.ExecutedAt).Skip(maximumHistoryEntries - 1).ToArray();
                foreach (var oldRecord in recordsToRemove)
                {
                    StatementExecutionHistory.Remove(oldRecord);
                }

                TraceLog.WriteLine($"Statement execution history limit of {maximumHistoryEntries} entries has been reached. Oldest entries have been removed. ");
            }

            StatementExecutionHistory.Add(entry);
        }
Ejemplo n.º 13
0
        private static void Initialize()
        {
            ReleaseConfigurationLock();

            try
            {
                _lockFile = new FileStream(Path.Combine(ConfigurationProvider.FolderNameWorkArea, LockFileName), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
            }
            catch (Exception e)
            {
                TraceLog.WriteLine("Configuration lock aquire failed: " + e);
            }

            if (!ReadConfiguration(_fileName))
            {
                _allowBackupOverwrite = ReadConfiguration(_backupFileName);
            }

            if (_instance == null)
            {
                _instance = new WorkDocumentCollection();
            }
            else
            {
                if (_instance._workingDocuments == null)
                {
                    _instance._workingDocuments = new Dictionary <Guid, WorkDocument>();
                }

                if (_instance._recentFiles == null)
                {
                    _instance._recentFiles = new List <WorkDocument>();
                }

                if (_instance._windowConfigurations == null)
                {
                    _instance._windowConfigurations = new Dictionary <Type, WindowProperties>();
                }
            }

            if (_instance._databaseProviderConfigurations == null)
            {
                _instance._databaseProviderConfigurations = new Dictionary <string, DatabaseProviderConfiguration>();
            }
        }
Ejemplo n.º 14
0
        private static void AdjustThreadPool(int requiredThreads)
        {
            var minSize = requiredThreads - 1;

            minSize |= minSize >> 1;
            minSize |= minSize >> 2;
            minSize |= minSize >> 4;
            minSize |= minSize >> 8;
            minSize |= minSize >> 16;
            minSize++;

            minSize = Math.Max(minSize, 8);
            minSize = Math.Min(minSize, 128);

            ThreadPool.SetMinThreads(minSize, 8);

            TraceLog.WriteLine($"Minimum of {requiredThreads} threads required to handle active documents. Thread pool minimum size adjusted to {minSize}. ");
        }
Ejemplo n.º 15
0
        private void UpdateHistoryEntries()
        {
            var maximumHistoryEntrySize = ConfigurationProvider.Configuration.Miscellaneous.MaximumHistoryEntrySize;

            foreach (var statementResult in _executionResult.StatementResults.Where(r => r.ExecutedAt.HasValue))
            {
                var executionHistoryRecord = new StatementExecutionHistoryEntry(statementResult.StatementModel.StatementText, statementResult.ExecutedAt.Value);

                if (executionHistoryRecord.StatementText.Length <= maximumHistoryEntrySize)
                {
                    _providerConfiguration.AddStatementExecution(executionHistoryRecord);
                }
                else
                {
                    TraceLog.WriteLine($"Executed statement not stored in the execution history. The maximum allowed size is {maximumHistoryEntrySize} characters while the statement has {executionHistoryRecord.StatementText.Length} characters. ");
                }
            }
        }
Ejemplo n.º 16
0
        private static void ConfigurationChangedHandler(object sender, FileSystemEventArgs fileSystemEventArgs)
        {
            var writeTime = File.GetLastWriteTimeUtc(fileSystemEventArgs.FullPath);

            if (writeTime == _lastConfigurationFileChange)
            {
                return;
            }

            Thread.Sleep(100);

            _lastConfigurationFileChange = writeTime;

            TraceLog.WriteLine("Configuration file has changed. ");

            if (Configure())
            {
                ConfigurationChanged?.Invoke(Configuration, EventArgs.Empty);
            }
        }
Ejemplo n.º 17
0
        private static bool Configure()
        {
            try
            {
                if (!File.Exists(ConfigurationFilePath))
                {
                    return(false);
                }

                using (var reader = XmlReader.Create(ConfigurationFilePath))
                {
                    Configuration = (Configuration)XmlSerializer.Deserialize(reader);
                    Configuration.Validate();
                    return(true);
                }
            }
            catch (Exception e)
            {
                TraceLog.WriteLine("Configuration loading failed: " + e);
                return(false);
            }
        }
Ejemplo n.º 18
0
        public async Task SaveExecutionResult(StatementExecutionBatchResult executionResult)
        {
            IsWaitingForResult = false;
            IsExecuting        = true;

            _exportClockTimer.Start();
            _exportResultInfoCollection.Clear();

            var commandNumber = 0;

            foreach (var statementResult in executionResult.StatementResults)
            {
                commandNumber++;

                var resultNumber = 0;
                foreach (var kvp in statementResult.ResultInfoColumnHeaders)
                {
                    resultNumber++;
                    var exportResultInfo = new ExportResultInfo(commandNumber, resultNumber, kvp.Key, kvp.Value);
                    _exportResultInfoCollection.Add(exportResultInfo);
                }
            }

            var exception = await App.SafeActionAsync(() => _outputViewer.ExecuteUsingCancellationToken(ExportRows));

            _exportClockTimer.Stop();

            IsExecuting = false;

            if (exception != null)
            {
                TraceLog.WriteLine($"Saving result to file failed: {exception}");

                CancelWaitingResults();

                Messages.ShowError(exception.Message);
            }
        }
Ejemplo n.º 19
0
        private static bool ReadConfiguration(string fileName)
        {
            if (!File.Exists(fileName))
            {
                return(true);
            }

            using (var file = File.OpenRead(fileName))
            {
                try
                {
                    _instance = (WorkDocumentCollection)Serializer.Deserialize(file, _instance, typeof(WorkDocumentCollection));

                    TraceLog.WriteLine($"WorkDocumentCollection ({_instance._workingDocuments.Count} document(s)) successfully loaded from '{fileName}'. ");
                    return(true);
                }
                catch (Exception e)
                {
                    TraceLog.WriteLine($"WorkDocumentCollection deserialization from '{fileName}' failed: {e}");
                }
            }

            return(false);
        }
Ejemplo n.º 20
0
        private async Task SetEditorValue()
        {
            var largeTextValue  = _largeValue as ILargeTextValue;
            var collectionValue = _largeValue as ICollectionValue;
            var complexType     = _largeValue as IComplexType;

            try
            {
                if (largeTextValue != null)
                {
                    TabText.Visibility = Visibility.Visible;
                    TabText.IsSelected = true;

                    _isXml = true;
                    using (var reader = new XmlTextReader(new StringReader(largeTextValue.Value)))
                    {
                        try
                        {
                            while (reader.Read())
                            {
                            }
                        }
                        catch
                        {
                            _isXml = false;
                        }
                    }

                    _isJson = true;
                    try
                    {
                        JToken.Parse(largeTextValue.Value);
                    }
                    catch (Exception)
                    {
                        _isJson = false;
                    }

                    TextEditor.Text = largeTextValue.Value;

                    if (_isXml)
                    {
                        TextEditor.SyntaxHighlighting = XmlHighlightingDefinition;
                    }
                    else if (_isJson)
                    {
                        TextEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition(SyntaxHighlightingNameJavaScript);
                    }

                    TabRaw.Visibility = Visibility.Visible;
                    await DisplayRawData(Encoding.UTF8.GetBytes(largeTextValue.Value));
                }
                else if (_largeBinaryValue != null)
                {
                    TabRaw.Visibility = Visibility.Visible;
                    TabRaw.IsSelected = true;

                    await DisplayRawData(_largeBinaryValue.Value);

                    ButtonSaveRawAs.Visibility = Visibility.Visible;
                }
                else if (collectionValue != null)
                {
                    TabCollection.Visibility = Visibility.Visible;
                    TabCollection.IsSelected = true;
                    var columnTemplate = DataGridHelper.CreateDataGridTemplateColumn(collectionValue.ColumnHeader);
                    CollectionViewer.Columns.Add(columnTemplate);
                    CollectionViewer.ItemsSource = collectionValue.Records.Cast <object>().Select(r => new [] { r }).ToArray();
                }
                else if (complexType != null)
                {
                    TabComplexType.Visibility     = Visibility.Visible;
                    TabComplexType.IsSelected     = true;
                    ComplexTypeViewer.ComplexType = complexType;
                }
            }
            catch (OperationCanceledException)
            {
                TraceLog.WriteLine("User has canceled large data editor load operation. ");
                Close();
            }
            catch (Exception e)
            {
                Messages.ShowError(e.Message, owner: this);
                Close();
            }
        }