Пример #1
0
        public void Current_EmptyHistory()
        {
            var queryEvents = new QueryHistory();

            Assert.IsNull(queryEvents.Current);
            Assert.IsNull(queryEvents.Current);
        }
Пример #2
0
        public async Task GetQuerySummary_WhenSummaryNotExist_ShouldThrow()
        {
            // arrange
            LoginAsDefaultTenantAdmin();
            var user = await GetCurrentUserAsync();

            var id = UsingDbContext(c =>
            {
                var entity = new QueryHistory
                {
                    UserId           = user.Id,
                    CreationTime     = DateTime.Now,
                    MainUsername     = "******",
                    IsReliableSource = false,
                };
                c.QueryHistories.Add(entity);
                c.SaveChanges();
                return(entity.Id);
            });

            // act
            var task = _queryHistoryAppService.GetQuerySummary(new GetQuerySummaryInput
            {
                QueryHistoryId = id,
            });

            // assert
            await task.ShouldThrow <UserFriendlyException>()
            .WithMessage("This query history does not have summary");
        }
Пример #3
0
        public MainViewModel(Settings settings)
        {
            _saved = false;
            _queryTextBeforeLoadContextMenu = "";
            _queryText = "";
            _lastQuery = new Query();

            _settings = settings;

            // happlebao todo temp fix for instance code logic
            HttpProxy.Instance.Settings = _settings;
            InternationalizationManager.Instance.Settings = _settings;
            InternationalizationManager.Instance.ChangeLanguage(_settings.Language);
            ThemeManager.Instance.Settings = _settings;

            _queryHistoryStorage       = new JsonStrorage <QueryHistory>();
            _userSelectedRecordStorage = new JsonStrorage <UserSelectedRecord>();
            _topMostRecordStorage      = new JsonStrorage <TopMostRecord>();
            _queryHistory       = _queryHistoryStorage.Load();
            _userSelectedRecord = _userSelectedRecordStorage.Load();
            _topMostRecord      = _topMostRecordStorage.Load();

            InitializeResultListBox();
            InitializeContextMenu();
            InitializeKeyCommands();
            RegisterResultsUpdatedEvent();

            SetHotkey(_settings.Hotkey, OnHotkey);
            SetCustomPluginHotkey();
        }
Пример #4
0
        public HistoryResult Get(QueryHistory q)
        {
            char[]   delimiterChars = { ',' };
            DateTime from           = DateTime.Parse(Request.QueryString["from"]);
            DateTime to             = DateTime.Parse(Request.QueryString["to"]);

            //string[] statusesString = Request.QueryString["statuses"].Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
            TaskRunningStatus[]      status   = Array.ConvertAll(Request.QueryString["statuses"].Split(','), s => (TaskRunningStatus)Enum.Parse(typeof(TaskRunningStatus), s));
            List <TaskRunningStatus> statuses = new List <TaskRunningStatus>(status);

            //Console.WriteLine(HttpUtility.UrlDecode(Request.QueryString["bs"]));

            string[] bs           = base.Request.QueryString["bs"].Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
            string   sizeOperator = Request.QueryString["sizeOperator"];
            long     size         = long.Parse(Request.QueryString["size"]);
            //tasksList = (List<P2PBackup.Common.Task>)remoteOperation.GetTasksHistory(bs, from, to);
            int offset = 0;
            int limit  = 20;

            int.TryParse(base.Request.QueryString["start"], out offset);
            int.TryParse(base.Request.QueryString["limit"], out limit);
            var hr         = new HistoryResult();
            int totalCount = 0;

            hr.Items      = (List <P2PBackup.Common.Task>)RemotingManager.GetRemoteObject().GetTasksHistory(bs, from, to, statuses, sizeOperator, size, limit, offset, out totalCount);
            hr.TotalCount = totalCount;
            return(hr);
            //RemotingManager.GetRemoteObject().GetTasksHistory
        }
