コード例 #1
0
        public void MakeSecondLineUpperCase()
        {
            //Assert
            var mockInputFile  = new MockFileData("Line 1\nLine 2\nLine 3");
            var mockFileSystem = new MockFileSystem();

            mockFileSystem.AddFile(@"a:\root\in\myfile.txt", mockInputFile);
            mockFileSystem.AddDirectory(@"a:\root\out");

            var sut = new TextFileProcessor(
                @"a:\root\in\myfile.txt",
                @"a:\root\out\myfile.txt", mockFileSystem);

            //act
            sut.Process();

            //Assert
            Assert.True(mockFileSystem.FileExists(@"a:\root\out\myfile.txt"));

            var processedFile = mockFileSystem.GetFile(@"a:\root\out\myfile.txt");
            var lines         = processedFile.TextContents.SplitLines();

            Assert.Equal("Line 1", lines[0]);
            Assert.Equal("LINE 2", lines[1]);
            Assert.Equal("Line 3", lines[2]);
        }
コード例 #2
0
ファイル: HomeView.cs プロジェクト: tipson007/project002
        public HomeView(TextFileProcessor textFileProcessor, FolderManager folderManager)
        {
            InitializeComponent();
            this.textFileProcessor = textFileProcessor;
            this.folderManager     = folderManager;

            ChangeView(Properties.Settings.Default.View);
            ChangeSortAttribute(Properties.Settings.Default.SortAttribute);
            ChangeSortOrder(Properties.Settings.Default.SortOrder);
            reportLabels = new List <Label> {
                totalWordsIndexedTitle, totalWordsIndexedLabel,
                totalUniqueWordsIndexedTitle, totalUniqueWordsIndexedLabel,
                longestWordIndexedTitle, longestWordIndexedLabel,
                shortestWordIndexedTitle, shortestWordIndexedLabel,
                mostFrequentWordIndexedTitle, mostFrequentWordIndexedLabel,
                leastFrequentWordIndexedTitle, leastFrequentWordIndexedLabel
            };
            textFileProcessor.OnIdle += (s, e) =>
            {
                if (InvokeRequired)
                {
                    Invoke((MethodInvoker)refreshStatsButton.PerformClick);
                }
            };

            LayoutReportLabels();
            FillWatchedFoldersListView();
            refreshStatsButton.PerformClick();
        }
コード例 #3
0
ファイル: ShellForm.cs プロジェクト: tipson007/project002
        public ShellForm(TextFileProcessor textFileProcessor, FolderManager folderManager, IncrementalIdentityStore identityStore)
        {
            InitializeComponent();

            this.identityStore     = identityStore;
            this.folderManager     = folderManager;
            this.textFileProcessor = textFileProcessor;

            Load += (s, e) =>
            {
                searchBar_middle_image.Width = searchBar_right_image.Left - searchBar_middle_image.Left + 3;
                urlNsearchTextbox.Width      = searchBar_middle_image.Width - 3;
            };
            Resize += (s, e) =>
            {
                searchBar_middle_image.Width = searchBar_right_image.Left - searchBar_middle_image.Left + 3;
                urlNsearchTextbox.Width      = searchBar_middle_image.Width - 3;
            };
            homeButton.MouseEnter += (s, e) => homeButton.BackgroundImage = Properties.Resources.Home_Enter;
            homeButton.MouseLeave += (s, e) => homeButton.BackgroundImage = Properties.Resources.Home_Leave;
            homeButton.MouseDown  += (s, e) => homeButton.BackgroundImage = Properties.Resources.Home_Press;
            homeButton.MouseUp    += (s, e) => homeButton.BackgroundImage = Properties.Resources.Home_Leave;

            goButton.MouseEnter += (s, e) => goButton.BackgroundImage = Properties.Resources.Search_Enter;
            goButton.MouseLeave += (s, e) => goButton.BackgroundImage = Properties.Resources.Search_Leave;
            goButton.MouseDown  += (s, e) => goButton.BackgroundImage = Properties.Resources.Search_Press;
            goButton.MouseUp    += (s, e) => goButton.BackgroundImage = Properties.Resources.Search_Leave;
        }
