Example #1
0
        public void FileOpenTests()
        {
            FileOpener reader = new FileOpener();

            reader.OpenFile(@"c:/file.txt");
            //If fails should throw an exception
        }
Example #2
0
        /// <summary>
        /// All static classes and singletons meant for global
        /// usage are activated here. Some areas depend on these classes having their
        /// data loaded before the program starts (e.g., OdometerTracker), so it
        /// is very important that they are called here. All static classes should at
        /// the bare minimum implement an empty Activate() method to ensure their
        /// constructors are called
        /// </summary>
        private void ActivateStaticClasses()
        {
            EventBridge.Initialize();
            DiagnosticsParser.Initialize();
            CanMessageHandler.Initialize();
            ConfigManager.LoadConfiguration();
            DiagnosticLogger.Initialize();
            RawLogger.Initialize();
            PIDValueStager.Initialize();
            _EngineDataParser = new EngineDataParser();
            _Acceleration     = new Acceleration();
            _Trackers         = new Trackers();
            ChassisParameters.Initialize();
            var engineFilePointer = new FileOpener(ConfigManager.Settings.Contents.engineFilePath);

            if (engineFilePointer.Exists())
            {
                EngineSpec.SetEngineFile(engineFilePointer.absoluteFilepath);
            }
            else
            {
                MessageBox.Show("No engine files can be found. Horsepower and Torque settings will be inaccurate");
            }
            SPNDefinitions.Activate();      //in VMSpc/Parsers/J1939/SPNDefinitions.cs - Defines every SPN object
            //Odometer.Activate();
            //ParamData.Activate();
            TireManager.Initialize();
            CommunicationManager.Initialize();
            DayNightManager.Initialize();
        }
