public void AddFile(string path, Stream stream) { FileSystemUtility.AddFile(ProjectFullPath, path, stream, NuGetProjectContext); }
public override Stream CreateFile(string fullPath, INuGetProjectContext nuGetProjectContext) { PendAddedFiles.Add(fullPath); return(FileSystemUtility.CreateFile(fullPath)); }
// App should wait for Sets fully loaded before opening files requested by user (by click or from cmd) // Open files from external links or cmd args on Sets Loaded private async void Sets_Loaded(object sender, RoutedEventArgs e) { int loadedCount = 0; if (!_loaded && EditorSettingsService.IsSessionSnapshotEnabled) { try { loadedCount = await SessionManager.LoadLastSessionAsync(); } catch (Exception ex) { LoggingService.LogError($"[SessionManager] Failed to LoadLastSessionAsync: {ex}"); Analytics.TrackEvent("FailedToLoadLastSession", new Dictionary <string, string> { { "Exception", ex.ToString() } }); } } if (_appLaunchFiles != null && _appLaunchFiles.Count > 0) { loadedCount += await OpenFiles(_appLaunchFiles); _appLaunchFiles = null; } else if (_appLaunchCmdDir != null) { var file = await FileSystemUtility.OpenFileFromCommandLine(_appLaunchCmdDir, _appLaunchCmdArgs); if (file != null && await OpenFile(file)) { loadedCount++; } _appLaunchCmdDir = null; _appLaunchCmdArgs = null; } else if (_appLaunchUri != null) { var operation = NotepadsProtocolService.GetOperationProtocol(_appLaunchUri, out var context); if (operation == NotepadsOperationProtocol.OpenNewInstance || operation == NotepadsOperationProtocol.Unrecognized) { // Do nothing } _appLaunchUri = null; } if (!_loaded) { if (loadedCount == 0) { NotepadsCore.OpenNewTextEditor(_defaultNewFileName); } if (!App.IsFirstInstance) { NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("App_ShadowWindowIndicator_Description"), 4000); } _loaded = true; } if (EditorSettingsService.IsSessionSnapshotEnabled) { SessionManager.IsBackupEnabled = true; SessionManager.StartSessionBackup(); } Window.Current.CoreWindow.Activated -= CoreWindow_Activated; Window.Current.CoreWindow.Activated += CoreWindow_Activated; Application.Current.EnteredBackground -= App_EnteredBackground; Application.Current.EnteredBackground += App_EnteredBackground; }
private async Task <ITextEditor> RecoverTextEditorAsync(TextEditorSessionDataV1 editorSessionData) { StorageFile editingFile = null; if (editorSessionData.EditingFileFutureAccessToken != null) { editingFile = await FileSystemUtility.GetFileFromFutureAccessList(editorSessionData.EditingFileFutureAccessToken); } string lastSavedFile = editorSessionData.LastSavedBackupFilePath; string pendingFile = editorSessionData.PendingBackupFilePath; ITextEditor textEditor; if (editingFile == null && lastSavedFile == null && pendingFile == null) { textEditor = null; } else if (editingFile != null && lastSavedFile == null && pendingFile == null) // File without pending changes { var encoding = EncodingUtility.GetEncodingByName(editorSessionData.StateMetaData.LastSavedEncoding); textEditor = await _notepadsCore.CreateTextEditor(editorSessionData.Id, editingFile, encoding : encoding, ignoreFileSizeLimit : true); textEditor.ResetEditorState(editorSessionData.StateMetaData); } else // File with pending changes { string lastSavedText = string.Empty; string pendingText = null; if (lastSavedFile != null) { TextFile lastSavedTextFile = await FileSystemUtility.ReadFile(lastSavedFile, ignoreFileSizeLimit : true, EncodingUtility.GetEncodingByName(editorSessionData.StateMetaData.LastSavedEncoding)); lastSavedText = lastSavedTextFile.Content; } var textFile = new TextFile(lastSavedText, EncodingUtility.GetEncodingByName(editorSessionData.StateMetaData.LastSavedEncoding), LineEndingUtility.GetLineEndingByName(editorSessionData.StateMetaData.LastSavedLineEnding), editorSessionData.StateMetaData.DateModifiedFileTime); textEditor = _notepadsCore.CreateTextEditor( editorSessionData.Id, textFile, editingFile, editorSessionData.StateMetaData.FileNamePlaceholder, editorSessionData.StateMetaData.IsModified); if (pendingFile != null) { TextFile pendingTextFile = await FileSystemUtility.ReadFile(pendingFile, ignoreFileSizeLimit : true, EncodingUtility.GetEncodingByName(editorSessionData.StateMetaData.LastSavedEncoding)); pendingText = pendingTextFile.Content; } textEditor.ResetEditorState(editorSessionData.StateMetaData, pendingText); } return(textEditor); }
public async Task SaveSessionAsync() { if (!IsBackupEnabled) { LoggingService.LogInfo("Session backup is disabled."); return; } // Serialize saves await _semaphoreSlim.WaitAsync(); Stopwatch stopwatch = Stopwatch.StartNew(); TextEditor[] textEditors = _notepadsCore.GetAllTextEditors(); TextEditor selectedTextEditor = _notepadsCore.GetSelectedTextEditor(); FileSystemUtility.ClearFutureAccessList(); NotepadsSessionDataV1 sessionData = new NotepadsSessionDataV1(); foreach (TextEditor textEditor in textEditors) { if (textEditor.EditingFile != null) { // Add the opened file to FutureAccessList so we can access it next launch await FileSystemUtility.TryAddToFutureAccessList(ToToken(textEditor.Id), textEditor.EditingFile); } if (!_sessionData.TryGetValue(textEditor.Id, out TextEditorSessionData textEditorData)) { textEditorData = new TextEditorSessionData { Id = textEditor.Id }; if (textEditor.IsModified) { if (textEditor.EditingFile != null) { // Persist the last save known to the app, which might not be up-to-date (if the file was modified outside the app) BackupMetadata lastSaved = await SaveLastSavedChangesAsync(textEditor); if (lastSaved == null) { continue; } textEditorData.LastSaved = lastSaved; } // Persist pending changes relative to the last save BackupMetadata pending = await SavePendingChangesAsync(textEditor); if (pending == null) { continue; } textEditorData.Pending = pending; } // We will not create new backup files for this text editor unless it has changes _sessionData.TryAdd(textEditor.Id, textEditorData); } sessionData.TextEditors.Add(textEditorData); if (textEditor == selectedTextEditor) { sessionData.SelectedTextEditor = textEditor.Id; } } bool sessionDataSaved = false; try { string sessionJson = JsonConvert.SerializeObject(sessionData, _encodingConverter); IPropertySet settings = ApplicationData.Current.LocalSettings.Values; if (!settings.TryGetValue(SessionDataKey, out object currentValue) || !string.Equals((string)currentValue, sessionJson, StringComparison.OrdinalIgnoreCase)) { settings[SessionDataKey] = sessionJson; sessionDataSaved = true; } } catch (Exception ex) { LoggingService.LogError($"Failed to save session metadata: {ex.Message}"); return; // Failed to save the session - do not proceed to delete backup files } if (sessionDataSaved) { await DeleteOrphanedBackupFilesAsync(sessionData); } stopwatch.Stop(); if (sessionDataSaved) { LoggingService.LogInfo($"Successfully saved the current session. Total time: {stopwatch.Elapsed.TotalMilliseconds} milliseconds.", consoleOnly: true); } _semaphoreSlim.Release(); }
// App should wait for Sets fully loaded before opening files requested by user (by click or from cmd) // Open files from external links or cmd args on Sets Loaded private async void Sets_Loaded(object sender, RoutedEventArgs e) { int loadedCount = 0; if (!_loaded && EditorSettingsService.IsSessionSnapshotEnabled) { try { loadedCount = await SessionManager.LoadLastSessionAsync(); } catch (Exception ex) { LoggingService.LogError($"[SessionManager] Failed to LoadLastSessionAsync: {ex}"); Analytics.TrackEvent("FailedToLoadLastSession", new Dictionary <string, string> { { "Exception", ex.ToString() } }); } } if (_appLaunchFiles != null && _appLaunchFiles.Count > 0) { loadedCount += await OpenFiles(_appLaunchFiles); _appLaunchFiles = null; } else if (_appLaunchCmdDir != null) { var file = await FileSystemUtility.OpenFileFromCommandLine(_appLaunchCmdDir, _appLaunchCmdArgs); if (file != null && await OpenFile(file)) { loadedCount++; } _appLaunchCmdDir = null; _appLaunchCmdArgs = null; } else if (_appLaunchUri != null) { var operation = NotepadsProtocolService.GetOperationProtocol(_appLaunchUri, out var context); if (operation == NotepadsOperationProtocol.OpenNewInstance || operation == NotepadsOperationProtocol.Unrecognized) { // Do nothing } _appLaunchUri = null; } if (!_loaded) { if (loadedCount == 0) { NotepadsCore.OpenNewTextEditor(_defaultNewFileName); } if (!App.IsFirstInstance) { NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("App_ShadowWindowIndicator_Description"), 4000); } _loaded = true; } if (EditorSettingsService.IsSessionSnapshotEnabled) { SessionManager.IsBackupEnabled = true; SessionManager.StartSessionBackup(); } await BuildOpenRecentButtonSubItems(); if (!App.IsGameBarWidget) { // An issue with the Game Bar extension model and Windows platform prevents the Notepads process from exiting cleanly // when more than one CoreWindow has been created, and NotepadsMainPage is the last to close. The common case for this // is to open Notepads in Game Bar, then open its settings, then close the settings and finally close Notepads. // This puts the process in a bad state where it will no longer open in Game Bar and the Notepads process is orphaned. // To work around this do not use the EnteredBackground event when running as a widget. // Microsoft is tracking this issue as VSO#25735260 Application.Current.EnteredBackground -= App_EnteredBackground; Application.Current.EnteredBackground += App_EnteredBackground; Window.Current.CoreWindow.Activated -= CoreWindow_Activated; Window.Current.CoreWindow.Activated += CoreWindow_Activated; } }
private async Task <TextEditorSessionDataV1> BuildTextEditorSessionData(ITextEditor textEditor) { TextEditorSessionDataV1 textEditorData = new TextEditorSessionDataV1 { Id = textEditor.Id, }; if (textEditor.EditingFile != null) { // Add the opened file to FutureAccessList so we can access it next launch var futureAccessToken = ToToken(textEditor.Id); await FileSystemUtility.TryAddOrReplaceTokenInFutureAccessList(futureAccessToken, textEditor.EditingFile); textEditorData.EditingFileFutureAccessToken = futureAccessToken; textEditorData.EditingFileName = textEditor.EditingFileName; textEditorData.EditingFilePath = textEditor.EditingFilePath; } if (textEditor.IsModified) { if (textEditor.EditingFile != null) { // Persist the last save known to the app, which might not be up-to-date (if the file was modified outside the app) var lastSavedBackupFile = await SessionUtility.CreateNewFileInBackupFolderAsync( ToToken(textEditor.Id) + "-LastSaved", CreationCollisionOption.ReplaceExisting, _backupFolderName); if (!await BackupTextAsync(textEditor.LastSavedSnapshot.Content, textEditor.LastSavedSnapshot.Encoding, textEditor.LastSavedSnapshot.LineEnding, lastSavedBackupFile)) { return(null); // Error: Failed to write backup text to file } textEditorData.LastSavedBackupFilePath = lastSavedBackupFile.Path; } if (textEditor.EditingFile == null || !string.Equals(textEditor.LastSavedSnapshot.Content, textEditor.GetText())) { // Persist pending changes relative to the last save var pendingBackupFile = await SessionUtility.CreateNewFileInBackupFolderAsync( ToToken(textEditor.Id) + "-Pending", CreationCollisionOption.ReplaceExisting, _backupFolderName); if (!await BackupTextAsync(textEditor.GetText(), textEditor.LastSavedSnapshot.Encoding, textEditor.LastSavedSnapshot.LineEnding, pendingBackupFile)) { return(null); // Error: Failed to write backup text to file } textEditorData.PendingBackupFilePath = pendingBackupFile.Path; } } textEditorData.StateMetaData = textEditor.GetTextEditorStateMetaData(); return(textEditorData); }
public virtual async Task AddReferenceAsync(string referencePath) { if (referencePath == null) { throw new ArgumentNullException(nameof(referencePath)); } var name = Path.GetFileNameWithoutExtension(referencePath); var projectName = string.Empty; var projectFullPath = string.Empty; var assemblyFullPath = string.Empty; var dteProjectFullName = string.Empty; var dteOriginalPath = string.Empty; var resolvedToPackage = false; try { // Perform all DTE operations on the UI thread await NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(async delegate { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // Read DTE properties from the UI thread projectFullPath = ProjectFullPath; projectName = ProjectName; dteProjectFullName = VsProjectAdapter.FullName; // Get the full path to the reference assemblyFullPath = Path.Combine(projectFullPath, referencePath); // Add a reference to the project dynamic reference; try { // First try the References3.AddFiles API, as that will incur fewer // design-time builds. References3.AddFiles(new[] { assemblyFullPath }, out var referencesArray); var references = (VSLangProj.Reference[])referencesArray; reference = references[0]; } catch (Exception e) { if (e is InvalidCastException) { // We've encountered a project system that doesn't implement References3, or // there's some sort of setup issue such that we can't find the library with // the References3 type. Send a report about this. TelemetryActivity.EmitTelemetryEvent(new TelemetryEvent("References3InvalidCastException")); } // If that didn't work, fall back to References.Add. reference = References.Add(assemblyFullPath); } if (reference != null) { dteOriginalPath = GetReferencePath(reference); // If path != fullPath, we need to set CopyLocal thru msbuild by setting Private // to true. // This happens if the assembly appears in any of the search paths that VS uses to // locate assembly references. // Most commonly, it happens if this assembly is in the GAC or in the output path. // The path may be null or for some project system it can be "". resolvedToPackage = !string.IsNullOrWhiteSpace(dteOriginalPath) && IsSamePath(dteOriginalPath, assemblyFullPath); if (resolvedToPackage) { // Set reference properties (if needed) TrySetCopyLocal(reference); TrySetSpecificVersion(reference); } } }); if (!resolvedToPackage) { // This should be done off the UI thread // Get the msbuild project for this project var buildProject = EnvDTEProjectUtility.AsMSBuildEvaluationProject(dteProjectFullName); if (buildProject != null) { // Get the assembly name of the reference we are trying to add var assemblyName = AssemblyName.GetAssemblyName(assemblyFullPath); // Try to find the item for the assembly name var item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences() where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2) select assemblyReferenceNode.Item1).FirstOrDefault(); if (item != null) { // Add the <HintPath> metadata item as a relative path var projectPath = PathUtility.EnsureTrailingSlash(projectFullPath); var relativePath = PathUtility.GetRelativePath(projectPath, referencePath); item.SetMetadataValue("HintPath", relativePath); // Set <Private> to true item.SetMetadataValue("Private", "True"); FileSystemUtility.MakeWritable(dteProjectFullName); // Change to the UI thread to save NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // Save the project after we've modified it. await SaveProjectAsync(); }); } } else { // The reference cannot be changed by modifying the project file. // This could be a failure, however that could be a breaking // change if there is a non-msbuild project system relying on this // to skip references. // Log a warning to let the user know that their reference may have failed. NuGetProjectContext.Log( ProjectManagement.MessageLevel.Warning, Strings.FailedToAddReference, name); } } }
protected virtual void PhysicalFileSystemAddFile(string path, Stream stream) { FileSystemUtility.AddFile(ProjectFullPath, path, stream, NuGetProjectContext); }
public void DeleteDirectory(string path, bool recursive) { // Only delete this folder if it is empty and we didn't specify that we want to recurse if (!recursive && (FileSystemUtility.GetFiles(ProjectFullPath, path, "*.*", recursive).Any() || FileSystemUtility.GetDirectories(ProjectFullPath, path).Any())) { NuGetProjectContext.Log(ProjectManagement.MessageLevel.Warning, Strings.Warning_DirectoryNotEmpty, path); return; } NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // Workaround for TFS update issue. If we're bound to TFS, do not try and delete directories. if (SourceControlUtility.GetSourceControlManager(NuGetProjectContext) == null) { var deletedProjectItem = await EnvDTEProjectUtility.DeleteProjectItemAsync(VsProjectAdapter.Project, path); if (deletedProjectItem) { NuGetProjectContext.Log(ProjectManagement.MessageLevel.Debug, Strings.Debug_RemovedFolder, path); } } }); }
public void RemoveFile(string path) { var fullPath = Path.Combine(ProjectFullPath, path); FileSystemUtility.DeleteFile(fullPath, NuGetProjectContext); }
public void DeleteDirectory(string path, bool recursive) { FileSystemUtility.DeleteDirectory(path, recursive, NuGetProjectContext); }
private async void SaveButton_Click(object sender, RoutedEventArgs e) { if (!(sender is TextEditor textEditor)) { textEditor = (Sets.SelectedItem as SetsViewItem)?.Content as TextEditor; if (textEditor == null) { return; } } StorageFile file; if (textEditor.EditingFile == null || e is SaveAsEventArgs || FileSystemUtility.IsFileReadOnly(textEditor.EditingFile) || !await FileSystemUtility.FileIsWritable(textEditor.EditingFile)) { file = await FilePickerFactory.GetFileSavePicker(e, textEditor, DefaultFileName).PickSaveFileAsync(); textEditor.Focus(FocusState.Programmatic); } else { file = textEditor.EditingFile; } if (file == null) { return; } var success = await textEditor.SaveFile(file); if (success) { if (Sets.Items != null) { foreach (SetsViewItem setsItem in Sets.Items) { if (setsItem.Content != textEditor) { continue; } setsItem.Header = file.Name; setsItem.Icon.Visibility = Visibility.Collapsed; PathIndicator.Text = textEditor.EditingFile.Path; LineEndingIndicator.Text = LineEndingUtility.GetLineEndingDisplayText(textEditor.LineEnding); EncodingIndicator.Text = textEditor.Encoding.EncodingName; break; } } ShowNotificationMessage("Saved", 2000); } else { await ContentDialogFactory.GetFileSaveErrorDialog(file).ShowAsync(); } }
private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { IC_ProgressPanel.Visible = false; InvoiceProgressBar.Visible = false; _vPanel.Enabled = true; _hPanel.Enabled = true; void UpdateProductStock() { foreach (var item in _invoicePage.AllProducts) { var product = _productList.Where(x => x.ProductCode.Equals(item.ProductCode)).FirstOrDefault(); if (product != null) { if (_itemList != null) { var previousItem = _itemList.Where(x => x.ProductCode.Equals(item.ProductCode)).FirstOrDefault(); product.StockAvailable += previousItem.Quantity; } product.StockAvailable -= item.Quantity; } } ProductManager.UpdateAllProducts(_productList); } void SaveInvoiceLogFile() { if (!string.IsNullOrEmpty(_invoicePage.CurrentLogFile)) { _invoicePage.PreviousLogFile = _invoicePage.CurrentLogFile; FileSystemUtility.DeleteFile(_invoicePage.CurrentLogFile); } Files invoiceLog = new Files(); invoiceLog.FileLocation = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Invoiceasy\InvoiceLog"; invoiceLog.FileName = "InvoiceLog-" + _invoicePage.No + "_" + DTP_IC_Date.Value.ToString("dd MMMM yyyy") + " " + DateTime.Now.ToString("HH-mm-ss") + ".txt"; _invoicePage.CurrentLogFile = invoiceLog.FileLocation + @"\" + invoiceLog.FileName; invoiceLog.FileText = JsonConvert.SerializeObject(_invoicePage); FileSystemUtility.DeleteFile(_invoicePage.CurrentLogFile); FileSystemUtility.Initialize(true, invoiceLog); FileSystemUtility.WriteFile(); var logFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Invoiceasy" + @"\InvoiceItems\" + "Invoice-" + _invoicePage.No + "_" + "ItemList_" + DTP_IC_Date.Value.ToString("dd MMMM yyyy HH-mm-ss") + ".txt"; FileSystemUtility.CreateFolder(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Invoiceasy" + @"\InvoiceItems"); CsvHelperUtility.WriteDataToFile <ItemModel>(true, logFilePath, ",", _invoicePage.AllProducts); } void AddSale() { var sale = new SalesAndCollectionModel { Id = Guid.NewGuid().ToString("N"), Sl = (SalesAndCollectionManager.GetAllSalesAndCollectionsCount() + 1).ToString(), DealerName = _invoicePage.Dealer.DealerName, Address = _invoicePage.Dealer.Address, Contact = _invoicePage.Dealer.Contact, DealerCode = _invoicePage.Dealer.Code, Date = DTP_IC_Date.Value, IC_NO = _invoicePage.No, MR_NO = "", OpeningBalance = null, SalesAmount = _invoicePage.PayableAmount, CollectionAmount = 0, ClosingBalance = null, Remarks = "", SyncType = "Sales" }; if (_invoicePage.sale == null) { _invoicePage.sale = sale; SalesAndCollectionManager.AddNewSale(sale); } else { SalesAndCollectionManager.UpdateSale(_invoicePage.sale, sale); } } BindInterfaceDataToObject(); UpdateProductStock(); AddSale(); SaveInvoiceLogFile(); if (_isSuccess) { MessageBox.Show("Invoice file has been saved successfully"); } else { MessageBox.Show("Error! Something Went Wrong while saving the file"); } LoadChallanForm(); }