Пример #1
0
        public async Task manage_until_cancelled()
        {
            var cts                   = new CancellationTokenSource();
            var mockQueue             = new Mock <ISortingQueue>();
            var manager               = new SortingManager(NullStandardLogger.Instance, mockQueue.Object, null, null);
            var awaitingEnqueueSignal = new ManualResetEventSlim(false);
            var mockEnqueueSignal     = new ManualResetEventSlim(false);

            mockQueue.Setup(x => x.TryDequeue(out It.Ref <SubscriberEvent> .IsAny)).Returns(false);
            mockQueue.Setup(x => x.AwaitEnqueueSignalAsync()).Callback(() => awaitingEnqueueSignal.Set()).Returns(mockEnqueueSignal.WaitHandle.AsTask());

            var manageTask = manager.ManageAsync(cts.Token);

            var timeoutToken1 = new CancellationTokenSource(10000).Token;
            await Task.WhenAny(new[] { awaitingEnqueueSignal.WaitHandle.AsTask(), timeoutToken1.WaitHandle.AsTask() });

            if (timeoutToken1.IsCancellationRequested)
            {
                throw new TimeoutException();
            }

            cts.Cancel();

            var timeoutToken2 = new CancellationTokenSource(10000).Token;
            await Task.WhenAny(new[] { manageTask, timeoutToken2.WaitHandle.AsTask() });

            if (timeoutToken2.IsCancellationRequested)
            {
                throw new TimeoutException();
            }
        }
Пример #2
0
        public async Task wait_for_enqueue_when_managing_and_no_events_in_queue()
        {
            var cts                   = new CancellationTokenSource(10000);
            var mockQueue             = new Mock <ISortingQueue>();
            var mockSorter            = new Mock <ISubscriberEventSorter>();
            var mockHandlingManager   = new Mock <IHandlingManager>();
            var manager               = new SortingManager(NullStandardLogger.Instance, mockQueue.Object, mockSorter.Object, mockHandlingManager.Object);
            var subscriberEvent       = new SubscriberEvent(null, null, 0, null, null);
            var parallelKey           = "x";
            var awaitingEnqueueSignal = new ManualResetEventSlim(false);
            var mockEnqueueSignal     = new ManualResetEventSlim(false);

            mockQueue.Setup(x => x.TryDequeue(out It.Ref <SubscriberEvent> .IsAny)).Returns(false);
            mockSorter.Setup(x => x.SortSubscriberEventToParallelKey(subscriberEvent)).Returns(parallelKey);
            mockQueue.Setup(x => x.AwaitEnqueueSignalAsync()).Callback(() => awaitingEnqueueSignal.Set()).Returns(mockEnqueueSignal.WaitHandle.AsTask());

            var manageTask = manager.ManageAsync(cts.Token);

            await Task.WhenAny(new[] { awaitingEnqueueSignal.WaitHandle.AsTask(), cts.Token.WaitHandle.AsTask() });

            if (cts.IsCancellationRequested)
            {
                throw new TimeoutException();
            }

            cts.Cancel();
        }
        // Reset Sorting properties when local path is changed.
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string requestUrl = filterContext.HttpContext.Request.Url.LocalPath;

            if (UrlManager.PreviousUrl != null && UrlManager.PreviousUrl != requestUrl)
            {
                SortingManager.ResetSorting();
            }

            UrlManager.SetPreviousUrl(requestUrl);
        }
Пример #4
0
        public async Task rethrow_exception_when_managing()
        {
            var cts       = new CancellationTokenSource(10000);
            var ex        = new TestException();
            var mockQueue = new Mock <ISortingQueue>();
            var manager   = new SortingManager(NullStandardLogger.Instance, mockQueue.Object, null, null);

            mockQueue.Setup(x => x.TryDequeue(out It.Ref <SubscriberEvent> .IsAny)).Throws(ex);

            await Assert.ThrowsAsync <TestException>(() => manager.ManageAsync(cts.Token));
        }