コード例 #4
0
ファイル: BuildStamp.cs プロジェクト: samegens/includechecker
        protected void StampFile(string file)
        {
            FileInfo src    = new FileInfo(file);
            string   target = Path.Combine(Path.GetDirectoryName(file),
                                           Path.GetFileNameWithoutExtension(file));

            if (!src.Exists)
            {
                return;
            }


            if (!_dryrun && !_clean)
            {
                Log(Level.Verbose, "{0}Stamping file {1}", LogPrefix, target);
                FilterProcessor   fp        = new FilterProcessor(this, target);
                TextFileProcessor processor = new TextFileProcessor(file);
                processor.ProcessFile(fp);
                fp._target.Close();
            }
            else if (!_dryrun && _clean)
            {
                Log(Level.Verbose, "{0}Removing file {1}", LogPrefix, target);
                File.Delete(target);
            }
        }
コード例 #5
0
        protected void UploadButton_Click(object sender, EventArgs e)
        {
            if (!FileUploadControl.HasFile)
            {
                LockPanel.Visible = false;
                return;
            }
            try
            {
                var extension       = Path.GetExtension(FileUploadControl.FileName);
                var fileContent     = FileUploadControl.FileContent;
                var trackingNumbers = extension == ".txt"
                    ? TextFileProcessor.GetLines(fileContent)
                    : XlsFileProcessor.GetLines(fileContent);

                MainPanel.Visible        = false;
                TrackNumberPanel.Visible = true;

                TrackingNumbersList.DataSource = Session["TrackingNumbersDataSource"] = trackingNumbers;
                TrackingNumbersList.DataBind();
            }
            catch (Exception ex)
            {
                ErrorLbl.Text = ex.Message;
            }
        }
コード例 #6
0
        public void MakeTheSecondLineUpperCase()
        {
            //Create a mock input file
            var mockInputFile = new MockFileData("Line 1\nLine 2\nLine 3");

            //Setup mock file system starting state
            var mockFileSystem = new MockFileSystem();

            mockFileSystem.AddFile(@"c:\rootTest\in\myFile.txt", mockInputFile);
            mockFileSystem.AddDirectory(@"c:\rootTest\out");

            //Create TextFileProcessor with mock file system
            var sut = new TextFileProcessor(@"c:\rootTest\in\myFile.txt"
                                            , @"c:\rootTest\out\myFile.txt"
                                            , mockFileSystem);

            //Process Test File
            sut.Process();

            //Check mock file system for output file
            Assert.True(mockFileSystem.FileExists(@"c:\rootTest\out\myFile.txt"));

            //Check content of output file in mock file system
            MockFileData processedFile = mockFileSystem.GetFile(@"c:\rootTest\out\myFile.txt");

            string[] lines = processedFile.TextContents.SplitLines();
            Assert.Equal("Line 1", lines[0]);
            Assert.Equal("LINE 2", lines[1]);
            Assert.Equal("Line 3", lines[2]);
        }
コード例 #7
0
 public SearchResultsView(TextFileProcessor textFileProcessor, FolderManager folderManager, string searchText)
 {
     InitializeComponent();
     this.textFileProcessor = textFileProcessor;
     this.folderManager     = folderManager;
     this.searchText        = searchText.Split().FirstOrDefault(s => !string.IsNullOrWhiteSpace(s));
     noResultLabel.Visible  = resultCountLabel.Visible = false;
     previousButton.Visible = nextButton.Visible = false;
     SwitchState(SearchResultsViewState.Loading);
 }
コード例 #8
0
        public void TextFileProcessor_ParseLine_WithEmptyString_ShouldThrowException()
        {
            // ARRANGE
            TextFileProcessor processor = new TextFileProcessor();

            // ACT
            // No act as we're checking an exception

            // ASSERT
            Assert.Throws <ArgumentNullException>(() => processor.ParseLine(string.Empty), "The method should have thrown an exception.");
        } // end test
コード例 #9
0
        public void TextFileProcessor_ParseLine_GivenStringWithMissingOperation_ShouldThrowException()
        {
            // ARRANGE
            TextFileProcessor processor  = new TextFileProcessor();
            string            fakeString = "[2017-12-13 09:df:23.244 INFO]";

            // ACT
            // No act as we're checking an exception

            // ASSERT
            Assert.Throws <FormatException>(() => processor.ParseLine(fakeString), "The method should have thrown an exception.");
        } // end test
