示例#1
0
        public void FileListing_GetHashCode_Not_Equal_To_Zero()
        {
            const string expectedName        = "testName";
            const string expectedFullName    = "testFullName";
            const bool   expectedIsDirectory = false;

            var expectedChildren = new Collection <IFileListing>
            {
                new FileListing {
                    Name = "childNameOne"
                },
                new FileListing {
                    Name = "childNameTwo"
                }
            };

            var mockFileListing = new Mock <IFileListing>();

            mockFileListing.Setup(fileList => fileList.Name).Returns(expectedName);
            mockFileListing.Setup(fileList => fileList.FullName).Returns(expectedFullName);
            mockFileListing.Setup(fileList => fileList.IsDirectory).Returns(expectedIsDirectory);

            var fileListing = new FileListing(mockFileListing.Object)
            {
                Children = expectedChildren
            };

            var hashCode = fileListing.GetHashCode();

            Assert.AreNotEqual(0, hashCode);
        }
示例#2
0
        public void FileListing_Equals_Object_Expected_True()
        {
            const string expectedName        = "testName";
            const string expectedFullName    = "testFullName";
            const bool   expectedIsDirectory = false;

            var expectedChildren = new Collection <IFileListing>
            {
                new FileListing {
                    Name = "childNameOne"
                },
                new FileListing {
                    Name = "childNameTwo"
                }
            };

            var mockFileListing = new Mock <IFileListing>();

            mockFileListing.Setup(fileList => fileList.Name).Returns(expectedName);
            mockFileListing.Setup(fileList => fileList.FullName).Returns(expectedFullName);
            mockFileListing.Setup(fileList => fileList.IsDirectory).Returns(expectedIsDirectory);

            var fileListing = new FileListing(mockFileListing.Object)
            {
                Children = expectedChildren
            };

            object fileListingObj = fileListing;

            var isEqual = fileListing.Equals(fileListingObj);

            Assert.IsTrue(isEqual);
        }
示例#3
0
        void SelectDllFromUsingAssemblyName()
        {
            if (_selectedDll != null)
            {
                return;
            }

            if (_assemblyName == null)
            {
                return;
            }

            if (!_assemblyName.StartsWith("GAC") && !File.Exists(_assemblyName))
            {
                return;
            }


            var dll = new FileInfo(_assemblyName);

            if (dll.Extension != ".dll")
            {
                return;
            }

            var fileListing = new FileListing {
                Name = dll.Name, FullName = dll.FullName
            };

            _selectedDll = new DllListingModel(_updateManager, fileListing);
        }
示例#4
0
        public void FileListing_Equals_FileListing_Expected_False()
        {
            const string expectedName        = "testName";
            const string expectedFullName    = "testFullName";
            const bool   expectedIsDirectory = false;

            var mockFileListing = new Mock <IFileListing>();

            mockFileListing.Setup(fileList => fileList.Name).Returns(expectedName);
            mockFileListing.Setup(fileList => fileList.FullName).Returns(expectedFullName);
            mockFileListing.Setup(fileList => fileList.IsDirectory).Returns(expectedIsDirectory);

            var fileListing = new FileListing(mockFileListing.Object);

            var mockFileListingDup = new Mock <IFileListing>();

            mockFileListingDup.Setup(fileList => fileList.Name).Returns("testNewName");
            mockFileListingDup.Setup(fileList => fileList.FullName).Returns(expectedFullName);
            mockFileListingDup.Setup(fileList => fileList.IsDirectory).Returns(expectedIsDirectory);

            var fileListingDup = new FileListing(mockFileListingDup.Object);

            var isEqual = fileListing.Equals(fileListingDup);

            Assert.IsFalse(isEqual);
            Assert.IsTrue(fileListing != fileListingDup);
        }