Пример #5
0
        public void ExecuteQuery_DontAddTheSameQueryTwice()
        {
            var executionCount = 0;

            var query1 = new Mock <IQuery>();

            query1.Setup(mock => mock.Text).Returns("1");
            var query2 = new Mock <IQuery>();

            query2.Setup(mock => mock.Text).Returns("1");

            var queryEvents = new QueryHistory();

            queryEvents.QueryExecuted += (sender, args) => ++ executionCount;

            Assert.AreEqual(0, executionCount);
            Assert.IsNull(queryEvents.Current);
            Assert.AreNotEqual(query1.Object, query2.Object);

            queryEvents.ExecuteQuery(query1.Object);
            Assert.AreEqual(1, executionCount);
            Assert.AreEqual(query1.Object, queryEvents.Current);

            queryEvents.ExecuteQuery(query2.Object);
            Assert.AreEqual(2, executionCount);
            Assert.AreEqual(query1.Object, queryEvents.Current);
        }
Пример #6
0
        public MainViewModel()
        {
            _queryTextBeforeLoadContextMenu = "";
            _queryText = "";
            _lastQuery = new Query();

            _settingsStorage = new JsonStrorage <Settings>();
            _settings        = _settingsStorage.Load();

            // happlebao todo temp fix for instance code logic
            HttpProxy.Instance.Settings      = _settings;
            UpdaterManager.Instance.Settings = _settings;
            InternationalizationManager.Instance.Settings = _settings;
            ThemeManager.Instance.Settings = _settings;

            _queryHistoryStorage       = new JsonStrorage <QueryHistory>();
            _userSelectedRecordStorage = new JsonStrorage <UserSelectedRecord>();
            _topMostRecordStorage      = new JsonStrorage <TopMostRecord>();
            _queryHistory       = _queryHistoryStorage.Load();
            _userSelectedRecord = _userSelectedRecordStorage.Load();
            _topMostRecord      = _topMostRecordStorage.Load();

            InitializeResultListBox();
            InitializeContextMenu();
            InitializeKeyCommands();
        }
Пример #7
0
 private void LoadHistoryFilesAsync()
 {
     _ = Task.Run(() =>
     {
         Log.Debug("{class} {method} {message}", "GlobalQueryHistory", "LoadHistoryFilesAsync", "Start Load");
         FileInfo[] fileList = null;
         try
         {
             DirectoryInfo d = new DirectoryInfo(_queryHistoryPath);
             fileList        = d.GetFiles("*-query-history.json", SearchOption.TopDirectoryOnly);
             List <QueryHistoryEvent> tempHist = new List <QueryHistoryEvent>(_globalOptions.QueryHistoryMaxItems);
             foreach (var fileInfo in fileList)
             {
                 using (StreamReader file = File.OpenText(fileInfo.FullName))
                 {
                     JsonSerializer serializer      = new JsonSerializer();
                     QueryHistoryEvent queryHistory = (QueryHistoryEvent)serializer.Deserialize(file, typeof(QueryHistoryEvent));
                     tempHist.Add(queryHistory);
                 }
             }
             QueryHistory.AddRange(tempHist);
         }
         catch (Exception ex)
         {
             Log.Error(ex, "{class} {method} {message}", nameof(GlobalQueryHistory), nameof(LoadHistoryFilesAsync), $"Error loading query history files: {ex.Message}");
         }
         Log.Debug("{class} {method} {message}", "GlobalQueryHistory", "LoadHistoryFilesAsync", "End Load (" + fileList?.Length + " files)");
     });
 }
