private void AddFileBtn_Click(object sender, EventArgs e) { var openFileDialog = new OpenFileDialog { Multiselect = true }; if (openFileDialog.ShowDialog() == true) { if (!Directory.Exists(Constants.AdditionalDocumentsDirectory)) { Directory.CreateDirectory(Constants.AdditionalDocumentsDirectory); } foreach (var ofdFileName in openFileDialog.FileNames) { var possiblePathToFile = Path.GetFullPath(Path.Combine(Constants.AdditionalDocumentsDirectory + "/" + Path.GetFileName(ofdFileName))); if (!File.Exists(possiblePathToFile)) { File.Copy(ofdFileName, possiblePathToFile); } var fileInfo = new FileInfo(possiblePathToFile); if (!LocalFiles.Contains(fileInfo, new FileInfoEqualityComparer())) { LocalFiles.Add(fileInfo); attachedFilesListView.Items.Add(new ListViewItem(new[] { "Number of contract", fileInfo.Name, fileInfo.FullName })); } } } IsDirty = true; }
public async Task RoamFile(IBindableStorageFile file) { using (await f_lock.Acquire()) { if (!RoamedFiles.Contains(file)) { //Backing values string oldPath = GetParentFolder(file.BackingFile); string value = await _ivService.GetValue(oldPath, FileLocation.Local); await _ivService.Remove(oldPath, FileLocation.Local); await file.BackingFile.MoveAsync(_roamingFolder, file.BackingFile.Name, NameCollisionOption.GenerateUniqueName); await _ivService.Add(GetParentFolder(file.BackingFile), value, FileLocation.Roamed); LocalFiles.Remove(file); //UI file.IsRoamed = true; RoamedFiles.Add(file); } } }
/// <summary> /// Saves and encrypts the contents into a StorageFile with the given name, and the given password. /// </summary> /// <param name="contents">The contents to encrypt.</param> /// <param name="fileName">The filename with which to save the file.</param> /// <param name="password">The password that will be used to generate the encryption key.</param> /// <returns>If successful, returns the created StorageFile.</returns> public async Task <BindableStorageFile> SaveAndEncryptFileAsync(string contents, string fileName, string password) { using (await f_lock.Acquire()) { if (!_initialized) { throw new ServiceNotInitializedException($"{nameof(FileService)} was not initialized before access was attempted."); } if (contents == null) { throw new ArgumentException("File contents cannot be null."); } string iv = Guid.NewGuid().ToString("N"); // OLD IV code. string encryptedContents = LegacyEncryptionManager.Encrypt(contents, password, iv); var savedFile = await _localFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName); await FileIO.WriteTextAsync(savedFile, encryptedContents); string savedFileName = savedFile.Name; BindableStorageFile bsf = await BindableStorageFile.Create(savedFile); LocalFiles.Add(bsf); await _ivService.Add(GetParentFolder(bsf.BackingFile), iv, FileLocation.Local); return(bsf); } }
public void CopyFileToPermDataPath() { const string patternFileBasename = "DefaultSpawnPattern"; const string patternFile = patternFileBasename + "-test.xml"; string targetFile = Path.Combine(Application.persistentDataPath, patternFile); LocalFiles.CopyResourceToPersistentData(patternFileBasename, patternFile); Assert.That(File.Exists(targetFile)); File.Delete(patternFile); }
public void ReadLocalFiles() { LocalFiles.Clear(); if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Minesweeper")) { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Minesweeper"); } String[] rawfiles = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Minesweeper"); foreach (String s in rawfiles) { if (s.Contains(".map")) { LocalFiles.Add(s); } } }
private void slurpFiles(XmlSerializer serializer) { _localFiles = new LocalFiles { Locations = Settings.Default.Locations, ThreadsPerProcessor = Settings.Default.ThreadsPerProcessor, Extensions = Settings.Default.Extensions }; _localFiles.Slurp(); TextWriter writer = new StreamWriter(Path.Combine(_path, "LocalFiles.xml")); serializer.Serialize(writer, _localFiles); writer.Close(); }
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); string localFilesPath = Path.Combine(_path, "LocalFiles.xml"); XmlSerializer serializer = new XmlSerializer(typeof(LocalFiles)); if (File.Exists(localFilesPath)) { // Read and deserialize the cached data if it exists. // TODO: Add expiration date logic to re-slurp files. TextReader reader = new StreamReader(localFilesPath); try { _localFiles = (LocalFiles)serializer.Deserialize(reader); reader.Close(); } catch (InvalidOperationException unused) { MessageBox.Show("There was an error reading the cache file. Recreating it now.", "Error reading settings!", MessageBoxButtons.OK, MessageBoxIcon.Error); reader.Close(); // If the file was unreadable slurp the files from the specified locations. slurpFiles(serializer); } } else { // If the file doesn't exist slurp files from the specified locations. slurpFiles(serializer); } stopwatch.Stop(); Trace.WriteLine(string.Format("Total time: {0}", stopwatch.Elapsed)); Trace.WriteLine(string.Format("Total songs added: {0}", _localFiles.Songs.Count)); }
public void ShouldBeAbleToCreateJobModelTypes() { var created = from simpleCommand in Command.NewSimpleCommand("echo 'Hello, World!'").Lift("simple-command") from parameterizedCommand in Command.NewParametrizedCommand( new ParametrizedCommand( "echo 'Hello, %user%'", new[] { "user" }.ToFSharpList())).Lift() from tryWithCatch in new CommandWithErrorHandler(parameterizedCommand, FSharpOption <Command> .Some(simpleCommand)).Lift( "try-with-catch") from tryWithoutCatch in new CommandWithErrorHandler(simpleCommand, FSharpOption <Command> .None).Lift("try-without-catch") from commandSet0 in CommandSet.Zero.Lift() from commandSet in new CommandSet( new[] { tryWithCatch }.ToFSharpList(), new[] { simpleCommand }.ToFSharpList()).Lift() from localFiles0 in LocalFiles.Zero.Lift() from localFiles in LocalFiles.NewLocalFiles( new[] { new FileInfo("temp.txt") }.ToFSharpList()).Lift() from uploadedFiles0 in UploadedFiles.Zero.Lift() from uploadedFiles in UploadedFiles.NewUploadedFiles( new[] { new ResourceFile("blobSource", "blobPath") }.ToFSharpList()).Lift("uploaded-files") from workloadUnitTemplate0 in WorkloadUnitTemplate.Zero.Lift() from workloadUnitTemplate in new WorkloadUnitTemplate(commandSet, localFiles, false).Lift() from workloadArguments0 in WorkloadArguments.Zero.Lift() from workloadArguments in WorkloadArguments.NewWorkloadArguments( new Dictionary <string, FSharpList <string> > { { "users", new[] { "john", "pradeep" }.ToFSharpList() } }.ToFSharpMap()).Lift() from workloadSpecification in new WorkloadSpecification( new[] { workloadUnitTemplate }.ToFSharpList(), LocalFiles.Zero, workloadArguments).Lift() from taskName in TaskName.NewTaskName("simple-task").Lift() from taskArguments0 in TaskArguments.Zero.Lift() from taskArguments in TaskArguments.NewTaskArguments( new Dictionary <string, string> { { "name", "john" } }.ToFSharpMap()).Lift() from defaultTaskSpecification in TaskSpecification.Zero.Lift() from jobName in JobName.NewJobName("simple-job").Lift() from nullJobPriority in JobPriority.NewJobPriority(null).Lift() from jobPriority in JobPriority.NewJobPriority(10).Lift() from defaultJobSpecification in JobSpecification.Zero.Lift() select "done"; Assert.AreEqual("done", created.Value); }
public AdditionalInfoControl(AdditionalInfo model) { Model = model; InitializeComponent(); #region AddInfo table if (Model?.AddInfoTable != null) { foreach (var addInfo in Model.AddInfoTable) { AddInfoListView.Items.Add(new ListViewItem(new[] { addInfo.NumberOfContract, addInfo.Notes, addInfo.OtherParticipants })); } } AddInfoListView.EditTextBox.TextChanged += (sender, args) => IsDirty = true; #endregion AddInfo table if (!Directory.Exists(Constants.AdditionalDocumentsDirectory)) { Directory.CreateDirectory(Constants.AdditionalDocumentsDirectory); } var dir = new DirectoryInfo(Constants.AdditionalDocumentsDirectory); var files = dir.GetFiles(); if (Model?.AttachedFiles != null) { //var result = Model.AttachedFiles.Intersect(files, new FileInfoEqualityComparer()); //For changing file path if the user relocate folder with program var result = files.Intersect(Model.AttachedFiles, new FileInfoEqualityComparer()); attachedFilesListView.Items.AddRange(result.Select(c => new ListViewItem(new[] { Model.ContractFileInfo.ContainsKey(c.FullName) ? Model?.ContractFileInfo[c.FullName] : "Number of contract", c.Name, c.FullName })).ToArray()); foreach (var item in result) { LocalFiles.Add(new FileInfo(item.FullName)); } } else { Model.AttachedFiles = new List <FileInfo>(); } searchTextBox.TextChanged += (sender, args) => { attachedFilesListView.Items.Clear(); // clear list items before adding // filter the items match with search key and add result to list view attachedFilesListView.Items.AddRange(LocalFiles .Where(i => string.IsNullOrEmpty(searchTextBox.Text.ToLowerInvariant()) || i.Name.ToLowerInvariant().Contains(searchTextBox.Text.ToLowerInvariant())) .Select(c => new ListViewItem(new[] { Model.ContractFileInfo.ContainsKey(c.FullName) ? Model?.ContractFileInfo[c.FullName] : "Number of contract", c.Name, c.FullName })).ToArray()); IsDirty = true; }; IsDirty = false; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Autodesk.Revit.ApplicationServices.Application app = uiapp.Application; Document doc = uidoc.Document; Document docUi = uidoc.Document; bool allGoodInTheHood = false; //app.SharedParametersFilename = LocalFiles.localSpFile; //DefinitionFile defFile = app.OpenSharedParameterFile(); //DefinitionGroups myGroups = defFile.Groups; //DefinitionGroup myGroup = myGroups.get_Item("Mechanical"); //Definitions myDefinitions = myGroup.Definitions; //ExternalDefinition eDef = myDefinitions.get_Item("AirFlowAirTerminal") as ExternalDefinition; // Create local directory LocalFiles.CreateLocalDir(); // Checks last time the OpenRFA online database was udpated LocalFiles.GetLastUpdateJsonOnline(); MainWindow appDialog = new MainWindow(); appDialog.WindowStartupLocation = WindowStartupLocation.CenterScreen; // Prompt user to select files Microsoft.Win32.OpenFileDialog openFilesDlg = new Microsoft.Win32.OpenFileDialog(); // Set filter for file extension and default file extension openFilesDlg.DefaultExt = ".rfa"; openFilesDlg.Filter = "Revit Family (*.rfa)|*.rfa"; openFilesDlg.Multiselect = true; openFilesDlg.Title = "Select Revit families to load parameters"; // Only open window if continueCommand is set true if (ImportProcess.continueCommand == true) { openFilesDlg.ShowDialog(); // Only open MainWindow if files are selected if (openFilesDlg.FileNames.Length > 0) { appDialog.ShowDialog(); // Print all families to be modified StringBuilder sb = new StringBuilder(); sb.Append("The following files will be modified. It is recommended to backup your families before proceeding. Would you like to continue?\n\n"); foreach (string fileName in openFilesDlg.FileNames) { sb.Append(fileName + "\n"); } MessageBoxResult resultConfirmOverwrite = System.Windows.MessageBox.Show(sb.ToString(), "Warning", MessageBoxButton.OKCancel); switch (resultConfirmOverwrite) { // Execute command if user confirmed case MessageBoxResult.OK: // Only executes if the user clicked "OK" button if (appDialog.DialogResult.HasValue && appDialog.DialogResult.Value) { // Opens configuration window ConfigureImport confDialog = new ConfigureImport(); confDialog.WindowStartupLocation = WindowStartupLocation.CenterScreen; confDialog.ShowDialog(); // Only execute command if configure process is committed by user if (confDialog.DialogResult.HasValue && confDialog.DialogResult.Value) { // Iterate through selected families and add parameters to each foreach (string fileName in openFilesDlg.FileNames) { // Check if user is trying to modify active doc if (fileName == docUi.PathName) { System.Windows.MessageBox.Show("This addin cannot be run on the active document. This family has been skipped in the process: \n" + fileName); } else { System.Windows.MessageBox.Show("Adding parameters to: " + fileName); doc = app.OpenDocumentFile(fileName); // Complete import process ImportProcess.ProcessImport(doc, app, confDialog.DialogResult.HasValue, confDialog.DialogResult.Value); doc.Close(true); } } } } // Clear all data in case addin is run again in the same session // TODO: Call this method with every method that uses the datatables? ImportProcess.ClearAllData(); allGoodInTheHood = true; break; case MessageBoxResult.Cancel: ImportProcess.ClearAllData(); allGoodInTheHood = false; break; } } } // Return results if (allGoodInTheHood) { return(Result.Succeeded); } else { return(Result.Cancelled); } }