Пример #5
0
        public async Task receive_and_enqueue_subscriber_event()
        {
            var cts             = new CancellationTokenSource(10000);
            var mockQueue       = new Mock <ISortingQueue>();
            var manager         = new SortingManager(NullStandardLogger.Instance, mockQueue.Object, null, null);
            var subscriberEvent = new SubscriberEvent(null, null, 0, null, null);

            mockQueue.Setup(x => x.EnqueueWithWaitAsync(It.IsAny <SubscriberEvent>(), It.IsAny <CancellationToken>())).Returns(Task.CompletedTask);

            await manager.ReceiveSubscriberEventAsync(subscriberEvent, cts.Token);

            mockQueue.Verify(x => x.EnqueueWithWaitAsync(subscriberEvent, cts.Token));
        }
Пример #6
0
 protected void ManageSearchingTermStatus(ref string search)
 {
     if (!string.IsNullOrEmpty(search))
     {
         SortingManager.SetSearchingTerm(search);
     }
     else if (search == "*")
     {
     }
     else if (SortingManager.SearchTerm != null)
     {
         search = SortingManager.SearchTerm;;
     }
 }
Пример #7
0
        public async Task throw_when_parallel_key_empty()
        {
            var cts             = new CancellationTokenSource(10000);
            var mockQueue       = new Mock <ISortingQueue>();
            var mockSorter      = new Mock <ISubscriberEventSorter>();
            var manager         = new SortingManager(NullStandardLogger.Instance, mockQueue.Object, mockSorter.Object, null);
            var subscriberEvent = new SubscriberEvent(null, null, 0, null, null);
            var parallelKey     = "";         // Must be empty (or null).

            mockQueue.Setup(x => x.TryDequeue(out subscriberEvent)).Returns(true);
            mockSorter.Setup(x => x.SortSubscriberEventToParallelKey(subscriberEvent)).Returns(parallelKey);

            await Assert.ThrowsAsync <ArgumentException>(() => manager.ManageAsync(cts.Token));
        }
        public PartialViewResult ProductsToPagedList(IEnumerable <ProductViewModel> model, int?page)
        {
            string sortOrder  = null;
            bool   descending = false;

            if (SortingManager.SortOrder != null)
            {
                sortOrder  = SortingManager.SortOrder;
                descending = SortingManager.IsSortDescending;
                SortingManager.SetSorting(sortOrder, descending);
            }

            IEnumerable <ProductViewModel> sortedModel = model.SortBy(x => x.Name, sortOrder, descending);
            int pageNumber = page ?? 1;
            IPagedList <ProductViewModel> viewModel = new PagedList <ProductViewModel>(sortedModel, pageNumber, 9);

            return(PartialView("_ProductsDeck", viewModel));
        }
Пример #9
0
        public async Task sort_subscriber_event_and_send_to_handling_manager()
        {
            var cts                 = new CancellationTokenSource(10000);
            var mockQueue           = new Mock <ISortingQueue>();
            var mockSorter          = new Mock <ISubscriberEventSorter>();
            var mockHandlingManager = new Mock <IHandlingManager>();
            var manager             = new SortingManager(NullStandardLogger.Instance, mockQueue.Object, mockSorter.Object, mockHandlingManager.Object);
            var subscriberEvent     = new SubscriberEvent(null, null, 0, null, null);
            var parallelKey         = "x";

            mockQueue.Setup(x => x.TryDequeue(out subscriberEvent)).Returns(true);
            mockSorter.Setup(x => x.SortSubscriberEventToParallelKey(subscriberEvent)).Returns(parallelKey);
            mockHandlingManager
            .Setup(x => x.ReceiveSubscriberEventAsync(It.IsAny <string>(), It.IsAny <SubscriberEvent>(), It.IsAny <CancellationToken>()))
            .Callback(() => cts.Cancel())
            .Returns(Task.CompletedTask);

            await manager.ManageAsync(cts.Token);

            mockHandlingManager.Verify(x => x.ReceiveSubscriberEventAsync(parallelKey, subscriberEvent, cts.Token));
        }