Пример #8
0
        public void Back_MoveInHistory()
        {
            var query = new[]
            {
                new Mock <IQuery>(),
                new Mock <IQuery>(),
                new Mock <IQuery>(),
                new Mock <IQuery>(),
                new Mock <IQuery>(),
            };

            for (var i = 0; i < query.Length; ++i)
            {
                query[i].Setup(mock => mock.Text).Returns(i.ToString());
            }

            IExecutableQuery current = null;
            var queryEvents          = new QueryHistory();

            queryEvents.QueryExecuted += (sender, args) => current = args.Query;

            Assert.IsNull(queryEvents.Current);

            queryEvents.ExecuteQuery(query[0].Object);
            Assert.AreEqual(query[0].Object, queryEvents.Current);
            Assert.AreEqual(query[0].Object, current);

            queryEvents.ExecuteQuery(query[1].Object);
            Assert.AreEqual(query[1].Object, queryEvents.Current);
            Assert.AreEqual(query[1].Object, current);

            queryEvents.Back();
            Assert.AreEqual(query[0].Object, queryEvents.Current);
            Assert.AreEqual(query[0].Object, current);

            queryEvents.ExecuteQuery(query[2].Object);
            Assert.AreEqual(query[2].Object, queryEvents.Current);
            Assert.AreEqual(query[2].Object, current);

            queryEvents.ExecuteQuery(query[3].Object);
            Assert.AreEqual(query[3].Object, queryEvents.Current);
            Assert.AreEqual(query[3].Object, current);

            queryEvents.Back();
            Assert.AreEqual(query[2].Object, queryEvents.Current);
            Assert.AreEqual(query[2].Object, current);

            queryEvents.Back();
            Assert.AreEqual(query[0].Object, queryEvents.Current);
            Assert.AreEqual(query[0].Object, current);

            queryEvents.Back();
            Assert.AreEqual(query[0].Object, queryEvents.Current);
            Assert.AreEqual(query[0].Object, current);

            queryEvents.ExecuteQuery(query[4].Object);
            Assert.AreEqual(query[4].Object, queryEvents.Current);
            Assert.AreEqual(query[4].Object, current);
        }
Пример #9
0
        public static async Task Save(QueryExecutionContext query, QueryResponseContext response)
        {
            string?statement = NormalizeSql(query.GetSqlStatement());

            if (statement is null)
            {
                return;
            }

            string sql;
            string code    = QueryHistory.GetCode(ComputeHash(statement), query.Server.Type);
            var    history = await LoadByCode(code);

            if (history is null)
            {
                history = QueryHistory.Create(code, statement, query, response);
                sql     = "INSERT INTO query (code, status, type, sql, star, execution_count, last_executed_on, last_environment, last_database) VALUES " +
                          "( " +
                          $"'{history.Code}', " +
                          $"{(int)history.Status}, " +
                          $"{(int)history.Type}, " +
                          $"'{history.Sql.Replace("'", "''")}', " +
                          $"{(history.Star ? 1 : 0)}, " +
                          $"{history.ExecutionCount}, " +
                          $"'{history.LastExecutedOn:yyyy-MM-dd HH:mm:ss}', " +
                          $"'{history.Stats.Last().Environment}', " +
                          $"'{history.Stats.Last().Database}' " +
                          ");";
            }
            else
            {
                history.UpdateStatistics(query, response);
                sql = $"UPDATE query SET " +
                      $"status = {(int)history.Status}, " +
                      $"execution_count = {history.ExecutionCount}, " +
                      $"last_executed_on = '{history.LastExecutedOn:yyyy-MM-dd HH:mm:ss}', " +
                      $"last_environment = '{history.Stats.Last().Environment}', " +
                      $"last_database = '{history.Stats.Last().Database}' " +
                      $"WHERE code = '{history.Code}';";
            }

            var stat = history.Stats.Last();

            sql += "INSERT INTO stat (code, status, executed_on, environment, database, server_connection, elapsed, row_count, records_affected) VALUES " +
                   "( " +
                   $"'{history.Code}', " +
                   $"{(int)stat.Status}, " +
                   $"'{stat.ExecutedOn:yyyy-MM-dd HH:mm:ss}', " +
                   $"'{stat.Environment}', " +
                   $"'{stat.Database}', " +
                   $"'{stat.ServerConnection}', " +
                   $"{stat.Elapsed}, " +
                   $"{stat.RowCount}, " +
                   $"{stat.RecordsAffected}" +
                   ");";

            await ServerConnection.ExecuteNonQuery(sql);
        }
Пример #10
0
 public void Handle(QueryHistoryEvent message)
 {
     QueryHistory.Add(message);
     while (QueryHistory.Count > _globalOptions.QueryHistoryMaxItems)
     {
         QueryHistory.RemoveAt(0);
     }
     SaveHistoryFile(message);
 }
