public async Task AddOrUpdateProfileAsync_ProfileDoesntExist(bool addToFront, int expectedIndex, bool isInMemory)
        {
            var moqFS    = new IFileSystemMock();
            var provider = GetLaunchSettingsProvider(moqFS);

            var profiles = new List <ILaunchProfile>()
            {
                { new LaunchProfile()
                  {
                      Name = "IIS Express", CommandName = "IISExpress", LaunchBrowser = true
                  } },
                { new LaunchProfile()
                  {
                      Name = "bar", ExecutablePath = "c:\\test\\project\\bin\\test.exe", CommandLineArgs = @"-someArg"
                  } }
            };

            var testSettings = new Mock <ILaunchSettings>();

            testSettings.Setup(m => m.Profiles).Returns(profiles.ToImmutableList());

            provider.SetCurrentSnapshot(testSettings.Object);

            var newProfile = new LaunchProfile()
            {
                Name = "test", CommandName = "Test", DoNotPersist = isInMemory
            };

            await provider.AddOrUpdateProfileAsync(newProfile, addToFront).ConfigureAwait(true);

            // Check disk file was written unless not in memory
            Assert.Equal(!isInMemory, moqFS.FileExists(provider.LaunchSettingsFile));

            // Check snapshot
            AssertEx.CollectionLength(provider.CurrentSnapshot.Profiles, 3);
            Assert.Equal("Test", provider.CurrentSnapshot.Profiles[expectedIndex].CommandName);
            Assert.Null(provider.CurrentSnapshot.Profiles[expectedIndex].ExecutablePath);
        }
        public async Task UpdateProfiles_MergeInMemoryProfiles()
        {
            var moqFS = new IFileSystemMock();

            using (var provider = GetLaunchSettingsProvider(moqFS))
            {
                moqFS.WriteAllText(provider.LaunchSettingsFile, JsonString1);

                var curProfiles = new Mock <ILaunchSettings>();
                curProfiles.Setup(m => m.Profiles).Returns(() =>
                {
                    return(new List <ILaunchProfile>()
                    {
                        { new LaunchProfile()
                          {
                              Name = "IIS Express", CommandName = "IISExpress", LaunchBrowser = true, DoNotPersist = true
                          } },
                        { new LaunchProfile()
                          {
                              Name = "InMemory1", DoNotPersist = true
                          } },
                        { new LaunchProfile()
                          {
                              Name = "ShouldNotBeIncluded", CommandName = LaunchSettingsProvider.ErrorProfileCommandName, DoNotPersist = true
                          } }
                    }.ToImmutableList());
                });

                provider.SetCurrentSnapshot(curProfiles.Object);

                await provider.UpdateProfilesAsyncTest(null);

                Assert.Equal(5, provider.CurrentSnapshot.Profiles.Count);
                Assert.Equal("InMemory1", provider.CurrentSnapshot.Profiles[1].Name);
                Assert.True(provider.CurrentSnapshot.Profiles[1].IsInMemoryObject());
                Assert.False(provider.CurrentSnapshot.Profiles[0].IsInMemoryObject());
            }
        }
        public async Task AddOrUpdateGlobalSettingAsync_SettingExists(bool isInMemory, bool existingIsInMemory)
        {
            var moqFS = new IFileSystemMock();

            using (var provider = GetLaunchSettingsProvider(moqFS))
            {
                SetJsonSerializationProviders(provider);

                var globalSettings = ImmutableStringDictionary <object> .EmptyOrdinal
                                     .Add("test", new LaunchProfile())
                                     .Add("iisSettings", new IISSettingsData()
                {
                    DoNotPersist = existingIsInMemory
                });

                var testSettings = new Mock <ILaunchSettings>();
                testSettings.Setup(m => m.GlobalSettings).Returns(globalSettings);
                testSettings.Setup(m => m.Profiles).Returns(ImmutableList <ILaunchProfile> .Empty);

                provider.SetCurrentSnapshot(testSettings.Object);

                var newSettings = new IISSettingsData()
                {
                    WindowsAuthentication = true, DoNotPersist = isInMemory
                };

                await provider.AddOrUpdateGlobalSettingAsync("iisSettings", newSettings);

                // Check disk file was written
                Assert.Equal(!isInMemory || (isInMemory && !existingIsInMemory), moqFS.FileExists(provider.LaunchSettingsFile));

                // Check snapshot
                AssertEx.CollectionLength(provider.CurrentSnapshot.GlobalSettings, 2);
                Assert.True(provider.CurrentSnapshot.GlobalSettings.TryGetValue("iisSettings", out object updatedSettings));

                Assert.True(((IISSettingsData)updatedSettings).WindowsAuthentication);
            }
        }