Пример #10
0
        /// <summary>
        /// Создаёт отражение участка файловой системы
        /// </summary>
        /// <param name="directory"></param>
        private void _BuildFileSystemView(DirectoryInfo directory)
        {
            //Очищаем список
            //lvFileList.Items.Clear();
            lvFileList.ItemsSource = null;


            _currentDirectory = directory;

            List <CustomFileSystemCover> list = new List <CustomFileSystemCover>();

            //CustomFileSystemCover cover = null;

            //lvFileList.ItemContainerGenerator.StatusChanged +=
            //        delegate(Object sender, EventArgs e)
            //        {
            //            ListViewItem lvi = (ListViewItem)lvFileList.ItemContainerGenerator.ContainerFromItem(cover);
            //            if (lvi != null)
            //            {
            //                lvi.PreviewMouseLeftButtonDown += delegate(Object sender, MouseButtonEventArgs e)
            //                {
            //                    DragDrop.do
            //                }
            //            }

            //        };

            // Если у текущего каталога есть родительский каталог, создаём елемент, дающий возможность
            // перейти в родительский каталог
            if (directory.Parent != null)
            {
                ParentDirectoryCover cover = new ParentDirectoryCover(directory.Parent);
                list.Add(cover);
                //lvFileList.Items.Add(cover);
            }

            // Создаём елементы отражающие директории
            try
            {
                foreach (var dir in directory.GetDirectories())
                {
                    DirectoryCover cover = new DirectoryCover(dir);

                    list.Add(cover);

                    #region comments Этот вариант был исправлен на более правельный

                    //Получаем ListViewItem, когда он будет создан и подписываемся на его события
                    //lvFileList.ItemContainerGenerator.StatusChanged +=
                    //    delegate(Object sender, EventArgs e)
                    //    {
                    //        ListViewItem lvi = (ListViewItem)lvFileList.ItemContainerGenerator.ContainerFromItem(cover);
                    //        if (lvi != null)
                    //        {
                    //            lvi.AllowDrop = true;

                    //            //Список событий. Сделан чтобы не подписываться много раз на одно событие
                    //            List<string> eventList = null;
                    //            if (lvi.Tag == null)
                    //            {
                    //                eventList = new List<string>();
                    //                lvi.Tag = eventList;
                    //            }
                    //            else
                    //            {
                    //                eventList = (List<string>)lvi.Tag;
                    //            }

                    //Если события нет в списке, то подписываемся на него
                    //if (!eventList.Contains("DragEnter"))
                    //{
                    //    eventList.Add("DragEnter");
                    //    lvi.DragEnter += delegate(Object sender1, DragEventArgs e1)
                    //    {
                    //        if (e1.Effects == DragDropEffects.Move)
                    //        {
                    //            lvi.Opacity = 0.5;
                    //        }
                    //    };
                    //}

                    //Если события нет в списке, то подписываемся на него
                    //if (!eventList.Contains("DragLeave"))
                    //{
                    //    eventList.Add("DragLeave");
                    //    lvi.DragLeave += delegate(Object sender1, DragEventArgs e1)
                    //    {
                    //        lvi.Opacity = 1;
                    //    };
                    //}

                    //Если события нет в списке, то подписываемся на него
                    //if (!eventList.Contains("Drop"))
                    //{
                    //    eventList.Add("Drop");
                    //    lvi.Drop += delegate(Object sender1, DragEventArgs e1)
                    //    {
                    //        lvi.Opacity = 1;
                    //        DataObject dObj = (DataObject)e1.Data;

                    //        //Делаем не возможным обрабатывать Drop lvFileList
                    //        this.isListViewDroped = false;

                    //        if (dObj.GetDataPresent(typeof(List<CustomFileSystemCover>)))
                    //        {
                    //            // If the desired data format is present, use one of the GetData methods to retrieve the
                    //            // data from the data object.
                    //            List<CustomFileSystemCover> selectedList = dObj.GetData(typeof(List<CustomFileSystemCover>))
                    //                as List<CustomFileSystemCover>;

                    //            //MessageBox.Show(selectedList[0].Name);
                    //            List<FileSystemInfo> fsiList = new List<FileSystemInfo>();

                    //            foreach (var sl in selectedList)
                    //            {
                    //                if (sl.FileSystemElement.GetType() == typeof(DirectoryInfo))
                    //                {
                    //                    fsiList.Add(new DirectoryInfo(sl.FileSystemElement.FullName));
                    //                }
                    //                else if (sl.FileSystemElement.GetType() == typeof(FileInfo))
                    //                {
                    //                    fsiList.Add(new FileInfo(sl.FileSystemElement.FullName));
                    //                }
                    //                else
                    //                {
                    //                    new Exception("Type not support!");
                    //                }
                    //            }

                    //            DirectoryCover dc = (DirectoryCover)lvi.Content;


                    //            CopyWindow cw = new CopyWindow(fsiList, dc.FileSystemElement.FullName);
                    //            cw.ShowDialog();

                    //        }

                    //        //DragDrop.RemovePreviewDropHandler(lvFileList, lvFileList_Drop);
                    //    };
                    //}

                    //}
                    //};
                    #endregion //comments
                }
            }
            catch (Exception)
            {
                MessageBox.Show(LanguagesManager.GetCurrLanguage().FPIsNotAccess, "",
                                MessageBoxButton.OK, MessageBoxImage.Warning);
                this.Path = System.IO.Path.GetDirectoryName(this.Path);
                return;
            }

            // Создаём елементы отражающие файлы
            foreach (var file in directory.GetFiles())
            {
                FileCover cover = new FileCover(file);

                list.Add(cover);
                //lvFileList.Items.Add(cover);
            }

            //list.Sort(new NameUpSorter());
            SortingManager.Sort(list, SortingKind.NameUp);

            lvFileList.ItemsSource = list;

            // Задаём в текстовом поле текущий путь
            txtPath.Text = directory.FullName;

            this.watcher.Path = directory.FullName;
            //this.watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            this.watcher.EnableRaisingEvents = true;
        }