Пример #11
0
        public MainViewModel(PowerToysRunSettings settings)
        {
            _saved = false;
            _queryTextBeforeLeaveResults = string.Empty;
            _currentQuery = _emptyQuery;
            _disposed     = false;

            _settings = settings ?? throw new ArgumentNullException(nameof(settings));

            _historyItemsStorage       = new WoxJsonStorage <QueryHistory>();
            _userSelectedRecordStorage = new WoxJsonStorage <UserSelectedRecord>();
            _topMostRecordStorage      = new WoxJsonStorage <TopMostRecord>();
            _history            = _historyItemsStorage.Load();
            _userSelectedRecord = _userSelectedRecordStorage.Load();
            _topMostRecord      = _topMostRecordStorage.Load();

            ContextMenu      = new ResultsViewModel(_settings);
            Results          = new ResultsViewModel(_settings);
            History          = new ResultsViewModel(_settings);
            _selectedResults = Results;

            InitializeKeyCommands();
            RegisterResultsUpdatedEvent();

            if (settings != null && settings.UsePowerToysRunnerKeyboardHook)
            {
                NativeEventWaiter.WaitForEventLoop(Constants.PowerLauncherSharedEvent(), OnHotkey);
                _hotkeyHandle = 0;
            }
            else
            {
                HotkeyManager              = new HotkeyManager();
                _settings.PropertyChanged += (s, e) =>
                {
                    if (e.PropertyName == nameof(PowerToysRunSettings.Hotkey))
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            if (!string.IsNullOrEmpty(_settings.PreviousHotkey))
                            {
                                HotkeyManager.UnregisterHotkey(_hotkeyHandle);
                            }

                            if (!string.IsNullOrEmpty(_settings.Hotkey))
                            {
                                SetHotkey(_settings.Hotkey, OnHotkey);
                            }
                        });
                    }
                };

                SetHotkey(_settings.Hotkey, OnHotkey);
                SetCustomPluginHotkey();
            }
        }
        public PlatformData GeneratePlatformData(AgentData agentData)
        {
            var platformData = new PlatformData(agentData);

            ComponentData[] pendingComponentData = QueryHistory.Select(qh => ComponentDataRetriever.GetData(qh.Value.ToArray()))
                                                   .Where(c => c != null).ToArray();

            pendingComponentData.ForEach(platformData.AddComponent);

            return(platformData);
        }
Пример #13
0
        public async Task <IActionResult> CreateNewQuery(CreateQueryViewModel createQueryViewModel)
        {
            if (ModelState.IsValid)
            {
                if (createQueryViewModel.QueryStatus == 4 && string.IsNullOrEmpty(createQueryViewModel.Invoice))
                {
                    ModelState.AddModelError("", "Please add invoice / file number before marking the query as complete");
                    LoadQueryType();
                    await LoadEmployees();

                    return(View("CreateNewQuery", createQueryViewModel));
                }

                Query query = new Query
                {
                    ReceivedDate = DateTime.Now,
                    QueryStatus  = 1,
                    QueryType    = createQueryViewModel.QueryType,
                    QueryTitle   = createQueryViewModel.QueryTitle,
                    UserId       = createQueryViewModel.UserId,
                };

                QueryHistory queryHistory = new QueryHistory
                {
                    QueryStatus = 1,
                    QueryType   = createQueryViewModel.QueryType,
                    Description = createQueryViewModel.Description,
                    ChangeDate  = DateTime.Now,
                    UserId      = createQueryViewModel.UserId,
                };

                query.QueryHistories = new List <QueryHistory> {
                    queryHistory
                };

                _context.Add(query);
                await _context.SaveChangesAsync();
            }
            else
            {
                LoadQueryType();
                await LoadEmployees();

                return(View("CreateNewQuery", createQueryViewModel));
            }
            if (_userManager.GetUserAsync(User).Result.Designation == 1000)
            {
                return(RedirectToAction("ViewAllQueries"));
            }
            else
            {
                return(RedirectToAction("ViewEmployeeQueries"));
            }
        }
 public void UpdateHistory(IQueryContext[] queryContexts)
 {
     queryContexts.ForEach(queryContext =>
     {
         Queue <IQueryContext> queryHistory = QueryHistory.GetOrCreate(queryContext.QueryName);
         if (queryHistory.Count >= 2)                                       //Only track up to last run of this query
         {
             queryHistory.Dequeue();
         }
         queryHistory.Enqueue(queryContext);
     });
 }