Exemple #4
0
        public async Task LaunchSettingsFile_TestTimeStampFlag()
        {
            var moqFS = new IFileSystemMock();

            using (var provider = GetLaunchSettingsProvider(moqFS))
            {
                moqFS.WriteAllText(provider.LaunchSettingsFile, JsonString1);
                await provider.LaunchSettingsFile_ChangedTest();

                Assert.Equal(4, provider.CurrentSnapshot.Profiles.Count);

                // Write new file, but set the timestamp to match
                moqFS.WriteAllText(provider.LaunchSettingsFile, JsonStringWithWebSettings);
                provider.LastSettingsFileSyncTimeTest = moqFS.LastFileWriteTime(provider.LaunchSettingsFile);
                Assert.Null(provider.LaunchSettingsFile_ChangedTest());
                AssertEx.CollectionLength(provider.CurrentSnapshot.Profiles, 4);

                moqFS.WriteAllText(provider.LaunchSettingsFile, JsonStringWithWebSettings);
                await provider.LaunchSettingsFile_ChangedTest();

                AssertEx.CollectionLength(provider.CurrentSnapshot.Profiles, 2);
            }
        }
Exemple #5
0
        public async Task LaunchSettingsFile_TestIgnoreFlag()
        {
            var moqFS = new IFileSystemMock();

            using var provider = GetLaunchSettingsProvider(moqFS);
            string fileName = await provider.GetLaunchSettingsFilePathNoCacheAsync();

            // Write file and generate disk change
            moqFS.WriteAllText(fileName, JsonString1);

            // Set the ignore flag. It should be ignored.
            provider.LastSettingsFileSyncTimeTest = DateTime.MinValue;
            provider.SetIgnoreFileChanges(true);
            Assert.Equal(provider.LaunchSettingsFile_ChangedTest(), Task.CompletedTask);
            Assert.Null(provider.CurrentSnapshot);

            // Should run this time
            provider.SetIgnoreFileChanges(false);
            await provider.LaunchSettingsFile_ChangedTest();

            Assert.NotNull(provider.CurrentSnapshot);
            Assert.Equal(4, provider.CurrentSnapshot.Profiles.Count);
        }
        public async Task RemoveProfileAsync_ProfileExists(bool isInMemory)
        {
            var moqFS = new IFileSystemMock();

            using (var provider = GetLaunchSettingsProvider(moqFS))
            {
                var profiles = new List <ILaunchProfile>()
                {
                    { new LaunchProfile()
                      {
                          Name = "IIS Express", CommandName = "IISExpress", LaunchBrowser = true
                      } },
                    { new LaunchProfile()
                      {
                          Name = "test", ExecutablePath = "c:\\test\\project\\bin\\test.exe", CommandLineArgs = @"-someArg", DoNotPersist = isInMemory
                      } },
                    { new LaunchProfile()
                      {
                          Name = "bar", ExecutablePath = "c:\\test\\project\\bin\\bar.exe"
                      } }
                };

                var testSettings = new Mock <ILaunchSettings>();
                testSettings.Setup(m => m.Profiles).Returns(profiles.ToImmutableList());

                provider.SetCurrentSnapshot(testSettings.Object);

                await provider.RemoveProfileAsync("test");

                // Check disk file was written
                Assert.Equal(!isInMemory, moqFS.FileExists(provider.LaunchSettingsFile));

                // Check snapshot
                AssertEx.CollectionLength(provider.CurrentSnapshot.Profiles, 2);
                Assert.Null(provider.CurrentSnapshot.Profiles.FirstOrDefault(p => p.Name.Equals("test")));
            }
        }