示例#5
0
            private void ExecuteEvents(TimelineHandler handler)
            {
                try
                {
                    foreach (var timelineEvent in handler.TimeLineEvents)
                    {
                        var path = GetSavePath(typeof(LightExcelHandler), handler, timelineEvent, "docx");

                        var list = RandomText.GetDictionary.GetDictionaryList();
                        var rt   = new RandomText(list.ToArray());
                        rt.AddSentence(5);

                        var title = rt.Content;
                        rt.AddContentParagraphs(2, 3, 5, 7, 22);
                        var paragraph = rt.Content;

                        Domain.Code.Office.Word.Write(path, title, paragraph);

                        FileListing.Add(path);
                        this.Report(handler.HandlerType.ToString(), timelineEvent.Command,
                                    timelineEvent.CommandArgs[0].ToString());
                    }
                }
                catch (Exception e)
                {
                    _log.Error(e);
                }
            }
示例#6
0
        public void FileChooserModel_GetFilesExpectPassThrough()
        {
            //------------Setup for test--------------------------
            var qm   = new Mock <IQueryManager>();
            var file = new FileListing()
            {
                Name = @"c:\"
            };

            qm.Setup(a => a.FetchFiles(file)).Returns(new List <IFileListing>()
            {
                new FileListing()
                {
                    Name = @"c:\"
                }
            });
            var emailAttachmentModel = new FileChooserModel(qm.Object);

            //------------Execute Test---------------------------
            var drives = emailAttachmentModel.FetchFiles(file);

            //------------Assert Results-------------------------

            Assert.AreEqual(drives.Count, 1);
            Assert.AreEqual(drives[0].Name, @"c:\");
        }
    private void CreatePromptInstance(FileListing listing) // Creates an instance of the prompt, in case of multiple selection,
    {                                                      // calling this multiple times is handled outside of this method
        DeletionPopup popupClone = Instantiate(settings.popupWindowPrefab, settings.mainCanvas.transform).GetComponent <DeletionPopup>();

        popupClone.popupForListing = listing;
        popupClone.transform.SetAsLastSibling();
    }
示例#8
0
        public void FileListing_Validate()
        {
            const string expectedName        = "testName";
            const string expectedFullName    = "testFullName";
            const bool   expectedIsDirectory = false;

            var expectedChildren = new Collection <IFileListing>
            {
                new FileListing {
                    Name = "childNameOne"
                },
                new FileListing {
                    Name = "childNameTwo"
                }
            };

            var mockFileListing = new Mock <IFileListing>();

            mockFileListing.Setup(fileList => fileList.Name).Returns(expectedName);
            mockFileListing.Setup(fileList => fileList.FullName).Returns(expectedFullName);
            mockFileListing.Setup(fileList => fileList.IsDirectory).Returns(expectedIsDirectory);

            var fileListing = new FileListing(mockFileListing.Object)
            {
                Children = expectedChildren
            };

            Assert.AreEqual(expectedName, fileListing.Name);
            Assert.AreEqual(expectedFullName, fileListing.FullName);
            Assert.AreEqual(expectedIsDirectory, fileListing.IsDirectory);
            Assert.AreEqual(2, fileListing.Children.Count);
            Assert.AreEqual("childNameOne", fileListing.Children.ToList()[0].Name);
            Assert.AreEqual("childNameTwo", fileListing.Children.ToList()[1].Name);
        }
    private void ForceSelect(FileListing listing, bool addToSelectedList = false, bool setAsSelected = true)
    {                      // Used mainly in the script, while OnClick_SelectFile is used as the OnClick event for the listings...
        if (setAsSelected) // We don't always want the last one to be selected, such as in shift-click selection
        {
            curSelectedFileListing = listing;
            curSelectedFileListing.GetComponent <Image>().color = Color.green;
        }

        if (addToSelectedList) // You could probably do without this as in all method calls the 2nd
        {                      // bool parameter is set to true
            selectionList.Add(listing);

            listing.GetComponent <Image>().color = Color.green;
        }
        else
        {
            ClearSelectionList();

            if (curSelectedFileListing != null)
            {
                curSelectedFileListing.GetComponent <Image>().color = Color.white;
            }

            if (curSelectedFileListing)
            {
                listing.GetComponent <Image>().color = Color.green;
            }
        }
    }
示例#10
0
        public void FileListing_GetHashCode_Expect_Zero()
        {
            var fileListing = new FileListing();

            var hashCode = fileListing.GetHashCode();

            Assert.AreEqual(0, hashCode);
        }
示例#11
0
        public FileListing BuildFileListing(FileSystemInfo fileInfo)
        {
            var dllListing = new FileListing {
                Name = fileInfo.Name, FullName = fileInfo.FullName
            };

            return(dllListing);
        }
示例#12
0
        public void FileListing_Equals_Object_Null_Expected_False()
        {
            var fileListing = new FileListing();

            const object fileListingObj = null;

            var isEqual = fileListing.Equals(fileListingObj);

            Assert.IsFalse(isEqual);
        }
    private void TryDeleteFile(FileListing listing)
    {
        // Prompt depending on forceDelete (set by UI button)

        if (forceDelete)
        {
            DeleteFile(listing);
        }
        else
        {
            CreatePromptInstance(listing);
        }
    }
    public void DeleteFile(FileListing listing)
    {
        if (listing != null) // very rare cases
        {
            string path = listing.FullPath;

            Destroy(listing.gameObject);
            File.Delete(path);
        }
        else
        {
#if UNITY_EDITOR
            Debug.LogWarning("Listing doesn't exist, perhaps it got deleted by something else beforehand?");
#endif
        }
    }
示例#15
0
        ///here lies technical debt
        //TODO clean up
        // if supposed to be one excel running, and there is more than 2, then kill race condition
        private static void SafetyNet()
        {
            while (true)
            {
                try
                {
                    _log.Trace("SafetyNet loop beginning");

                    FileListing.FlushList(); //Added 6/10 by AMV to clear clogged while loop.

                    var timeline = TimelineBuilder.GetLocalTimeline();

                    var handlerCount = timeline.TimeLineHandlers.Count(o => o.HandlerType == HandlerType.Excel);
                    var pids         = ProcessManager.GetPids(ProcessManager.ProcessNames.Excel).ToList();
                    if (pids.Count > handlerCount + 1)
                    {
                        _log.Trace($"SafetyNet excel handlers: {handlerCount} pids: {pids.Count} - killing");
                        ProcessManager.KillProcessAndChildrenByName(ProcessManager.ProcessNames.Excel);
                    }

                    handlerCount = timeline.TimeLineHandlers.Count(o => o.HandlerType == HandlerType.PowerPoint);
                    pids         = ProcessManager.GetPids(ProcessManager.ProcessNames.PowerPoint).ToList();
                    if (pids.Count > handlerCount + 1)
                    {
                        _log.Trace($"SafetyNet powerpoint handlers: {handlerCount} pids: {pids.Count} - killing");
                        ProcessManager.KillProcessAndChildrenByName(ProcessManager.ProcessNames.PowerPoint);
                    }

                    handlerCount = timeline.TimeLineHandlers.Count(o => o.HandlerType == HandlerType.Word);
                    pids         = ProcessManager.GetPids(ProcessManager.ProcessNames.Word).ToList();
                    if (pids.Count > handlerCount + 1)
                    {
                        _log.Trace($"SafetyNet word handlers: {handlerCount} pids: {pids.Count} - killing");
                        ProcessManager.KillProcessAndChildrenByName(ProcessManager.ProcessNames.Word);
                    }
                    _log.Trace("SafetyNet loop ending");
                }
                catch (Exception e)
                {
                    _log.Trace($"SafetyNet exception: {e}");
                }
                finally
                {
                    Thread.Sleep(60000); //every 60 seconds clean up
                }
            }
        }
示例#16
0
        public void FileListing_Equals_Object_GetType_Expected_False()
        {
            const string expectedName        = "testName";
            const string expectedFullName    = "testFullName";
            const bool   expectedIsDirectory = false;

            var mockFileListing = new Mock <IFileListing>();

            mockFileListing.Setup(fileList => fileList.Name).Returns(expectedName);
            mockFileListing.Setup(fileList => fileList.FullName).Returns(expectedFullName);
            mockFileListing.Setup(fileList => fileList.IsDirectory).Returns(expectedIsDirectory);

            var fileListing = new FileListing(mockFileListing.Object);

            var fileListingObj = new object();

            var isEqual = fileListing.Equals(fileListingObj);

            Assert.IsFalse(isEqual);
        }
示例#17
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (String.IsNullOrEmpty(Heading))
            {
                FileListHeading.Visible = false;
            }

            FileListHeading.InnerText = Heading;

            if (String.IsNullOrEmpty(RootFolder))
            {
                ErrorMessage.Visible = true;
                return;
            }

            var lastModifiedFiles = FindLastModifiedFiles(RootFolder, MaxCount);

            FileListPanel.Visible  = lastModifiedFiles.Count > 0;
            FileListing.DataSource = lastModifiedFiles;
            FileListing.DataBind();
        }
    private void CreateFileListing(string fullPath) // Creates a file listing and places it in the content, it now exists in existingListings
    {
        FileListing fileListingClone = Instantiate(settings.fileListingPrefab, settings.fileScrollContent) as FileListing;
        Button      cloneButton      = fileListingClone.GetComponent <Button>();
        Text        cloneText        = cloneButton.GetComponentInChildren <Text>();

        fileListingClone.FullPath = fullPath;
        fileListingClone.FileName = Path.GetFileName(fullPath);

        existingListings.Add(fileListingClone);

        if (showFullPath)
        {
            cloneText.text = fileListingClone.FullPath;
        }
        else
        {
            cloneText.text = fileListingClone.FileName;
        }


        cloneButton.onClick.AddListener(() => OnClick_SelectFile(fileListingClone));
        // You could probably do the above in the FileListing script as well, this just felt easier for me
    }