Пример #15
0
 public static void AddQueryHistory(string uid)
 {
     if (!QueryHistory.Contains(uid))
     {
         MainWindow.ComboBoxUserId.Items.Add(uid);
         QueryHistory.Add(uid);
         if (QueryHistory.Count > MAX_QUERY_HISTORY_COUNT)
         {
             MainWindow.ComboBoxUserId.Items.RemoveAt(0);
             QueryHistory.RemoveAt(0);
         }
     }
 }
        public void AddQueryHistory(QueryHistory queryHistory)
        {
            if (queryHistory == null)
            {
                throw new ArgumentNullException(nameof(queryHistory));
            }

            using (var unitOfWork = _unitOfWorkFactory.GetUnitOfWork())
            {
                unitOfWork.QueriesHistory.Create(queryHistory);
                unitOfWork.Save();
            }
        }
Пример #17
0
        private double getDepthValue(long lTime)
        {
            double iDepth = 0;
            Scale  yScale = zed1.GraphPane.YAxis.Scale;

            string PostData = null;
            string PostUrl  = System.Configuration.ConfigurationManager.AppSettings["QueryHistoryData"].ToString();

            QueryHistory model = new QueryHistory();

            model.startTime     = lTime - 20;
            model.endTime       = lTime;
            model.DrillId       = m_iDrillID;
            model.DepthTag      = "var2";
            model.isHistoryData = true;

            List <string> tag = new List <string>();

            tag.Add("var2");
            model.Tag = tag;

            PostData = new JavaScriptSerializer().Serialize(model);

            var QueryData = Comm.HttpPost(PostUrl, PostData);

            if (!string.IsNullOrEmpty(QueryData))
            {
                JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
                jsSerializer.MaxJsonLength = Int32.MaxValue;
                getHistoryData dataList = jsSerializer.Deserialize <getHistoryData>(QueryData); //反序列化

                if (dataList.datas.Count <= 0)
                {
                    return(iDepth);
                }
                else
                {
                    if (dataList.Depthdatas.Count <= 0)
                    {
                        return(iDepth);
                    }

                    int iIndex = dataList.Depthdatas.Count - 1;
                    iDepth = dataList.Depthdatas[iIndex].Value;

                    return(Math.Round(iDepth, 2));
                }
            }

            return(iDepth);
        }
Пример #18
0
        public void Back_EmptyHistory()
        {
            var executed    = false;
            var queryEvents = new QueryHistory();

            queryEvents.QueryExecuted += (sender, args) => executed = true;

            Assert.IsFalse(executed);
            Assert.IsNull(queryEvents.Current);

            queryEvents.Back();

            Assert.IsFalse(executed);
            Assert.IsNull(queryEvents.Current);
        }
Пример #19
0
 public async Task Handle(QueryHistoryEvent message)
 {
     // don't add a history record if the query text is empty
     if (string.IsNullOrWhiteSpace(message.QueryText))
     {
         Log.Debug("{class} {method} {message}", nameof(GlobalQueryHistory), "Handle<QueryHistoryEvent>", "Skipping saving Query History as QueryText is empty");
         return;
     }
     QueryHistory.Add(message);
     while (QueryHistory.Count > _globalOptions.QueryHistoryMaxItems)
     {
         QueryHistory.RemoveAt(0);
     }
     await SaveHistoryFileAsync(message);
 }