Exemple #7
0
        public async Task RemoveProfileAsync_ProfileExists()
        {
            IFileSystemMock moqFS    = new IFileSystemMock();
            var             provider = GetLaunchSettingsProvider(moqFS);

            var profiles = new List <ILaunchProfile>()
            {
                { new LaunchProfile()
                  {
                      Name = "IIS Express", CommandName = "IISExpress", LaunchBrowser = true
                  } },
                { new LaunchProfile()
                  {
                      Name = "test", ExecutablePath = "c:\\test\\project\\bin\\test.exe", CommandLineArgs = @"-someArg"
                  } },
                { new LaunchProfile()
                  {
                      Name = "bar", ExecutablePath = "c:\\test\\project\\bin\\bar.exe"
                  } }
            };

            var testSettings = new Mock <ILaunchSettings>();

            testSettings.Setup(m => m.Profiles).Returns(profiles.ToImmutableList());

            provider.SetCurrentSnapshot(testSettings.Object);

            await provider.RemoveProfileAsync("test").ConfigureAwait(true);

            // Check disk file was written
            Assert.True(moqFS.FileExists(provider.LaunchSettingsFile));

            // Check snapshot
            Assert.Equal(2, provider.CurrentSnapshot.Profiles.Count);
            Assert.Null(provider.CurrentSnapshot.Profiles.FirstOrDefault(p => p.Name.Equals("test")));
        }
        private EditProjectFileCommand SetupScenario(string projectXml, string tempPath, string tempProjectFile, string projectFile,
                                                     IFileSystemMock fileSystem, ITextDocument textDoc, IVsWindowFrame frame, IExportFactory <IMsBuildModelWatcher> watcherFactory = null)
        {
            fileSystem.SetTempFile(tempPath);
            var configuredProject   = ConfiguredProjectFactory.Create();
            var unconfiguredProject = IUnconfiguredProjectFactory.Create(filePath: projectFile, configuredProject: configuredProject);
            var shellUtilities      = new TestShellUtilitiesHelper((sp, path) =>
            {
                Assert.Equal(tempProjectFile, path);
                return(Tuple.Create(IVsHierarchyFactory.Create(), (uint)0, IVsPersistDocDataFactory.ImplementAsIVsTextBuffer(), (uint)0));
            }, (sp, path, factoryGuid, logicalView) =>
            {
                Assert.Equal(tempProjectFile, path);
                Assert.Equal(XmlGuid, factoryGuid);
                Assert.Equal(Guid.Empty, logicalView);

                return(frame);
            });

            var textBuffer           = ITextBufferFactory.ImplementSnapshot(projectXml);
            var editorFactoryService = IVsEditorAdaptersFactoryServiceFactory.ImplementGetDocumentBuffer(textBuffer);

            Mock.Get(textDoc).SetupGet(t => t.TextBuffer).Returns(textBuffer);
            var textDocFactory = ITextDocumentFactoryServiceFactory.ImplementGetTextDocument(textDoc, true);

            var msbuildAccessor = IMsBuildAccessorFactory.ImplementGetProjectXmlRunLocked(projectXml, async(writeLock, callback) =>
            {
                await callback();
                Assert.True(writeLock);
            });

            var threadingService = IProjectThreadingServiceFactory.Create();

            return(CreateInstance(unconfiguredProject, true, msbuildAccessor, fileSystem, textDocFactory,
                                  editorFactoryService, threadingService, shellUtilities, watcherFactory));
        }