コード例 #10
0
        public void TextFileProcessor_ParseData_GivenEmptyStream_ShouldThrowException()
        {
            // ARRANGE
            TextFileProcessor processor   = new TextFileProcessor();
            Stream            emptyStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(string.Empty));

            // ACT
            // No act as we're checking an exception

            // ASSERT
            Assert.Throws <DataLoadException>(() => processor.ParseData(emptyStream), "The method should have thrown an exception.");
        } // end test
コード例 #11
0
        public void TextFileProcessor_ParseLine_GivenStringWithMissingSeverity_ShouldThrowException()
        {
            // ARRANGE
            TextFileProcessor processor  = new TextFileProcessor();
            string            fakeString = "[2017-12-13 09:14:23.244 - Data Updated]";

            // ACT
            // No act as we're checking an exception

            // ASSERT
            Assert.Throws <IndexOutOfRangeException>(() => processor.ParseLine(fakeString), "The method should have thrown an exception.");
        } // end test
コード例 #12
0
        public void TextFileProcessor_ParseData_GivenValidSingleLineStream_ShouldReturnParsedLine()
        {
            // ARRANGE
            TextFileProcessor      processor = new TextFileProcessor();
            IEnumerable <DataItem> results   = null;
            Stream fakeStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("[2017-12-13 09:42:23.244 INFO - Data Updated] Something fun happened."));

            // ACT
            results = processor.ParseData(fakeStream);

            // ASSERT
            Assert.AreEqual(1, results.Count(), "There should only have been one result.");
        } // end test
コード例 #13
0
        public void TextFileProcessor_ParseData_GivenSingleLineString_ShouldReturnOneResultOnly()
        {
            // ARRANGE
            TextFileProcessor      processor = new TextFileProcessor();
            IEnumerable <DataItem> results   = null;
            string fakeString = "[2017-12-13 09:42:23.244 INFO - Data Updated] Something fun happened.";

            // ACT
            results = processor.ParseData(fakeString);

            // ASSERT
            Assert.AreEqual(1, results.Count(), "There should only have been one result.");
        } // end test
コード例 #14
0
        public void TextFileProcessor_ParseData_GivenMultiLineStringWithTrailingEmptyLine_ShouldTrimExtraLine()
        {
            // ARRANGE
            TextFileProcessor      processor = new TextFileProcessor();
            IEnumerable <DataItem> results   = null;
            string fakeString = "[2017-12-13 09:42:23.244 INFO - Data Updated] Something fun happened." + Environment.NewLine + "[2017-12-13 11:26:19.583 INFO - Data Updated] Something different happened later." + Environment.NewLine;

            // ACT
            results = processor.ParseData(fakeString);

            // ASSERT
            Assert.AreEqual(2, results.Count(), "There should only be two results and the trailing newline ignored.");
        } // end test
コード例 #15
0
        public void TextFileProcessor_ParseData_GivenMultiLineString_ShouldBuildMultipleResults()
        {
            // ARRANGE
            TextFileProcessor      processor = new TextFileProcessor();
            IEnumerable <DataItem> results   = null;
            string fakeString = "[2017-12-13 09:42:23.244 INFO - Data Updated] Something fun happened." + Environment.NewLine + "[2017-12-13 11:26:19.583 INFO - Data Updated] Something different happened later.";

            // ACT
            results = processor.ParseData(fakeString);

            // ASSERT
            Assert.AreEqual(2, results.Count(), "There should have been two results built from the input.");
        } // end test
コード例 #16
0
        public void TextFileProcessor_ParseData_GivenValidMultiLineStream_ShouldReturnParsedLines()
        {
            // ARRANGE
            TextFileProcessor      processor = new TextFileProcessor();
            IEnumerable <DataItem> results   = null;
            Stream fakeStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("[2017-12-13 09:42:23.244 INFO - Data Updated] Something fun happened." + Environment.NewLine + "[2017-12-13 11:26:19.583 INFO - Data Updated] Something different happened later."));

            // ACT
            results = processor.ParseData(fakeStream);

            // ASSERT
            Assert.AreEqual(2, results.Count(), "There should have been exactly two results.");
        } // end test
コード例 #17
0
        public void TextFileProcessor_ParseLine_GivenValidStringWithNoMessage_ShouldBuildObjectWithEmptyMessage()
        {
            // ARRANGE
            TextFileProcessor processor  = new TextFileProcessor();
            DataItem          resultItem = null;
            string            fakeString = "[2017-12-13 09:42:23.244 INFO - Data Updated]";

            // ACT
            resultItem = processor.ParseLine(fakeString);

            // ASSERT
            Assert.NotNull(resultItem, "The function should have built a data item.");
            Assert.IsEmpty(resultItem.Data, "No data should have been populated.");
        } // end test