Пример #20
0
        public async Task <IActionResult> EditQuery(CreateQueryViewModel createQueryViewModel)
        {
            if (ModelState.IsValid)
            {
                if (createQueryViewModel.QueryStatus == 4 && string.IsNullOrEmpty(createQueryViewModel.Invoice))
                {
                    ModelState.AddModelError("", "Please add invoice / file number before marking the query as complete");
                    LoadQueryType();
                    LoadQueryStatus();
                    await LoadEmployees();

                    return(View("CreateNewQuery", createQueryViewModel));
                }

                IEnumerable <Query> selectedQuery = _context.Query.Where(query => query.Id == createQueryViewModel.QueryId).Include(query => query.QueryHistories);

                selectedQuery.Single().QueryTitle = createQueryViewModel.QueryTitle;

                QueryHistory queryHistory = new QueryHistory
                {
                    QueryStatus = createQueryViewModel.QueryStatus,
                    QueryType   = createQueryViewModel.QueryType,
                    Description = createQueryViewModel.Description,
                    ChangeDate  = DateTime.Now,
                    UserId      = createQueryViewModel.UserId
                };

                selectedQuery.Single().QueryHistories = new List <QueryHistory> {
                    queryHistory
                };

                _context.Update(selectedQuery.Single());
                await _context.SaveChangesAsync();
            }
            else
            {
                return(RedirectToAction("EditQuery"));
            }

            if (_userManager.GetUserAsync(User).Result.Designation == 1000)
            {
                return(RedirectToAction("ViewAllQueries"));
            }
            else
            {
                return(RedirectToAction("ViewEmployeeQueries"));
            }
        }
Пример #21
0
            public static async Task Save(QueryExecutionContext query, QueryResponseContext response)
            {
                string?statement = NormalizeSql(query.GetSqlStatement());

                if (statement is null)
                {
                    return;
                }

                string sql;
                string hash    = ComputeHash(statement);
                var    history = await LoadByHash(hash);

                if (history is null)
                {
                    history = QueryHistory.Create(statement, hash, query, response);
                    sql     = "INSERT INTO [data] (type, server_connection, sql, hash, executed_on, status, elapsed, row_count, records_affected, execution_count, star) VALUES " +
                              "( " +
                              $"{(int)history.Type}, " +
                              $"'{history.ServerConnection}', " +
                              $"'{history.Sql.Replace("'", "''")}', " +
                              $"'{history.Hash}', " +
                              $"'{history.ExecutedOn:yyyy-MM-dd HH:mm:ss}', " +
                              $"{(int)history.Status}, " +
                              $"{history.Elapsed}, " +
                              $"{history.RowCount}, " +
                              $"{history.RecordsAffected}, " +
                              $"{history.ExecutionCount}, " +
                              $"{(history.Star ? 1 : 0)}" +
                              ");";
                }
                else
                {
                    history.UpdateStatistics(query, response);
                    sql = "UPDATE [data] " +
                          $"SET server_connection = '{history.ServerConnection}', " +
                          $"executed_on = '{history.ExecutedOn:yyyy-MM-dd HH:mm:ss}', " +
                          $"status = {(int)history.Status}, " +
                          $"elapsed = {history.Elapsed}, " +
                          $"row_count = {history.RowCount}, " +
                          $"records_affected = {history.RecordsAffected}, " +
                          $"execution_count = {history.ExecutionCount} " +
                          $"WHERE id = {history.Id};";
                }

                await ServerConnection.ExecuteNonQuery(sql);
            }
Пример #22
0
        public MainViewModel(Settings settings)
        {
            _hotkeyManager = new HotkeyManager();
            _saved         = false;
            _queryTextBeforeLeaveResults = "";
            _lastQuery = _emptyQuery;
            _disposed  = false;

            _settings = settings ?? throw new ArgumentNullException(nameof(settings));

            _historyItemsStorage       = new WoxJsonStorage <QueryHistory>();
            _userSelectedRecordStorage = new WoxJsonStorage <UserSelectedRecord>();
            _topMostRecordStorage      = new WoxJsonStorage <TopMostRecord>();
            _history            = _historyItemsStorage.Load();
            _userSelectedRecord = _userSelectedRecordStorage.Load();
            _topMostRecord      = _topMostRecordStorage.Load();

            ContextMenu      = new ResultsViewModel(_settings);
            Results          = new ResultsViewModel(_settings);
            History          = new ResultsViewModel(_settings);
            _selectedResults = Results;

            InitializeKeyCommands();
            RegisterResultsUpdatedEvent();

            _settings.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(Settings.Hotkey))
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        if (!string.IsNullOrEmpty(_settings.PreviousHotkey))
                        {
                            _hotkeyManager.UnregisterHotkey(_hotkeyHandle);
                        }

                        if (!string.IsNullOrEmpty(_settings.Hotkey))
                        {
                            SetHotkey(_settings.Hotkey, OnHotkey);
                        }
                    });
                }
            };

            SetHotkey(_settings.Hotkey, OnHotkey);
            SetCustomPluginHotkey();
        }