Exemple #9
0
        public async Task LaunchSettingsProvider_AddOrUpdateGlobalSettingAsync_SettingExists()
        {
            IFileSystemMock moqFS    = new IFileSystemMock();
            var             provider = GetLaunchSettingsProvider(moqFS);

            // Set the serialization provider
            SetJsonSerializationProviders(provider);

            var globalSettings = ImmutableDictionary <string, object> .Empty
                                 .Add("test", new LaunchProfile())
                                 .Add("iisSettings", new IISSettingsData());

            var testSettings = new Mock <ILaunchSettings>();

            testSettings.Setup(m => m.GlobalSettings).Returns(globalSettings);
            testSettings.Setup(m => m.Profiles).Returns(ImmutableList <ILaunchProfile> .Empty);

            provider.SetCurrentSnapshot(testSettings.Object);

            var newSettings = new IISSettingsData()
            {
                WindowsAuthentication = true
            };

            await provider.AddOrUpdateGlobalSettingAsync("iisSettings", newSettings).ConfigureAwait(true);

            // Check disk file was written
            Assert.True(moqFS.FileExists(provider.LaunchSettingsFile));

            // Check snapshot
            object updatedSettings;

            Assert.Equal(2, provider.CurrentSnapshot.GlobalSettings.Count);
            Assert.True(provider.CurrentSnapshot.GlobalSettings.TryGetValue("iisSettings", out updatedSettings));
            Assert.True(((IISSettingsData)updatedSettings).WindowsAuthentication);
        }
Exemple #10
0
        public async Task RemoveGlobalSettingAsync_SettingDoesntExist()
        {
            var moqFS = new IFileSystemMock();

            using var provider = GetLaunchSettingsProvider(moqFS);
            SetJsonSerializationProviders(provider);

            var globalSettings = ImmutableStringDictionary <object> .EmptyOrdinal.Add("test", new LaunchProfile());

            var testSettings = new Mock <ILaunchSettings>();

            testSettings.Setup(m => m.GlobalSettings).Returns(globalSettings);
            testSettings.Setup(m => m.Profiles).Returns(ImmutableList <ILaunchProfile> .Empty);

            provider.SetCurrentSnapshot(testSettings.Object);

            await provider.RemoveGlobalSettingAsync("iisSettings");

            // Check disk file was not written
            Assert.False(moqFS.FileExists(provider.LaunchSettingsFile));

            // Check snapshot
            Assert.Single(provider.CurrentSnapshot.GlobalSettings);
        }
Exemple #11
0
        public async Task AbstractEditProjectFileCommand_CorrectNode_CreatesWindowCorrectly()
        {
            var projectPath                = $"C:\\Project1\\Project1.{EditProjectFileCommand.Extension}";
            var tempFile                   = "C:\\Temp\\asdf.xyz";
            var tempProjFile               = $"{tempFile}.{EditProjectFileCommand.Extension}";
            var expectedCaption            = $"Project1.{EditProjectFileCommand.Extension}";
            var projectXml                 = @"<Project></Project>";
            var captionSet                 = false;
            var autoOpenSet                = false;
            var listenerSet                = false;
            IVsWindowFrameNotify2 notifier = null;

            var fileSystem = new IFileSystemMock();
            var textDoc    = ITextDocumentFactory.Create();
            var frame      = IVsWindowFrameFactory.ImplementShowAndSetProperty(VSConstants.S_OK, (property, obj) =>
            {
                switch (property)
                {
                case (int)__VSFPROPID5.VSFPROPID_OverrideCaption:
                    captionSet = true;
                    break;

                case (int)__VSFPROPID5.VSFPROPID_DontAutoOpen:
                    autoOpenSet = true;
                    break;

                case (int)__VSFPROPID.VSFPROPID_ViewHelper:
                    listenerSet = true;
                    Assert.IsAssignableFrom <IVsWindowFrameNotify2>(obj);
                    notifier = obj as IVsWindowFrameNotify2;
                    break;

                default:
                    Assert.False(true, $"Unexpected property ID {property}");
                    break;
                }

                return(VSConstants.S_OK);
            });

            var command = SetupScenario(projectXml, tempFile, tempProjFile, projectPath, expectedCaption, fileSystem, textDoc, frame);
            var tree    = ProjectTreeParser.Parse(@"
Root (flags: {ProjectRoot})
");
            var nodes   = ImmutableHashSet.Create(tree);

            // Verify the frame was setup correctly
            Assert.True(await command.TryHandleCommandAsync(nodes, CommandId, true, 0, IntPtr.Zero, IntPtr.Zero));
            Assert.Equal(projectXml, fileSystem.ReadAllText(tempProjFile));
            Mock.Get(frame).Verify(f => f.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, expectedCaption));
            Mock.Get(frame).Verify(f => f.Show());
            Assert.True(captionSet);
            Assert.True(autoOpenSet);
            Assert.True(listenerSet);
            Assert.NotNull(notifier);

            // Now see if the event correctly saved the text from the buffer into the project file
            var args = new TextDocumentFileActionEventArgs(tempProjFile, DateTime.Now, FileActionTypes.ContentSavedToDisk);

            Mock.Get(textDoc).Raise(t => t.FileActionOccurred += null, args);
            Assert.Equal(projectXml, fileSystem.ReadAllText(projectPath));

            // Finally, ensure the cleanup works as expected. We don't do anything with the passed option. The notifier
            // should remove the file temp file from the filesystem.
            Assert.Equal(VSConstants.S_OK, notifier.OnClose(0));
            Assert.False(fileSystem.FileExists(tempProjFile));
        }