示例#19
0
        private void ExecuteEvents(Timeline timeline, TimelineHandler handler)
        {
            try
            {
                foreach (var timelineEvent in handler.TimeLineEvents)
                {
                    try
                    {
                        _log.Trace($"Excel event - {timelineEvent}");
                        WorkingHours.Is(handler);

                        if (timelineEvent.DelayBefore > 0)
                        {
                            Thread.Sleep(timelineEvent.DelayBefore);
                        }

                        if (timeline != null)
                        {
                            var processIds = ProcessManager.GetPids(ProcessManager.ProcessNames.Excel).ToList();
                            if (processIds.Count > timeline.TimeLineHandlers.Count(o => o.HandlerType == HandlerType.Excel))
                            {
                                return;
                            }
                        }

                        // start excel and turn off msg boxes
                        var excelApplication = new Excel.Application
                        {
                            DisplayAlerts = false,
                            Visible       = true
                        };

                        try
                        {
                            excelApplication.WindowState = XlWindowState.xlMinimized;
                            foreach (var item in excelApplication.Workbooks)
                            {
                                item.Windows[1].WindowState = XlWindowState.xlMinimized;
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Trace($"Could not minimize: {e}");
                        }

                        // create a utils instance, not need for but helpful to keep the lines of code low
                        var utils = new CommonUtils(excelApplication);

                        _log.Trace("Excel adding workbook");
                        // add a new workbook
                        var workBook = excelApplication.Workbooks.Add();
                        _log.Trace("Excel adding worksheet");
                        var workSheet = (Excel.Worksheet)workBook.Worksheets[1];

                        // draw back color and perform the BorderAround method
                        workSheet.Range("$B2:$B5").Interior.Color = utils.Color.ToDouble(Color.DarkGreen);
                        workSheet.Range("$B2:$B5").BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlMedium,
                                                                XlColorIndex.xlColorIndexAutomatic);

                        // draw back color and border the range explicitly
                        workSheet.Range("$D2:$D5").Interior.Color = utils.Color.ToDouble(Color.DarkGreen);
                        workSheet.Range("$D2:$D5")
                        .Borders[(Excel.Enums.XlBordersIndex)XlBordersIndex.xlInsideHorizontal]
                        .LineStyle = XlLineStyle.xlDouble;
                        workSheet.Range("$D2:$D5")
                        .Borders[(Excel.Enums.XlBordersIndex)XlBordersIndex.xlInsideHorizontal]
                        .Weight = 4;
                        workSheet.Range("$D2:$D5")
                        .Borders[(Excel.Enums.XlBordersIndex)XlBordersIndex.xlInsideHorizontal]
                        .Color = utils.Color.ToDouble(Color.Black);

                        var writeSleep = ProcessManager.Jitter(100);
                        Thread.Sleep(writeSleep);

                        workSheet.Cells[1, 1].Value = "We have 2 simple shapes created.";

                        var rand = RandomFilename.Generate();

                        var dir = timelineEvent.CommandArgs[0].ToString();
                        if (dir.Contains("%"))
                        {
                            dir = Environment.ExpandEnvironmentVariables(dir);
                        }

                        if (Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }

                        var path = $"{dir}\\{rand}.xlsx";

                        //if directory does not exist, create!
                        _log.Trace($"Checking directory at {path}");
                        var f = new FileInfo(path).Directory;
                        if (f == null)
                        {
                            _log.Trace($"Directory does not exist, creating directory at {f.FullName}");
                            Directory.CreateDirectory(f.FullName);
                        }

                        try
                        {
                            if (File.Exists(path))
                            {
                                File.Delete(path);
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Error($"Excel file delete exception: {e}");
                        }

                        _log.Trace($"Excel saving to path - {path}");
                        workBook.SaveAs(path);
                        FileListing.Add(path);
                        Report(handler.HandlerType.ToString(), timelineEvent.Command,
                               timelineEvent.CommandArgs[0].ToString());

                        if (timelineEvent.DelayAfter > 0)
                        {
                            //sleep and leave the app open
                            _log.Trace($"Sleep after for {timelineEvent.DelayAfter}");
                            Thread.Sleep(timelineEvent.DelayAfter - writeSleep);
                        }

                        // close excel and dispose reference
                        excelApplication.Quit();
                        excelApplication.Dispose();
                        excelApplication = null;

                        workBook  = null;
                        workSheet = null;

                        try
                        {
                            Marshal.ReleaseComObject(excelApplication);
                        }
                        catch { }

                        try
                        {
                            Marshal.FinalReleaseComObject(excelApplication);
                        }
                        catch { }

                        GC.Collect();
                    }
                    catch (Exception e)
                    {
                        _log.Error($"Excel handler exception: {e}");
                    }
                    finally
                    {
                        Thread.Sleep(5000);
                    }
                }
            }
            catch (Exception e)
            {
                _log.Error(e);
            }
            finally
            {
                KillApp();
                _log.Trace("Excel closing...");
            }
        }
    public void OnClick_SelectFile(FileListing listing)
    {
        if (Input.GetKey(KeyCode.LeftControl)) // Clicking on a file while holding ctrl, adds it to selection unless it already is in
        {                                      // otherwise deselects it
            if (selectionList.Contains(listing))
            {
                if (curSelectedFileListing)
                {
                    curSelectedFileListing.GetComponent <Image>().color = Color.white;

                    if (curSelectedFileListing.GetInstanceID() == listing.GetInstanceID())
                    {
                        curSelectedFileListing = null;
                    }
                }

                selectionList.Remove(listing);
            }
            else
            {
                curSelectedFileListing = listing;

                selectionList.Add(listing);

                curSelectedFileListing.GetComponent <Image>().color = Color.green;
            }
        }
        else if (Input.GetKey(KeyCode.LeftShift)) // // Clicking on a file while holding lshift, selects it from A to B
        {
            ClearSelectionList();

            int start;
            int end;

            if (curSelectedFileListing == null)
            {
                start = 0;
                end   = existingListings.IndexOf(listing);
            }
            else
            {
                int ind1 = existingListings.IndexOf(curSelectedFileListing);
                int ind2 = existingListings.IndexOf(listing);

                start = ind1 > ind2 ? ind2 : ind1;
                end   = ind1 > ind2 ? ind1 : ind2;
            }

            for (int i = start; i <= end; i++)
            {
                if (existingListings[i] == null)
                {
#if UNITY_EDITOR
                    Debug.LogWarning("isnull");
#endif
                    continue;
                }

                Debug.Log(existingListings[i]);
                ForceSelect(existingListings[i], true, false); // No matter where you shift-click, it always starts from the currently selected
                // listing, or 0 if none selected
            }
        }
        else
        {
            ClearSelectionList(); // Just clicking clears the list and selects the listing by itself

            if (curSelectedFileListing != null)
            {
                curSelectedFileListing.GetComponent <Image>().color = Color.white;
            }

            curSelectedFileListing = listing;
            selectionList.Add(listing);

            curSelectedFileListing.GetComponent <Image>().color = Color.green;
        }
    }
示例#21
0
        private void ExecuteEvents(Timeline timeline, TimelineHandler handler)
        {
            try
            {
                foreach (var timelineEvent in handler.TimeLineEvents)
                {
                    try
                    {
                        _log.Trace($"PowerPoint event - {timelineEvent}");
                        WorkingHours.Is(handler);

                        if (timelineEvent.DelayBefore > 0)
                        {
                            Thread.Sleep(timelineEvent.DelayBefore);
                        }

                        if (timeline != null)
                        {
                            var processIds = ProcessManager.GetPids(ProcessManager.ProcessNames.PowerPoint).ToList();
                            if (processIds.Count > timeline.TimeLineHandlers.Count(o => o.HandlerType == HandlerType.PowerPoint))
                            {
                                return;
                            }
                        }

                        var powerApplication = new PowerPoint.Application
                        {
                            DisplayAlerts = PpAlertLevel.ppAlertsNone,
                            Visible       = MsoTriState.msoTrue
                        };

                        try
                        {
                            powerApplication.WindowState = PpWindowState.ppWindowMinimized;
                        }
                        catch (Exception e)
                        {
                            _log.Trace($"Could not minimize: {e}");
                        }

                        // add a new presentation with one new slide
                        var presentation = powerApplication.Presentations.Add(MsoTriState.msoTrue);
                        presentation.Slides.Add(1, PpSlideLayout.ppLayoutClipArtAndVerticalText);

                        var writeSleep = ProcessManager.Jitter(100);
                        Thread.Sleep(writeSleep);

                        // save the document
                        var rand = RandomFilename.Generate();

                        var dir = timelineEvent.CommandArgs[0].ToString();
                        if (dir.Contains("%"))
                        {
                            dir = Environment.ExpandEnvironmentVariables(dir);
                        }

                        if (Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }

                        var path = $"{dir}\\{rand}.pptx";

                        //if directory does not exist, create!
                        _log.Trace($"Checking directory at {path}");
                        var f = new FileInfo(path).Directory;
                        if (f == null)
                        {
                            _log.Trace($"Directory does not exist, creating directory at {path}");
                            Directory.CreateDirectory(path);
                        }

                        try
                        {
                            if (File.Exists(path))
                            {
                                File.Delete(path);
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Debug(e);
                        }

                        Thread.Sleep(5000);
                        presentation.SaveAs(path);
                        FileListing.Add(path);
                        Report(handler.HandlerType.ToString(), timelineEvent.Command,
                               timelineEvent.CommandArgs[0].ToString());

                        if (timelineEvent.DelayAfter > 0)
                        {
                            //sleep and leave the app open
                            _log.Trace($"Sleep after for {timelineEvent.DelayAfter}");
                            Thread.Sleep(timelineEvent.DelayAfter - writeSleep);
                        }

                        // close power point and dispose reference
                        powerApplication.Quit();
                        powerApplication.Dispose();
                        powerApplication = null;
                        presentation     = null;

                        try
                        {
                            Marshal.ReleaseComObject(powerApplication);
                        }
                        catch { }

                        try
                        {
                            Marshal.FinalReleaseComObject(powerApplication);
                        }
                        catch { }

                        GC.Collect();
                    }
                    catch (Exception e)
                    {
                        _log.Debug(e);
                    }
                    finally
                    {
                        Thread.Sleep(5000);
                    }
                }
            }
            catch (Exception e)
            {
                _log.Debug(e);
            }
            finally
            {
                KillApp();
                _log.Trace("PowerPoint closing...");
            }
        }
示例#22
0
        private void ExecuteEvents(Timeline timeline, TimelineHandler handler)
        {
            try
            {
                foreach (TimelineEvent timelineEvent in handler.TimeLineEvents)
                {
                    try
                    {
                        _log.Trace($"Word event - {timelineEvent}");
                        WorkingHours.Is(handler);

                        if (timelineEvent.DelayBefore > 0)
                        {
                            Thread.Sleep(timelineEvent.DelayBefore);
                        }

                        if (timeline != null)
                        {
                            System.Collections.Generic.List <int> pids = ProcessManager.GetPids(ProcessManager.ProcessNames.Word).ToList();
                            if (pids.Count > timeline.TimeLineHandlers.Count(o => o.HandlerType == HandlerType.Word))
                            {
                                return;
                            }
                        }

                        // start word and turn off msg boxes
                        Word.Application wordApplication = new Word.Application
                        {
                            DisplayAlerts = WdAlertLevel.wdAlertsNone,
                            Visible       = true
                        };

                        // add a new document
                        Word.Document newDocument = wordApplication.Documents.Add();

                        try
                        {
                            wordApplication.WindowState = WdWindowState.wdWindowStateMinimize;
                            foreach (Word.Document item in wordApplication.Documents)
                            {
                                item.Windows[1].WindowState = WdWindowState.wdWindowStateMinimize;
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Trace($"Could not minimize: {e}");
                        }

                        // insert some text
                        System.Collections.Generic.List <string> list = RandomText.GetDictionary.GetDictionaryList();
                        RandomText rt = new RandomText(list.ToArray());
                        rt.AddContentParagraphs(1, 1, 1, 10, 50);
                        wordApplication.Selection.TypeText(rt.Content);

                        int writeSleep = ProcessManager.Jitter(100);
                        Thread.Sleep(writeSleep);

                        wordApplication.Selection.HomeKey(WdUnits.wdLine, WdMovementType.wdExtend);
                        wordApplication.Selection.Font.Color = WdColor.wdColorSeaGreen;
                        wordApplication.Selection.Font.Bold  = 1;
                        wordApplication.Selection.Font.Size  = 18;

                        string rand = RandomFilename.Generate();

                        string dir = timelineEvent.CommandArgs[0].ToString();
                        if (dir.Contains("%"))
                        {
                            dir = Environment.ExpandEnvironmentVariables(dir);
                        }

                        if (Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }

                        string path = $"{dir}\\{rand}.docx";

                        //if directory does not exist, create!
                        _log.Trace($"Checking directory at {path}");
                        DirectoryInfo f = new FileInfo(path).Directory;
                        if (f == null)
                        {
                            _log.Trace($"Directory does not exist, creating directory at {f.FullName}");
                            Directory.CreateDirectory(f.FullName);
                        }

                        try
                        {
                            if (File.Exists(path))
                            {
                                File.Delete(path);
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Debug(e);
                        }

                        newDocument.Saved = true;
                        newDocument.SaveAs(path);
                        Report(handler.HandlerType.ToString(), timelineEvent.Command, timelineEvent.CommandArgs[0].ToString());

                        FileListing.Add(path);

                        if (timelineEvent.DelayAfter > 0)
                        {
                            //sleep and leave the app open
                            _log.Trace($"Sleep after for {timelineEvent.DelayAfter}");
                            Thread.Sleep(timelineEvent.DelayAfter - writeSleep);
                        }

                        wordApplication.Quit();
                        wordApplication.Dispose();
                        wordApplication = null;

                        try
                        {
                            Marshal.ReleaseComObject(wordApplication);
                        }
                        catch { }

                        try
                        {
                            Marshal.FinalReleaseComObject(wordApplication);
                        }
                        catch { }

                        GC.Collect();
                    }
                    catch (Exception e)
                    {
                        _log.Debug(e);
                    }
                    finally
                    {
                        Thread.Sleep(5000);
                    }
                }
            }
            catch (Exception e)
            {
                _log.Error(e);
            }
            finally
            {
                KillApp();
                _log.Trace($"Word closing...");
            }
        }
 /// <summary>Adds to file list stack.</summary>
 /// <param name="item">The item.</param>
 public void AddToFileListStack(string item) => FileListing.Add(item);
示例#24
0
        /// <summary>
        /// Returns a list of files and directories for the given path
        /// </summary>
        /// <param name="relativepath"></param>
        /// <returns></returns>
        private static DirectoryListing BuildFileList(string path, bool includeParentLink = true)
        {
            //see if we have an ordering file for the supplied path
            Dictionary <string, int> ordering = new Dictionary <string, int>();
            string orderingPath = Path.Combine(path, OrderingFileName);

            if (File.Exists(orderingPath))
            {
                ordering = GetFileOrdering(orderingPath);
            }

            //build a new listing, set some initial values
            DirectoryListing listing = new DirectoryListing();

            listing.AbsolutePath = path;
            listing.Name         = path.Substring(path.LastIndexOf('\\') + 1);
            listing.LastModified = File.GetLastWriteTime(path);

            //handle files
            int defaultOrderingCount = 1000;

            foreach (string file in Directory.GetFiles(path))
            {
                //the ordering file is used to denote ordering of files and should not be
                //displayed in the file list.
                if (Path.GetFileName(file).CompareTo(OrderingFileName) == 0)
                {
                    continue;
                }
                FileListing fList = new FileListing();
                fList.AbsolutePath = file;
                fList.Name         = Path.GetFileName(file);
                fList.LastModified = File.GetLastWriteTime(file);
                fList.FileUrl      = CourseDocumentPathToWebUrl(file);

                //set file ordering if it exists
                if (ordering.ContainsKey(fList.Name))
                {
                    fList.SortOrder = ordering[fList.Name];
                }
                else
                {
                    defaultOrderingCount++;
                    while (ordering.ContainsValue(defaultOrderingCount))
                    {
                        defaultOrderingCount++;
                    }
                    fList.SortOrder = defaultOrderingCount;
                }
                listing.Files.Add(fList);
            }

            //Add a parent directory "..." at the top of every directory listing if requested
            if (includeParentLink)
            {
                listing.Directories.Add(new ParentDirectoryListing());
            }

            //handle other directories
            foreach (string folder in Directory.EnumerateDirectories(path))
            {
                //recursively build the directory's subcontents.  Note that we have
                //to pass only the folder's name and not the complete path
                DirectoryListing dlisting = BuildFileList(folder, includeParentLink);
                if (ordering.ContainsKey(dlisting.Name))
                {
                    dlisting.SortOrder = ordering[dlisting.Name];
                }
                else
                {
                    defaultOrderingCount++;
                    while (ordering.ContainsValue(defaultOrderingCount))
                    {
                        defaultOrderingCount++;
                    }
                    dlisting.SortOrder = defaultOrderingCount;
                    defaultOrderingCount++;
                }
                listing.Directories.Add(dlisting);
            }

            //return the completed listing
            return(listing);
        }