Пример #11
0
        public void CheckSortingOrder()
        {
            const int linesCountProgressToInform = 1000 * 1000 * 5;

            Console.WriteLine($"{DateTime.Now}. Started checking of output file for correct sorting.");

            int firstLineNumber = 1, secondLineNumber = 1;

            using (var fs = new FileStream(_filePathToCheck, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (var firstLineReader = new StreamReader(fs))
                {
                    bool isWrongSorting = false;

                    string firstLine  = firstLineReader.ReadLine();
                    string secondLine = null;
                    while (firstLine != null && (secondLine = firstLineReader.ReadLine()) != null)
                    {
                        secondLineNumber = firstLineNumber + 1;

                        if (!CorrectLinePattern.IsMatch(firstLine))
                        {
                            Console.WriteLine($"{DateTime.Now}. Wrong format of first line.");
                        }

                        if (!CorrectLinePattern.IsMatch(secondLine))
                        {
                            Console.WriteLine($"{DateTime.Now}. Wrong format of second line.");
                        }

                        var firstLinePart  = SortingManager.LinePreProcessingFunc(firstLine);
                        var secondLinePart = SortingManager.LinePreProcessingFunc(secondLine);

                        var result = _standardComparator.Compare(firstLinePart, secondLinePart);

                        if (result > 0)
                        {
                            // it seems that we have problem with sorting
                            isWrongSorting = true;

                            Console.WriteLine($"{DateTime.Now}. Lines are in incorrect order.");
                            Console.WriteLine($"{DateTime.Now}. First line: '{firstLine}'. Line number: {firstLineNumber}");
                            Console.WriteLine($"{DateTime.Now}. Second line: '{secondLine}'. Line number: {secondLineNumber}");
                        }

                        if (secondLineNumber % linesCountProgressToInform == 0)
                        {
                            Console.WriteLine($"{DateTime.Now}. Checked {secondLineNumber} lines");
                        }

                        firstLine       = secondLine;
                        firstLineNumber = secondLineNumber;
                    }

                    if (isWrongSorting)
                    {
                        Console.WriteLine($"{DateTime.Now}. Wrong sorting of lines or another problem.");
                    }
                    else
                    {
                        Console.WriteLine($"{DateTime.Now}. All lines sorted correctly and have correct output format.");
                    }
                }
            }

            Console.WriteLine($"{DateTime.Now}. Completed checking of output file for correct sorting.");
        }
Пример #12
0
 public static void Init(object sender, EventArgs e)
 {
     manager = new SortingManager();
 }
Пример #13
0
 protected void SaveSortingState(string sortOrder, bool descending, string searchTerm = null)
 {
     SortingManager.SetSorting(sortOrder, descending, searchTerm);
 }