コード例 #18
0
        public void TextFileProcessor_TryParseData_WithInvalidStringInput_ShouldReturnFalseAndNullOutput()
        {
            // ARRANGE
            TextFileProcessor      processor = new TextFileProcessor();
            IEnumerable <DataItem> results   = null;
            string fakeString = "[2017-12-13 09:42:2- Data Updated] Something fun happened.";
            bool   actualResult;

            // ACT
            actualResult = processor.TryParseData(fakeString, out results);

            // ASSERT
            Assert.Null(results, "No results should have come back.");
            Assert.False(actualResult, "The result of the TryParse should have been false.");
        } // end test
コード例 #19
0
        public void TextFileProcessor_TryParseData_WithInvalidStreamInput_ShouldReturnFalseAndNullOutput()
        {
            // ARRANGE
            TextFileProcessor      processor = new TextFileProcessor();
            IEnumerable <DataItem> results   = null;
            Stream fakeStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("[2017-12-13 09:42:2- thing fun happened."));
            bool   actualResult;

            // ACT
            actualResult = processor.TryParseData(fakeStream, out results);

            // ASSERT
            Assert.Null(results, "No results should have come back.");
            Assert.False(actualResult, "The result of the TryParse should have been false.");
        } // end test
コード例 #20
0
        public void TextFileProcessor_TryParseData_WithValidStreamInput_ShouldReturnTrueAndOutputResults()
        {
            // ARRANGE
            TextFileProcessor      processor = new TextFileProcessor();
            IEnumerable <DataItem> results   = null;
            Stream fakeStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("[2017-12-13 09:42:23.244 INFO - Data Updated] Something fun happened."));
            bool   actualResult;

            // ACT
            actualResult = processor.TryParseData(fakeStream, out results);

            // ASSERT
            Assert.AreEqual(1, results.Count(), "One result should have come out of the method.");
            Assert.True(actualResult, "The result of the TryParse should have been true.");
        } // end test
コード例 #21
0
        public void TextFileProcessor_ParseLine_GivenValidEntry_ShouldBuildNewObjectWithValues(string inputOperation, string inputDateTime, ItemSeverity inputSeverity, string inputMessage)
        {
            // ARRANGE
            DateTime          expectedTime = DateTime.Parse(inputDateTime);
            string            timeFormat   = "yyyy-MM-dd HH:mm:ss.fff";
            TextFileProcessor processor    = new TextFileProcessor();
            DataItem          resultItem   = null;
            string            fakeString   = string.Concat("[", expectedTime.ToString(timeFormat), " ", inputSeverity.ToString(), " - ", inputOperation, "] ", inputMessage);

            // ACT
            resultItem = processor.ParseLine(fakeString);

            // ASSERT
            Assert.NotNull(resultItem, "The method should have built a data item.");
            Assert.AreEqual(inputOperation, resultItem.Operation, "The operation was not built properly.");
            Assert.AreEqual(expectedTime.ToString(timeFormat), resultItem.TimeStamp.ToString(timeFormat), "The date / time was not built properly.");
            Assert.AreEqual(inputSeverity, resultItem.Severity, "The severity was not built properly.");
            Assert.AreEqual(inputMessage, resultItem.Data, "The data was not build properly.");
        } // end test
コード例 #22
0
        protected void ExportTxtButton_Click(object sender, EventArgs e)
        {
            try
            {
                var items  = (IList <TrackingPackage>)Session["TrackingInfoDataSource"];
                var result = TextFileProcessor.BuildTxtFile(items.ToDataTable());
                Response.Clear();
                Response.Output.Write(result);
            }
            catch (Exception ex)
            {
                ErrorLbl.Text = ex.Message;
                return;
            }

            Response.AddHeader("content-disposition", "attachment;filename=Track.txt");
            Response.ContentType = "application/text";
            Response.Flush();
            Response.End();
        }