Exemple #12
0
        public async Task UpdateAndSaveProfilesAsync()
        {
            var moqFS = new IFileSystemMock();

            using (var provider = GetLaunchSettingsProvider(moqFS))
            {
                var profiles = new List <ILaunchProfile>()
                {
                    { new LaunchProfile()
                      {
                          Name = "IIS Express", CommandName = "IISExpress", LaunchBrowser = true
                      } },
                    { new LaunchProfile()
                      {
                          Name = "bar", ExecutablePath = "c:\\test\\project\\bin\\test.exe", CommandLineArgs = @"-someArg"
                      } }
                };

                var testSettings = new Mock <ILaunchSettings>();
                testSettings.Setup(m => m.ActiveProfile).Returns(() => { return(profiles[0]); });
                testSettings.Setup(m => m.Profiles).Returns(() =>
                {
                    return(profiles.ToImmutableList());
                });

                testSettings.Setup(m => m.GlobalSettings).Returns(() =>
                {
                    var iisSettings = new IISSettingsData()
                    {
                        AnonymousAuthentication = false,
                        WindowsAuthentication   = true,
                        IISExpressBindingData   = new ServerBindingData()
                        {
                            ApplicationUrl = "http://localhost:12345/",
                            SSLPort        = 44301
                        }
                    };
                    return(ImmutableStringDictionary <object> .EmptyOrdinal.Add("iisSettings", iisSettings));
                });

                // Setup SCC to verify it is called before modifying the file
                var mockScc = new Mock <ISourceCodeControlIntegration>(MockBehavior.Strict);
                mockScc.Setup(m => m.CanChangeProjectFilesAsync(It.IsAny <IReadOnlyCollection <string> >())).Returns(Task.FromResult(true));
                var sccProviders = new OrderPrecedenceImportCollection <ISourceCodeControlIntegration>(ImportOrderPrecedenceComparer.PreferenceOrder.PreferredComesFirst, (UnconfiguredProject)null)
                {
                    mockScc.Object
                };
                provider.SetSourceControlProviderCollection(sccProviders);

                await provider.UpdateAndSaveSettingsAsync(testSettings.Object);

                // Check disk contents
                Assert.Equal(JsonStringWithWebSettings, moqFS.ReadAllText(provider.LaunchSettingsFile), ignoreLineEndingDifferences: true);

                // Check snapshot
                AssertEx.CollectionLength(provider.CurrentSnapshot.Profiles, 2);
                Assert.Single(provider.CurrentSnapshot.GlobalSettings);

                // Verify the activeProfile is set to the first one since no existing snapshot
                Assert.Equal("IIS Express", provider.CurrentSnapshot.ActiveProfile.Name);

                mockScc.Verify();
            }
        }