Пример #23
0
        public MainWindow()
        {
            InitializeComponent();

            Model = new MainWindowModel();

            _pluginEngine   = new PluginEngine();
            _queryHistory   = new QueryHistory(10);
            _settingsWindow = new SettingsWindow(this, _pluginEngine);

            _pluginEngine.Listeners.Add(_settingsWindow);

            RegisterHotkey(AppConstants.HotkeyToggleVisibilityId, _settingsWindow.Model.HotkeyToggleVisibility, OnToggleVisibility);
            RegisterHotkey(AppConstants.HotkeyPasteId, _settingsWindow.Model.HotkeyPasteClipboard, OnSystemClipboardPaste);

            _clipboard.ClipboardChanged += ClipboardOnClipboardChanged;
        }
Пример #24
0
        public void ExecuteQuery_EmptyHistory()
        {
            var query = new Mock <IQuery>();
            IExecutableQuery executed = null;

            var queryEvents = new QueryHistory();

            queryEvents.QueryExecuted += (sender, args) => executed = args.Query;

            Assert.IsNull(queryEvents.Current);
            Assert.IsNull(executed);

            queryEvents.ExecuteQuery(query.Object);

            Assert.AreEqual(query.Object, queryEvents.Current);
            Assert.AreEqual(query.Object, executed);
        }