コード例 #23
0
        static void Main(string[] args)
        {
            // This section serves as the composition root.
            // In Dependency Injection or Inversion of Control, the composition root is the "entry" point of the application.
            // For web-applications it is the App_Start or AppStart, for windows services it is the OnStart method.
            // For console applications, it is the main method.
            // Only executables have a REAL composition root.  Class libraries are by definition a library of types to be used by
            // calling code to accomplish a goal.  The class library cannot (and should not) make any assumptions beyond it's own behavior
            // regarding how it will be used.

            // Take note of the difference between the IConfigurationProvider and the AppConfigProvider.
            // The interface is defined in the class library, while the implementation is defined in the console application project.
            // This setup allows the console application to be able to "read" configuration, without having to know how that particular configuration
            // should be accessed.  You COULD provide a default provider in the class library for configuration (as we did with the FileSystem)
            // but this gives us maximum flexibility.  This same class library used in a web.application would load config from a web.config
            // file instead of an app.config.  Or it could be a SQLConfigurationProvider as long as they implement the class library interface.
            IConfigurationProvider provider   = new AppConfigProvider();
            IDataProcessor         processor  = new TextFileProcessor();
            IFileSystemProvider    fileSystem = new SimpleFileSystemProvider();

            // Notice the .Out property of the static Console class being passed as an argument.
            // The constructor dependency for the ConsoleReportViewer requires a TextWriter instance (which the .Out property happens to be).
            // We could really pass in ANY TextWriter instance, so you COULD rename the ConsoleReportViewer to TextReportViewer to be more specific.
            // It is this injected dependency that allows us to
            // A) Actually test the output in tests
            // B) De-couple the ConsoleReportViewer from NEEDING to run in a place where it has access to the actual Console.
            // In this case, we don't have to worry about disposing of the TextWriter (like you would normally) because it's lifetime is managed
            // by the Console Application
            IReportViewer viewer = new ConsoleReportViewer(Console.Out);

            // Because we have modified the constructor to take interface arguments, and moved the primary logic from the actual viewer
            // to a new "layer" called an engine, our code-base has become larger, but also more loosely coupled.
            ReportingEngine engine = new ReportingEngine(provider, processor, fileSystem, viewer);

            engine.GenerateReport();
            Console.ReadLine();
        }
コード例 #24
0
ファイル: SplashForm.cs プロジェクト: tipson007/project002
        private async void SplashForm_Load(object sender, EventArgs e)
        {
            a                = 0;
            frameNumber      = 0;
            speed            = MaxWaveSpeed;
            speedDelta       = -1;
            messageIndex     = 0;
            messageStep      = 0;
            requestNextFrame = true;

            animationTimer          = new Timer();
            animationTimer.Tick    += AnimationTimer_Tick;
            animationTimer.Interval = 100;
            animationTimer.Start();

            messageTimer = new System.Threading.Timer(_ =>
            {
                messageStep++;
                if (messageStep == MaxMessageStep + 1)
                {
                    messageStep = 0;
                    messageIndex++;
                    if (messageIndex == messages.Length)   // disable the timer
                    {
                        messageIndex--;
                        messageTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
                    }
                }
            }, null, 0, MinSplashTime / (messages.Length * MaxMessageStep));

            try
            {
                initTask = Task.Run(() =>
                {
                    var dataDirectory = Path.Combine(Environment.CurrentDirectory, "datastore");
                    identityStore     = new IncrementalIdentityStore(dataDirectory);
                    folderManager     = new FolderManager(dataDirectory, identityStore);
                    textFileProcessor = new TextFileProcessor(dataDirectory, identityStore);

                    folderManager.TextFileCreated          = (arg) => textFileProcessor.TextFileCreated(arg.FileId, arg.FilePath, arg.OnCompleted);
                    folderManager.TextFileChanged          = (arg) => textFileProcessor.TextFileChanged(arg.FileId, arg.FilePath, arg.OnCompleted);
                    folderManager.TextFileRemoved          = (arg) => textFileProcessor.TextFilesRemoved(new[] { arg.FileId }, arg.OnCompleted);
                    folderManager.MultipleTextFilesDeleted = (arg) => textFileProcessor.TextFilesRemoved(arg.FileIds, arg.OnCompleted);

                    textFileProcessor.StartRequestProcessingLoop();
                    folderManager.StartWatching();
                });
                await Task.WhenAll(Task.Delay(MinSplashTime), initTask);

                var shellForm = new ShellForm(textFileProcessor, folderManager, identityStore);
                StartShellForm(shellForm);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Close();
            }
            finally
            {
                messageTimer?.Dispose();
                animationTimer?.Dispose();
                path?.Dispose();
                brush?.Dispose();
            }
        }