Example #3
0
 public static bool InstallDrivers()
 {
     try
     {
         if (!FileOpener.DirectoryExists("\\installer"))
         {
             var installerZipFile = new FileOpener("\\InstallerArchive.zip").absoluteFilepath;
             using (var client = new WebClient())
             {
                 client.DownloadFile("https://www.silverleafelectronics.com/silverleafelectronics.com/sites/default/files/2019-04/Signed_Drivers_Only_04-16-2015.zip", installerZipFile);
                 if (FileOpener.FileExists("\\InstallerArchive.zip"))
                 {
                     UnzipInstallerArchive();
                     FileOpener.DeleteFile("\\InstallerArchive.zip");
                 }
             }
         }
         var process = Process.Start(new FileOpener("\\installer").absoluteFilepath + "\\Signed_Drivers_Only_04-16-2015\\Install_Drivers.exe");
         process.WaitForExit();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Example #4
0
        private void btnReadFile_Click(object sender, System.EventArgs e)
        {
            this.lblFileSizeValue.Text = string.Empty;

            string fileName = this.txtFileName.Text;

            if (fileName != null && fileName.Length > 0)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;
                    FileOpener opener   = new FileOpener();
                    int        fileSize = opener.ReadFile(fileName);
                    this.lblFileSizeValue.Text = fileSize.ToString();
                }
                catch (Exception ex)
                {
                    this.Cursor = Cursors.Default;
                    MessageBox.Show(this, ex.Message, "File Opener Exception",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation);
                    MessageBox.Show(this, ex.StackTrace, "File Opener Exception",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }
Example #5
0
        private void OpenFileWithSelectedResult(object sender)
        {
            try
            {
                var result = sender as ListBoxItem;
                if (result != null)
                {
                    string[] searchKeys   = GetKeys(this.searchKey);
                    var      searchResult = result.Content as CodeSearchResult;
                    FileOpener.OpenItem(searchResult);
                    Task.Factory.StartNew(() =>
                    {
                        Thread.Sleep(500);
                        this.Dispatcher.BeginInvoke(HighlightStuffInvoker, searchResult.ProgramElement.FullFilePath, searchResult.
                                                    ProgramElement.DefinitionLineNumber, searchResult.ProgramElement.RawSource, searchKeys);
                    });

                    var matchDescription = QueryMetrics.DescribeQueryProgramElementMatch(searchResult.ProgramElement, searchBox.Text);
                    LogEvents.OpeningCodeSearchResult(searchResult, SearchResults.IndexOf(searchResult) + 1, matchDescription);
                }
            }
            catch (ArgumentException aex)
            {
                LogEvents.UIGenericError(this, aex);
                MessageBox.Show(FileNotFoundPopupMessage, FileNotFoundPopupTitle, MessageBoxButton.OK);
            }
            catch (Exception ee)
            {
                LogEvents.UIGenericError(this, ee);
                MessageBox.Show(FileNotFoundPopupMessage, FileNotFoundPopupTitle, MessageBoxButton.OK);
            }
        }
Example #6
0
        public override void Open()
        {
            FileOpener opener = new FileOpener(this);

            opener.window.ClearHtml.IsEnabled = true;
            opener.Open();
        }
        private void ChangeLogFile_Click(object sender, RoutedEventArgs e)
        {
            //"Text files (*.txt)|*.txt|All files (*.*)|*.*";
            var dlg = new FileSelector("\\rawlogs", CurrentLogFile.Text, "vms")
            {
                Owner = this,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                ExcludeLockedFiles    = true,
                AllowNewFiles         = true,
                NewFilesExtension     = ".vms",
                AllowImports          = true,
                ImportFilter          = "VMS Log Files (*.vms)|*.vms",
            };

            if ((bool)dlg.ShowDialog())
            {
                bool okayToUseFile = true;
                var  newFilePath   = dlg.ResultFilePath;
                if (!FileOpener.IsFileEmpty(newFilePath))
                {
                    string           messageBoxText = FileOpener.GetFileName(newFilePath) + " already exists. Logging to this file will overwrite it. Do you want to continue?";
                    string           caption        = "VMS Logging";
                    MessageBoxButton yesNoBtn       = MessageBoxButton.YesNoCancel;
                    MessageBoxImage  icon           = MessageBoxImage.Warning;
                    MessageBoxResult messageResult  = MessageBox.Show(messageBoxText, caption, yesNoBtn, icon);
                    okayToUseFile = (messageResult == MessageBoxResult.Yes);
                }
                if (okayToUseFile)
                {
                    Settings.rawLogFilePath = newFilePath;
                    SetCurrentLogFileText();
                }
            }
        }
 private void ToggleLog_Click(object sender, RoutedEventArgs e)
 {
     if (LogRecordingEnabled)
     {
         LogRecordingEnabled = false;
         RawLogger.Instance.Stop();
     }
     else if (!LogRecordingEnabled)
     {
         LogRecordingEnabled = true;
         //empty the file contents
         try
         {
             MessageBoxResult messageResult = MessageBox.Show("Do you want to erase existing file contents before logging?", "Start Raw Log", MessageBoxButton.YesNo);
             if (messageResult == MessageBoxResult.Yes)
             {
                 FileOpener.WriteAllText(Settings.rawLogFilePath, string.Empty);
             }
             RawLogger.Instance.Start();
             MessageBox.Show("Logging Initiated");
         }
         catch (IOException)
         {
             LogRecordingEnabled = false;
             MessageBox.Show($"The file {Settings.rawLogFilePath} cannot be written to. It is either being used by a different process, or it does not exist.\n" +
                             $"Verify that it exists by clicking the Change Log File button and viewing the available Raw Log files.\n" +
                             $"To verify that it is not being used by VMSpc, go to Advanced->Communications and check that it is not in use by the Log Player");
         }
         catch (Exception ex)
         {
             ErrorLogger.GenerateErrorRecord(ex);
         }
     }
     SetLogButtonText();
 }
Example #9
0
        public void OpenBadNotEnoughNumbersTxtFile()
        {
            CreateBadNotEnoughNumbersTxtFile();
            var opener = new FileOpener();

            Assert.Throws <FileLoadException>(() => opener.OpenKrotTxt(filename));
        }
Example #10
0
        private static void UnzipInstallerArchive()
        {
            var SourceZipFilePath      = new FileOpener("\\InstallerArchive.zip").absoluteFilepath;
            var RelativeDeploymentPath = new FileOpener("\\installer").absoluteFilepath;

            ZipFile.ExtractToDirectory(SourceZipFilePath, RelativeDeploymentPath);
        }
Example #11
0
        private void Open_Execute(object sender, ExecutedRoutedEventArgs e)
        {
            if (!SaveModified())
            {
                return;
            }

            var dlg = new Microsoft.Win32.OpenFileDialog();

            dlg.Filter      = GetFileDialogFilter();
            dlg.Multiselect = false;
            if (dlg.ShowDialog() == true)
            {
                var hostedScript = new HostedScriptEngine();
                hostedScript.CustomConfig = CustomConfigPath(dlg.FileName);
                SetEncodingFromConfig(hostedScript);

                using (var fs = FileOpener.OpenReader(dlg.FileName))
                {
                    txtCode.Text    = fs.ReadToEnd();
                    _currentDocPath = dlg.FileName;
                    this.Title      = _currentDocPath;
                }
            }
        }
Example #12
0
        public static void OnBeforeScriptRead(HostedScriptEngine engine)
        {
            var cfg = engine.GetWorkingConfig();

            string openerEncoding = cfg["encoding.script"];

            if (!String.IsNullOrWhiteSpace(openerEncoding))
            {
                if (StringComparer.InvariantCultureIgnoreCase.Compare(openerEncoding, "default") == 0)
                {
                    engine.Loader.ReaderEncoding = FileOpener.SystemSpecificEncoding();
                }
                else
                {
                    engine.Loader.ReaderEncoding = Encoding.GetEncoding(openerEncoding);
                }
            }

            var strictWebRequest = ConvertSettingValueToBool(cfg["http.strictWebRequest"]);

            if (!strictWebRequest)
            {
                SetAllowUnsafeHeaderParsing();
            }
        }
Example #13
0
        void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (IsEdited())
            {
                MessageBox.Show("yay it works");
            }
            var f = new FileOpener();

            ShiftWM.Init(f, "testing", null);
        }
Example #14
0
        public void OpenTxtSimple()
        {
            CreateBasicTxtFile();
            var opener = new FileOpener();

            var cmpScan = opener.OpenKrotTxt(filename);

            Assert.Equal(2, cmpScan.LengthDimensionless);
            Assert.Equal(3, cmpScan.AscanLengthDimensionless);
        }
 private bool PassesConditions(string filename)
 {
     if (!PassesFilter(filename))
     {
         return(false);
     }
     if (ExcludeLockedFiles)
     {
         bool isUsed = !FileOpener.IsFileLocked(filename, FilePathType.Absolute);
         return(isUsed);
     }
     return(true);
 }
Example #16
0
        public void Execute(object parameter)
        {
            var Opener = new FileOpener(Encoding.Default, ControlType.CSV);

            if (parameter == null)
            {
                Opener.OpenFile();
            }
            else
            {
                Opener.OpenFile((string)parameter);
            }
        }
Example #17
0
 private void WriteLogEntries()
 {
     if (MessagesToWrite.Count > 0)
     {
         using (streamWriter = new StreamWriter(FileOpener.GetAbsoluteFilePath(Settings.rawLogFilePath)))
         {
             foreach (var DataEvent in MessagesToWrite)
             {
                 streamWriter.WriteLine(DataEvent.timeStamp.ToString());
                 streamWriter.WriteLine(DataEvent.message);
             }
         }
     }
 }
Example #18
0
        public void Template_InputHtml_HideSection_RemovesFromHtml()
        {
            // Given
            Template template = new Template(FileOpener.GetMailExample("Input"));

            // When
            template.AddReplacement("subject", "World");
            template.RemoveSection("MY-HIDE-SECTION");
            StringifiedTemplate output = template.Stringify();

            // Then
            Assert.That(output.Title, Is.EqualTo("Hello World"));
            Assert.That(output.Body, Is.EqualTo(FileOpener.GetMailExample("Expected")));
        }
Example #19
0
        private void ButtonSearchFilePath_Click(object sender, EventArgs e)
        {
            if (File.Exists(TextFilePath.Text))
            {
                FileOpener.FileName = TextFilePath.Text;
            }

            FileOpener.Filter = APIList.SelectedItem.ToString() + "|*" + (APICategory.SelectedIndex == 0 ? "Q" : "S") + "@" + APIList.SelectedItem.ToString().Replace('/', '@') + ".json|JSON|*.json;*.js|File|*";

            if (FileOpener.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                TextFilePath.Text = FileOpener.FileName;
            }
        }
Example #20
0
 private static bool UnzipEngineArchive()
 {
     try
     {
         var SourceZipFilePath      = new FileOpener("\\EngineArchive.zip").absoluteFilepath;
         var RelativeDeploymentPath = new FileOpener("\\engines").absoluteFilepath;
         ZipFile.ExtractToDirectory(SourceZipFilePath, RelativeDeploymentPath);
         MoveToBaseEnginePath();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
 private void TestButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         mediaPlayer.Stop();
         mediaPlayer.Close();
         var uri = new Uri(FileOpener.GetAbsoluteFilePath(SoundFile.Text));
         mediaPlayer.Open(uri);
         mediaPlayer.Play();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
        private void ImportButton_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog()
            {
                Multiselect      = true,
                InitialDirectory = System.IO.Path.GetPathRoot(Environment.SystemDirectory),
            };

            if (!string.IsNullOrEmpty(ImportFilter))
            {
                openFileDialog.Filter = ImportFilter;
            }
            if (!string.IsNullOrEmpty(DefaultImportExtension))
            {
                openFileDialog.DefaultExt = DefaultImportExtension;
            }
            if (openFileDialog.ShowDialog() == true)
            {
                bool hasInvalidFiles = false;
                var  invalidFiles    = new List <string>();
                foreach (string filename in openFileDialog.FileNames)
                {
                    try
                    {
                        FileOpener.CopyFile(filename, RelativeDirectoryPath + "\\" + FileOpener.GetFileName(filename));
                    }
                    catch (IOException) //should only get thrown if a user tries to import a file from the same directory
                    {
                        hasInvalidFiles = true;
                        invalidFiles.Add(FileOpener.GetFileName(filename));
                    }
                    catch (Exception ex)
                    {
                        ErrorLogger.GenerateErrorRecord(ex);
                    }
                }
                if (hasInvalidFiles)
                {
                    string errorMessage = "Some files failed to copy because of naming conflicts with files in the current directory. Please rename the following files before trying to import them: ";
                    foreach (var file in invalidFiles)
                    {
                        errorMessage += "\n" + file;
                    }
                    MessageBox.Show(errorMessage);
                }
            }
            AddFileRows();
        }
        private void NewFileButton_Click(object sender, RoutedEventArgs e)
        {
            var addFileDlg = new AddFileDlg()
            {
                Extension             = NewFilesExtension,
                Owner                 = this,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
            };
            bool added = false;

            if ((bool)addFileDlg.ShowDialog())
            {
                if (!string.IsNullOrEmpty(addFileDlg.FileName))
                {
                    var newFile = addFileDlg.FileName + addFileDlg.Extension;
                    if (!DisplayedfileNames.Contains(newFile))
                    {
                        FileOpener.WriteAllText(RelativeDirectoryPath + "\\" + newFile, string.Empty);
                        added = true;
                    }
                    else
                    {
                        MessageBox.Show($"Cannot add {newFile}, because it already exists in this directory. Please enter a unique file name when adding new files");
                    }
                }
                else
                {
                    MessageBox.Show("Cannot add a new file without a file name");
                }
            }
            AddFileRows();
            if (added)
            {
                foreach (var item in DisplayedFiles.Items)
                {
                    if ((item as ListBoxItem) != null)
                    {
                        if ((item as ListBoxItem).Content.ToString() == (addFileDlg.FileName + addFileDlg.Extension))
                        {
                            (item as ListBoxItem).IsSelected = true;
                        }
                    }
                }
            }
        }
        public static void OnBeforeScriptRead(HostedScriptEngine engine)
        {
            var cfg = engine.GetWorkingConfig();

            string openerEncoding = cfg["encoding.script"];

            if (!String.IsNullOrWhiteSpace(openerEncoding))
            {
                if (StringComparer.InvariantCultureIgnoreCase.Compare(openerEncoding, "default") == 0)
                {
                    engine.Loader.ReaderEncoding = FileOpener.SystemSpecificEncoding();
                }
                else
                {
                    engine.Loader.ReaderEncoding = Encoding.GetEncoding(openerEncoding);
                }
            }
        }
Example #25
0
        private async void FileReceived(string fileId)
        {
            if (fileId == _vm?.File?.FileId.ToString())
            {
                MessagingCenter.Unsubscribe <string>(this, Events.Events.FileReceived);

                if (!FileOpener.Open(_vm.File.FileId.ToString(), _vm.File.MimeType, Configuration.OpenableTempFolderName))
                {
                    await DisplayAlert(
                        "No application",
                        $"You don not have an application that can open the following file type:  '{_vm.File.MimeType}'. Download a program that can handle this file type, then try again.",
                        "Ok");
                }
            }

            await Task.Delay(1000);

            _vm.FetchFiles();
        }
Example #26
0
        private static void MoveToBaseEnginePath()
        {
            var absoluteDir       = new FileOpener("\\engines\\Additional_Engines_(10-09-2018)").absoluteFilepath;
            var absoluteSourceDir = new FileOpener("\\engines").absoluteFilepath;
            var dirFiles          = FileOpener.GetDirectoryFiles("\\engines\\Additional_Engines_(10-09-2018)");

            foreach (var file in dirFiles)
            {
                FileInfo mFile = new FileInfo(file);
                mFile.MoveTo(absoluteSourceDir + "\\" + mFile.Name);
            }
            try
            {
                Cleanup();
            }
            catch (Exception ex)
            {
                ErrorLogger.GenerateErrorRecord(ex);
            }
        }
Example #27
0
 public static bool DownloadEngines()
 {
     try
     {
         var engineZipFile = new FileOpener("\\EngineArchive.zip").absoluteFilepath;
         using (var client = new WebClient())
         {
             client.DownloadFile("https://silverleafelectronics.com/silverleafelectronics.com/sites/default/files/2019-04/Additional_Engines_%2810-09-2018%29.zip", engineZipFile);
             if (FileOpener.FileExists("\\EngineArchive.zip"))
             {
                 return(UnzipEngineArchive());
             }
         }
     }
     catch
     {
         return(false);
     }
     return(false);
 }
Example #28
0
        private void Generate()
        {
            IList <IPerson> people = GetPeopleList();

            // Generate data
            DaysOffData        daysOff  = new DaysOffData(Year);
            AttendanceListData listData = new AttendanceListData(daysOff, people, Month, Year);

            // Create document generator
            LocalizedNames localizedNames = new LocalizedNames();
            AttendanceListDocumentGenerator documentGenerator = new AttendanceListDocumentGenerator(listData, localizedNames);

            // Set document generator settings
            documentGenerator.EnableColors          = EnableColors;
            documentGenerator.EnableHolidaysTexts   = EnableHolidaysTexts;
            documentGenerator.EnableSundaysTexts    = EnableSundaysTexts;
            documentGenerator.EnableTableStretching = EnableTableStretching;

            // Generate a document
            Document document = documentGenerator.GenerateDocument();

            // Get directory path and filename
            DirectoryProvider directoryProvider = new DirectoryProvider(localizedNames);
            FilenameGenerator filenameGenerator = new FilenameGenerator(localizedNames, _dateTimeProvider);
            string            path     = directoryProvider.GetDocumentsDirectoryPath();
            string            filename = filenameGenerator.GeneratePdfDocumentFilename(listData);

            // Save document
            FileSaver fileSaver = new FileSaver();

            fileSaver.SavePdfDocument(document, path, filename);

            // And open it
            FileOpener fileOpener = new FileOpener();

            fileOpener.OpenFile(path, filename);

            SerializeSettings(directoryProvider, filenameGenerator, fileSaver);
        }
Example #29
0
 internal static Brush GetHistoryTextColor()
 {
     if (FileOpener.Is2012OrLater())
     {
         var key   = Microsoft.VisualStudio.Shell.VsBrushes.ToolWindowTabMouseOverTextKey;
         var color = (Brush)Application.Current.Resources[key];
         var other = (Brush)Application.Current.Resources[Microsoft.VisualStudio.Shell.VsBrushes.ToolWindowBackgroundKey];
         if (color.ToString().Equals(other.ToString()))
         {
             return((Brush)Application.Current.Resources[Microsoft.VisualStudio.Shell.VsBrushes.HelpSearchResultLinkSelectedKey]);
         }
         else
         {
             return(color);
         }
     }
     else
     {
         var key = Microsoft.VisualStudio.Shell.VsBrushes.HelpSearchResultLinkSelectedKey;
         return((Brush)Application.Current.Resources[key]);
     }
 }
Example #30
0
        private void Open()
        {
            DialogResult dialogResult = FileOpener.ShowDialog();

            if (dialogResult == DialogResult.OK)
            {
                if (FileOpener.CheckFileExists)
                {
                    string file = FileOpener.FileName;
                    try
                    {
                        OpenFile(file);
                    }
                    catch (IOException)
                    {
                        if (ucfg.Default.language != "EN")
                        {
                            MessageBox.Show(ParseIt(LanguageFile, "messages", "openFileError"), "ERROR!");
                        }
                        else
                        {
                            MessageBox.Show("An error returned while openin file.", "ERROR!");
                        }
                    }
                }
                else
                {
                    if (ucfg.Default.language != "EN")
                    {
                        MessageBox.Show(ParseIt(LanguageFile, "messages", "fileFindError"), "ERROR!");
                    }
                    else
                    {
                        MessageBox.Show("File not found!", "ERROR!");
                    }
                }
            }
        }