Пример #25
0
        private static async Task <List <QueryHistory> > QueryList(string where)
        {
            var    list = new List <QueryHistory>();
            string sql  = "SELECT q.code, q.status as status1, type, sql, star, execution_count, last_executed_on, last_environment, last_database, name, topics, " +
                          "s.status as status2, executed_on, environment, database, server_connection, elapsed, row_count, records_affected " +
                          "FROM query q INNER JOIN stat s ON q.code = s.code " +
                          $"{where} " +
                          "ORDER BY last_executed_on DESC, executed_on DESC";

            using var cnn = ServerConnection.CreateConnection();
            await cnn.OpenAsync();

            using var dbCommand   = cnn.CreateCommand();
            dbCommand.CommandText = sql;
            using var dataReader  = await dbCommand.ExecuteReaderAsync();

            string       previousCode = "";
            QueryHistory history      = default !;
Пример #26
0
 private async Task LoadHistoryFilesAsync()
 {
     await Task.Run(() =>
     {
         Log.Debug("{class} {method} {message}", "GlobalQueryHistory", "LoadHistoryFilesAsync", "Start Load");
         FileInfo[] fileList = null;
         int errorCnt        = 0;
         try
         {
             DirectoryInfo d = new DirectoryInfo(_queryHistoryPath);
             fileList        = d.GetFiles("*-query-history.json", SearchOption.TopDirectoryOnly);
             Log.Debug(Constants.LogMessageTemplate, nameof(GlobalQueryHistory), nameof(LoadHistoryFilesAsync), $"Starting load of {fileList.Length} history files");
             List <QueryHistoryEvent> tempHist = new List <QueryHistoryEvent>(_globalOptions.QueryHistoryMaxItems);
             foreach (var fileInfo in fileList)
             {
                 try
                 {
                     using (StreamReader file = File.OpenText(fileInfo.FullName))
                     {
                         JsonSerializer serializer      = new JsonSerializer();
                         QueryHistoryEvent queryHistory = (QueryHistoryEvent)serializer.Deserialize(file, typeof(QueryHistoryEvent));
                         tempHist.Add(queryHistory);
                     }
                 }
                 catch (Exception ex)
                 {
                     Log.Error(ex, "{class} {method} {message}", nameof(GlobalQueryHistory), nameof(LoadHistoryFilesAsync), $"Error loading History file: {fileInfo.FullName}, Message: {ex.Message}");
                     errorCnt++;
                 }
             }
             QueryHistory.AddRange(tempHist);
         }
         catch (Exception ex)
         {
             Log.Error(ex, "{class} {method} {message}", nameof(GlobalQueryHistory), nameof(LoadHistoryFilesAsync), $"Error loading query history files: {ex.Message}");
         }
         if (errorCnt > 0)
         {
             _eventAggregator.PublishOnUIThread(new OutputMessage(MessageType.Warning, $"Not all Query History records could be loaded, {errorCnt} error{(errorCnt==1?" has":"s have")} been written to the log file"));
         }
         Log.Debug("{class} {method} {message}", "GlobalQueryHistory", "LoadHistoryFilesAsync", "End Load (" + fileList?.Length + " files)");
     });
 }
Пример #27
0
        public MainWindow()
        {
            InitializeComponent();

            // Load old settings
            AppSettings.Load();

            Model = new MainWindowModel();

            _pluginEngine   = new PluginEngine();
            _queryHistory   = new QueryHistory(10);
            _settingsWindow = new SettingsWindow(this, _pluginEngine);

            _pluginEngine.Listeners.Add(_settingsWindow);

            LoadPlugins();

            var hotkey = _settingsWindow.Model.Hotkey;

            HotkeyManager.Current.AddOrReplace(AppConstants.HotkeyIdentifier, hotkey.Key, hotkey.Modifiers, OnToggleVisibility);
        }
Пример #28
0
 private void LoadHistoryFilesAsync()
 {
     Task.Run(() =>
     {
         Log.Debug("{class} {method} {message}", "GlobalQueryHistory", "LoadHistoryFilesAsync", "Start Load");
         DirectoryInfo d = new DirectoryInfo(_queryHistoryPath);
         var fileList    = d.GetFiles("*-query-history.json", SearchOption.TopDirectoryOnly);
         List <QueryHistoryEvent> tempHist = new List <QueryHistoryEvent>(_globalOptions.QueryHistoryMaxItems);
         foreach (var fileInfo in fileList)
         {
             using (StreamReader file = File.OpenText(fileInfo.FullName))
             {
                 JsonSerializer serializer      = new JsonSerializer();
                 QueryHistoryEvent queryHistory = (QueryHistoryEvent)serializer.Deserialize(file, typeof(QueryHistoryEvent));
                 tempHist.Add(queryHistory);
             }
         }
         QueryHistory.AddRange(tempHist);
         Log.Debug("{class} {method} {message}", "GlobalQueryHistory", "LoadHistoryFilesAsync", "End Load (" + fileList.Count() + " files)");
     });
 }
Пример #29
0
        static MessageBus()
        {
            new Thread(UpdateChecker.CheckUpdate).Start();

            if (File.Exists(LOGIN_TICKET_FILE))
            {
                LoginTicket = File.ReadAllText(LOGIN_TICKET_FILE);
            }

            if (File.Exists(QUERY_HISTORY_FILE))
            {
                try
                {
                    string queryHistory = File.ReadAllText(QUERY_HISTORY_FILE);
                    QueryHistory.AddRange(Regex.Split(queryHistory.Trim(), "\r\n|\r|\n"));
                }
                catch
                {
                    MessageBox.Show("查询历史记录解析失败");
                }
            }
        }
Пример #30
0
        public MainViewModel(PowerToysRunSettings settings)
        {
            _saved = false;
            _queryTextBeforeLeaveResults = string.Empty;
            _currentQuery = _emptyQuery;
            _disposed     = false;

            _settings = settings ?? throw new ArgumentNullException(nameof(settings));

            _historyItemsStorage       = new WoxJsonStorage <QueryHistory>();
            _userSelectedRecordStorage = new WoxJsonStorage <UserSelectedRecord>();
            _history            = _historyItemsStorage.Load();
            _userSelectedRecord = _userSelectedRecordStorage.Load();

            ContextMenu      = new ResultsViewModel(_settings);
            Results          = new ResultsViewModel(_settings);
            History          = new ResultsViewModel(_settings);
            _selectedResults = Results;

            InitializeKeyCommands();
            RegisterResultsUpdatedEvent();
        }