public static void BuildReleasesFile(string releasePackagesDir, IFileSystemFactory fileSystemFactory = null) { fileSystemFactory = fileSystemFactory ?? AnonFileSystem.Default; var packagesDir = fileSystemFactory.GetDirectoryInfo(releasePackagesDir); // Generate release entries for all of the local packages var entries = packagesDir.GetFiles("*.nupkg").MapReduce(x => Observable.Start(() => { using (var file = x.OpenRead()) { return(GenerateFromFile(file, x.Name)); } }, RxApp.TaskpoolScheduler)).First(); // Write the new RELEASES file to a temp file then move it into // place var tempFile = fileSystemFactory.CreateTempFile(); try { if (entries.Count > 0) { WriteReleaseFile(entries, tempFile.Item2); } } finally { tempFile.Item2.Dispose(); } var target = Path.Combine(packagesDir.FullName, "RELEASES"); if (File.Exists(target)) { File.Delete(target); } fileSystemFactory.GetFileInfo(tempFile.Item1).MoveTo(target); }
public DiagnosticController(IContentItemRepository repository, IHost host, IDefinitionManager definitions, ILinkGenerator linkGenerator, IUrlParser parser, DatabaseSection config, IFlushable flushable, IReplicationStorage repstore, IFileSystemFactory fileSystemFactory) { _repository = repository; _host = host; _definitions = definitions; _linkGenerator = linkGenerator; _parser = parser; _flushable = flushable; _tablePrefix = config.TablePrefix; _repstore = repstore; if (_forceWriteLockManager != null) { return; } // Create Force Write Lock Manager var storageConfig = (FileSystemNamespace)Enum.Parse(typeof(FileSystemNamespace), ConfigurationManager.AppSettings["AzureReplicationStorageContainerName"] ?? "ReplicationStorageDebug"); var fileSystem = fileSystemFactory.Create(storageConfig); _forceWriteLockManager = new ReplicationForceWriteLockManager(fileSystem); _writeLockManager = new ReplicationWriteLockManager(fileSystem); }
public ExportDataProcess(IExportDataProvider dataProvider, IFileSystemFactory fileSystemFactory, IVkGroupRepository vkGroupRepository, ILog log) { this.dataProvider = dataProvider; this.fileSystemFactory = fileSystemFactory; this.vkGroupRepository = vkGroupRepository; this.log = log; }
private void ConfigureServices(ServerTestsBase container, RecursiveProcessingMode processingMode, IServiceCollection services) { IFileSystemFactory fileSystemFactory = null; IPropertyStoreFactory propertyStoreFactory = null; services .AddOptions() .AddLogging() .Configure <CopyHandlerOptions>( opt => { opt.Mode = processingMode; }) .Configure <MoveHandlerOptions>( opt => { opt.Mode = processingMode; }) .AddScoped <IWebDavContext>(sp => new TestHost(sp, container.Server.BaseAddress, sp.GetRequiredService <IHttpContextAccessor>())) .AddScoped <IHttpMessageHandlerFactory>(sp => new TestHttpMessageHandlerFactory(container.Server)) .AddScoped(sp => fileSystemFactory ?? (fileSystemFactory = ActivatorUtilities.CreateInstance <InMemoryFileSystemFactory>(sp))) .AddScoped(sp => propertyStoreFactory ?? (propertyStoreFactory = ActivatorUtilities.CreateInstance <InMemoryPropertyStoreFactory>(sp))) .AddSingleton <ILockManager, InMemoryLockManager>() .AddMvcCore() .AddApplicationPart(typeof(TestWebDavController).GetTypeInfo().Assembly) .AddWebDav(); }
public DiagnosticController(IContentItemRepository repository, IHost host, IDefinitionManager definitions, ILinkGenerator linkGenerator, IUrlParser parser, DatabaseSection config, IFlushable flushable, IReplicationStorage repstore, IFileSystemFactory fileSystemFactory) { _repository = repository; _host = host; _definitions = definitions; _linkGenerator = linkGenerator; _parser = parser; _flushable = flushable; _tablePrefix = config.TablePrefix; _repstore = repstore; if (_forceWriteLockManager != null) return; // Create Force Write Lock Manager var storageConfig = (FileSystemNamespace) Enum.Parse(typeof (FileSystemNamespace), ConfigurationManager.AppSettings["AzureReplicationStorageContainerName"] ?? "ReplicationStorageDebug"); var fileSystem = fileSystemFactory.Create(storageConfig); _forceWriteLockManager = new ReplicationForceWriteLockManager(fileSystem); _writeLockManager = new ReplicationWriteLockManager(fileSystem); }
public void GlobalJsonRemover_NoJson_DoesntCrash() { UnitTestHelper.IsRunningUnitTests = true; var solution = IVsSolutionFactory.CreateWithSolutionDirectory(DirectoryInfoCallback); var dteSolution = SolutionFactory.ImplementFindProjectItem(path => { Assert.Equal(Path.Combine(Directory, "global.json"), path); return(null); }); var dte = DteFactory.ImplementSolution(() => dteSolution); var serviceProvider = IServiceProviderFactory.ImplementGetService(t => { if (typeof(SVsSolution) == t) { return(solution); } if (typeof(DTE) == t) { return(dte); } Assert.False(true); throw new InvalidOperationException(); }); var remover = new GlobalJsonRemover(serviceProvider, IFileSystemFactory.Create()); GlobalJsonRemover.Remover = remover; Assert.Equal(VSConstants.S_OK, remover.OnAfterOpenSolution(null, 0)); }
public async Task CreateFile_NotInSync(string input, string expected, bool fileExistsOnDisk, string expectedFilePath) { var inputTree = ProjectTreeParser.Parse(input); var expectedTree = ProjectTreeParser.Parse(expected); var projectTreeProvider = new ProjectTreeProvider(); var projectTree = IPhysicalProjectTreeFactory.Create(provider: projectTreeProvider, currentTree: inputTree); var sourceItemsProvider = IProjectItemProviderFactory.CreateWithAdd(inputTree); var fileSystem = IFileSystemFactory.Create(path => fileExistsOnDisk, path => { // Verify that file is created on disk. Assert.False(fileExistsOnDisk); Assert.Equal(expectedFilePath, path); return(null); }); var specialFilesManager = ISpecialFilesManagerFactory.ImplementGetFile(@"C:\Foo\Properties"); var provider = new SettingsFileSpecialFileProvider(projectTree, sourceItemsProvider, null, fileSystem, specialFilesManager); var filePath = await provider.GetFileAsync(SpecialFiles.AppSettings, SpecialFileFlags.CreateIfNotExist); Assert.Equal(expectedFilePath, filePath); AssertAreEquivalent(expectedTree, inputTree); }
public async Task Test(string input, string appManifestPropertyValue, string expectedFilePath) { var inputTree = ProjectTreeParser.Parse(input); var projectTreeProvider = IProjectTreeProviderFactory.Create(@"C:\Foo\Properties", (root, path) => { root.TryFindImmediateChild(Path.GetFileName(path), out var node); return(node); }); var projectTree = IPhysicalProjectTreeFactory.Create(currentTree: inputTree, provider: projectTreeProvider); var sourceItemsProvider = IProjectItemProviderFactory.Create(); var fileSystem = IFileSystemFactory.Create(path => true); var specialFilesManager = ISpecialFilesManagerFactory.Create(); var properties = ProjectPropertiesFactory.Create(UnconfiguredProjectFactory.Create(), new PropertyPageData { Category = ConfigurationGeneralBrowseObject.SchemaName, PropertyName = ConfigurationGeneralBrowseObject.ApplicationManifestProperty, Value = appManifestPropertyValue }); var provider = new AppManifestSpecialFileProvider(projectTree, sourceItemsProvider, null, fileSystem, specialFilesManager, properties); var filePath = await provider.GetFileAsync(SpecialFiles.AppSettings, SpecialFileFlags.CreateIfNotExist); Assert.Equal(expectedFilePath, filePath); }
public InitializeRootBehavior( IFileSystemFactory <FileSystemEntry> factory, ISystemRootManager systemRoot ) { this.factory = factory; this.systemRoot = systemRoot; }
public InstallerHookOperations(IFileSystemFactory fileSystem, string applicationName) { // XXX: ALWAYS BE LOGGING this.log = new WrappingFullLogger(new FileLogger(applicationName), typeof(InstallerHookOperations)); this.fileSystem = fileSystem; this.applicationName = applicationName; }
public UpdateRepositoryBehavior( IFileSystemFactory <FileSystemEntry> factory, ICreatedEntriesManager createdManager ) { this.createdManager = createdManager; this.factory = factory; }
public void GlobalJsonSetup_ExistingRemover_ReturnsSameRemover() { UnitTestHelper.IsRunningUnitTests = true; var remover = new GlobalJsonRemover(IServiceProviderFactory.Create(), IFileSystemFactory.Create()); GlobalJsonRemover.Remover = remover; Assert.False(new GlobalJsonRemover.GlobalJsonSetup().SetupRemoval(IVsSolutionFactory.Create(), IServiceProviderFactory.Create(), IFileSystemFactory.Create())); Assert.True(ReferenceEquals(remover, GlobalJsonRemover.Remover)); }
public void Constructor_NullProjectTreeService_ThrowsArgumentNullException() { var fileSystem = IFileSystemFactory.Create(); var sourceItemsProvider = IProjectItemProviderFactory.Create(); var specialFilesManager = ISpecialFilesManagerFactory.Create(); Assert.Throws <ArgumentNullException>("projectTree", () => { new AppSettingsSpecialFileProvider(null !, sourceItemsProvider, null, fileSystem, specialFilesManager); });
public LogFileArchiver(IFileSystemFactory fileSystemFactory, string archiveLocation, string fileSystemType) { var ipUser = IPAddress.GetCurrentMachineIp().ReverseMe() + "_" + RuntimeHelper.GetCurrentUserName().ReverseMe(); _archiveLocation = Path.Combine(archiveLocation, ipUser); _fileSystem = fileSystemFactory.GetFileSystem(fileSystemType); _lastCopyedFileName = string.Empty; Init(); EventContainer.SubscribeEvent(Events.LogFileReachedMaxLimit.ToString(), OnNewLogFileCreated); }
public void Constructor_NullSourceItemsProvider_ThrowsArgumentNullException() { var projectTree = IPhysicalProjectTreeFactory.Create(); var fileSystem = IFileSystemFactory.Create(); var specialFilesManager = ISpecialFilesManagerFactory.Create(); Assert.Throws <ArgumentNullException>("sourceItemsProvider", () => { new SettingsFileSpecialFileProvider(projectTree, null, null, fileSystem, specialFilesManager); }); }
public async Task CreateFolderAsync_CreatesFolderOnDisk() { string result = null; var project = UnconfiguredProjectFactory.Create(filePath: @"C:\Root.csproj"); var fileSystem = IFileSystemFactory.ImplementCreateDirectory((path) => { result = path; }); var storage = CreateInstance(fileSystem: fileSystem, project: project); await storage.CreateFolderAsync("Folder"); Assert.Equal(@"C:\Folder", result); }
public ReplicationManager( IPersister persister, IItemFinder finder, IReplicationStorage repstore, IFileSystemFactory fileSystemFactory, DatabaseSection dataBaseSection, ISecurityManager security ) : this(persister, finder, repstore, fileSystemFactory, dataBaseSection, security, null, null) { // needed to be able to execute N2 unit tests w/o additional dependecies }
public void NullShellUtilities_Throws() { Assert.Throws <ArgumentNullException>("shellUtilities", () => new TempFileTextBufferManager( UnconfiguredProjectFactory.Create(), IProjectXmlAccessorFactory.Create(), IVsEditorAdaptersFactoryServiceFactory.Create(), ITextDocumentFactoryServiceFactory.Create(), null, IFileSystemFactory.Create(), IProjectThreadingServiceFactory.Create(), IServiceProviderFactory.Create())); }
private PhysicalProjectTreeStorage CreateInstance(IProjectTreeService treeService = null, IProjectTreeProvider treeProvider = null, IFileSystem fileSystem = null, IFolderManager folderManager = null, UnconfiguredProject project = null) { treeService = treeService ?? IProjectTreeServiceFactory.Create(ProjectTreeParser.Parse("Root")); treeProvider = treeProvider ?? IProjectTreeProviderFactory.Create(); fileSystem = fileSystem ?? IFileSystemFactory.Create(); folderManager = folderManager ?? IFolderManagerFactory.Create(); project = project ?? UnconfiguredProjectFactory.Create(); return new PhysicalProjectTreeStorage(new Lazy<IProjectTreeService>(() => treeService), new Lazy<IProjectTreeProvider>(() => treeProvider), new Lazy<IFileSystem>(() => fileSystem), ActiveConfiguredProjectFactory.ImplementValue(() => folderManager), project); }
public async Task FindFile_NodeNotInSync(string input, bool fileExistsOnDisk, string expectedFilePath) { var inputTree = ProjectTreeParser.Parse(input); var projectTreeService = IProjectTreeServiceFactory.Create(inputTree); var sourceItemsProvider = IProjectItemProviderFactory.Create(); var fileSystem = IFileSystemFactory.Create(path => fileExistsOnDisk); var provider = new SettingsFileSpecialFileProvider(projectTreeService, sourceItemsProvider, null, fileSystem); var filePath = await provider.GetFileAsync(SpecialFiles.AppSettings, SpecialFileFlags.FullPath); Assert.Equal(expectedFilePath, filePath); }
public async Task FindFile_FromRoot(string input, string expectedFilePath) { var inputTree = ProjectTreeParser.Parse(input); var projectTreeService = IProjectTreeServiceFactory.Create(inputTree); var sourceItemsProvider = IProjectItemProviderFactory.Create(); var fileSystem = IFileSystemFactory.Create(path => true); var provider = new AppConfigFileSpecialFileProvider(projectTreeService, sourceItemsProvider, null, fileSystem); var filePath = await provider.GetFileAsync(SpecialFiles.AppConfig, SpecialFileFlags.FullPath); Assert.Equal(expectedFilePath, filePath); }
public async Task FindFile_FromAppDesignerFolder(string input, string expectedFilePath) { var inputTree = ProjectTreeParser.Parse(input); var projectTreeProvider = new ProjectTreeProvider(); var projectTree = IPhysicalProjectTreeFactory.Create(currentTree: inputTree, provider: projectTreeProvider); var sourceItemsProvider = IProjectItemProviderFactory.Create(); var fileSystem = IFileSystemFactory.Create(path => true); var specialFilesManager = ISpecialFilesManagerFactory.ImplementGetFile(@"C:\Foo\Properties"); var provider = new SettingsFileSpecialFileProvider(projectTree, sourceItemsProvider, null, fileSystem, specialFilesManager); var filePath = await provider.GetFileAsync(SpecialFiles.AppSettings, SpecialFileFlags.FullPath); Assert.Equal(expectedFilePath, filePath); }
public DotLiquidViewEngineFixture() { this.factory = A.Fake<IFileSystemFactory>(); this.engine = new DotLiquidViewEngine(this.factory); var cache = A.Fake<IViewCache>(); A.CallTo(() => cache.GetOrAdd(A<ViewLocationResult>.Ignored, A<Func<ViewLocationResult, Template>>.Ignored)) .ReturnsLazily(x => { var result = x.GetArgument<ViewLocationResult>(0); return x.GetArgument<Func<ViewLocationResult, Template>>(1).Invoke(result); }); this.renderContext = A.Fake<IRenderContext>(); A.CallTo(() => this.renderContext.ViewCache).Returns(cache); }
public DotLiquidViewEngineFixture() { this.factory = A.Fake <IFileSystemFactory>(); this.engine = new DotLiquidViewEngine(this.factory); var cache = A.Fake <IViewCache>(); A.CallTo(() => cache.GetOrAdd(A <ViewLocationResult> .Ignored, A <Func <ViewLocationResult, Template> > .Ignored)) .ReturnsLazily(x => { var result = x.GetArgument <ViewLocationResult>(0); return(x.GetArgument <Func <ViewLocationResult, Template> >(1).Invoke(result)); }); this.renderContext = A.Fake <IRenderContext>(); A.CallTo(() => this.renderContext.ViewCache).Returns(cache); }
public DotLiquidViewEngine(IFileSystemFactory fileSystem, IViewLocator viewLocator, IEnumerable <Type> filters) { DotLiquid.Liquid.UseRubyDateFormat = true; _viewLocator = viewLocator; this._fileSystem = fileSystem; // Register custom tags (Only need to do this once) Template.RegisterFilter(typeof(CommonFilters)); Template.RegisterFilter(typeof(CommerceFilters)); foreach (var filter in filters) { Template.RegisterFilter(filter); } Template.RegisterTag <Paginate>("paginate"); Template.RegisterTag <CurrentPage>("current_page"); Template.RegisterTag <Layout>("layout"); }
public DotLiquidViewEngine(IFileSystemFactory fileSystem, IViewLocator viewLocator, IEnumerable<Type> filters) { DotLiquid.Liquid.UseRubyDateFormat = true; _viewLocator = viewLocator; this._fileSystem = fileSystem; // Register custom tags (Only need to do this once) Template.RegisterFilter(typeof(CommonFilters)); Template.RegisterFilter(typeof(CommerceFilters)); foreach (var filter in filters) { Template.RegisterFilter(filter); } Template.RegisterTag<Paginate>("paginate"); Template.RegisterTag<CurrentPage>("current_page"); Template.RegisterTag<Layout>("layout"); }
private PackageRestoreDataSource CreateInstance(UnconfiguredProject?project = null, IPackageRestoreUnconfiguredInputDataSource?dataSource = null, IVsSolutionRestoreService3?solutionRestoreService = null) { project ??= UnconfiguredProjectFactory.Create(IProjectThreadingServiceFactory.Create()); dataSource ??= IPackageRestoreUnconfiguredInputDataSourceFactory.Create(); IProjectAsynchronousTasksService projectAsynchronousTasksService = IProjectAsynchronousTasksServiceFactory.Create(); solutionRestoreService ??= IVsSolutionRestoreServiceFactory.Create(); IProjectLogger logger = IProjectLoggerFactory.Create(); IFileSystem fileSystem = IFileSystemFactory.Create(); return(new PackageRestoreDataSource( project, dataSource, projectAsynchronousTasksService, solutionRestoreService, fileSystem, logger)); }
private static DotNetCoreProjectCompatibilityDetector CreateCompatibilityDetector(out IDialogServices dialogServices, string?versionDataString = null, Version?vsVersion = null, bool isSolutionOpen = false, bool hasNewProjects = false, bool usingPreviewSDK = false, bool isCapabilityMatch = true, string targetFrameworkMoniker = ".NETCoreApp,Version=v3.0") { dialogServices = IDialogServicesFactory.Create(); var additionalReference = dialogServices; var projectProperties = IProjectPropertiesFactory.CreateWithPropertyAndValue("TargetFrameworkMoniker", targetFrameworkMoniker); var propertiesProvider = IProjectPropertiesProviderFactory.Create(commonProps: projectProperties); var project = ConfiguredProjectFactory.Create(services: ConfiguredProjectServicesFactory.Create(projectPropertiesProvider: propertiesProvider)); var scope = hasNewProjects ? IProjectCapabilitiesScopeFactory.Create(new[] { ProjectCapability.DotNet, ProjectCapability.PackageReferences }) : null; var projectAccessor = new Lazy <IProjectServiceAccessor>(() => IProjectServiceAccessorFactory.Create(scope, project)); var lazyDialogServices = new Lazy <IDialogServices>(() => additionalReference); var threadHandling = new Lazy <IProjectThreadingService>(() => IProjectThreadingServiceFactory.Create(verifyOnUIThread: false)); var vsShellUtilitiesHelper = new Lazy <IVsShellUtilitiesHelper>(() => IVsShellUtilitiesHelperFactory.Create(string.Empty, vsVersion ?? new Version("16.1"))); var fileSystem = new Lazy <IFileSystem>(() => IFileSystemFactory.Create(existsFunc: x => true, readAllTextFunc: x => versionDataString ?? defaultVersionDataString)); var httpClient = new Lazy <IHttpClient>(() => IHttpClientFactory.Create(versionDataString ?? defaultVersionDataString)); var vsUIShellService = IVsServiceFactory.Create <SVsUIShell, IVsUIShell>(Mock.Of <IVsUIShell>()); var settingsManagerService = IVsServiceFactory.Create <SVsSettingsPersistenceManager, ISettingsManager>(Mock.Of <ISettingsManager>()); var vsSolutionService = IVsServiceFactory.Create <SVsSolution, IVsSolution>(IVsSolutionFactory.CreateWithAdviseUnadviseSolutionEvents(1, isFullyLoaded: isSolutionOpen)); var vsAppIdService = IVsServiceFactory.Create <SVsAppId, IVsAppId>(Mock.Of <IVsAppId>()); var vsShellService = IVsServiceFactory.Create <SVsShell, IVsShell>(Mock.Of <IVsShell>()); var compatibilityDetector = new TestDotNetCoreProjectCompatibilityDetector(projectAccessor, lazyDialogServices, threadHandling, vsShellUtilitiesHelper, fileSystem, httpClient, vsUIShellService, settingsManagerService, vsSolutionService, vsAppIdService, vsShellService, hasNewProjects, usingPreviewSDK, isCapabilityMatch); return(compatibilityDetector); }
public UpdateManager(string urlOrPath, string applicationName, FrameworkVersion appFrameworkVersion, string rootDirectory = null, IFileSystemFactory fileSystem = null, IUrlDownloader urlDownloader = null) { Contract.Requires(!String.IsNullOrEmpty(urlOrPath)); Contract.Requires(!String.IsNullOrEmpty(applicationName)); updateUrlOrPath = urlOrPath; this.applicationName = applicationName; this.appFrameworkVersion = appFrameworkVersion; this.rootAppDirectory = Path.Combine(rootDirectory ?? getLocalAppDataDirectory(), applicationName); this.fileSystem = fileSystem ?? AnonFileSystem.Default; this.urlDownloader = urlDownloader ?? new DirectUrlDownloader(fileSystem); }
public async Task GetFile_WhenNoAppDesigner_ReturnsPathUnderProjectRoot() { var inputTree = ProjectTreeParser.Parse(@" Root (flags: {ProjectRoot}), FilePath: ""C:\Foo\testing.csproj"" Properties (flags: {Folder}), FilePath: ""C:\Foo\Properties"" Settings.settings, FilePath: ""C:\Foo\Properties\Settings.settings"""); var projectTreeProvider = new ProjectTreeProvider(); var projectTree = IPhysicalProjectTreeFactory.Create(currentTree: inputTree, provider: projectTreeProvider); var sourceItemsProvider = IProjectItemProviderFactory.Create(); var fileSystem = IFileSystemFactory.Create(path => true); var specialFilesManager = ISpecialFilesManagerFactory.ImplementGetFile(null); // No AppDesigner var provider = new SettingsFileSpecialFileProvider(projectTree, sourceItemsProvider, null, fileSystem, specialFilesManager); var filePath = await provider.GetFileAsync(SpecialFiles.AppSettings, SpecialFileFlags.FullPath); Assert.Equal(@"C:\Foo\Settings.settings", filePath); }
public ReplicationStorageFileSystemN2(ContentActivator activator, IFileSystemFactory fsfactory, IDefinitionManager definitions, IPersister persister) { _activator = activator; _definitions = definitions; _persister = persister; string value = (ConfigurationManager.AppSettings["XmlReplication"] ?? "false").ToLowerInvariant(); if (value.Equals("slave") || value.Equals("master")) { // only initialize if replication is active var storageConfig = (FileSystemNamespace) Enum.Parse(typeof (FileSystemNamespace), ConfigurationManager.AppSettings["AzureReplicationStorageContainerName"] ?? "ReplicationStorageDebug"); _fs = fsfactory.Create(storageConfig); if (_fs.GetType().Name.Contains("Azure")) _path = "/_Xml_Sync_"; // TODO maybe should add TablePrefix? } }
public void GlobalJsonRemover_AfterRemoval_UnadvisesEvents() { UnitTestHelper.IsRunningUnitTests = true; var globalJsonPath = Path.Combine(Directory, "global.json"); var solution = IVsSolutionFactory.CreateWithSolutionDirectory(DirectoryInfoCallback); var projectItem = ProjectItemFactory.Create(); var dteSolution = SolutionFactory.ImplementFindProjectItem(path => { Assert.Equal(globalJsonPath, path); return(projectItem); }); var dte = DteFactory.ImplementSolution(() => dteSolution); var serviceProvider = IServiceProviderFactory.ImplementGetService(t => { if (typeof(SVsSolution) == t) { return(solution); } if (typeof(DTE) == t) { return(dte); } Assert.False(true); throw new InvalidOperationException(); }); var fileSystem = IFileSystemFactory.Create(); fileSystem.Create(globalJsonPath); var remover = new GlobalJsonRemover(serviceProvider, fileSystem) { SolutionCookie = 1234 }; GlobalJsonRemover.Remover = remover; Assert.Equal(VSConstants.S_OK, remover.OnAfterOpenSolution(null, 0)); Mock.Get(solution).Verify(s => s.UnadviseSolutionEvents(1234), Times.Once); }
private static PackageRestoreDataSource CreateInstance(UnconfiguredProject?project = null, IPackageRestoreUnconfiguredInputDataSource?dataSource = null, IVsSolutionRestoreService3?solutionRestoreService = null) { project ??= UnconfiguredProjectFactory.Create(IProjectThreadingServiceFactory.Create()); dataSource ??= IPackageRestoreUnconfiguredInputDataSourceFactory.Create(); IProjectAsynchronousTasksService projectAsynchronousTasksService = IProjectAsynchronousTasksServiceFactory.Create(); solutionRestoreService ??= IVsSolutionRestoreServiceFactory.Create(); IProjectDiagnosticOutputService logger = IProjectDiagnosticOutputServiceFactory.Create(); IFileSystem fileSystem = IFileSystemFactory.Create(); var projectDependentFileChangeNotificationService = IProjectDependentFileChangeNotificationServiceFactory.Create(); return(new PackageRestoreDataSource( project, dataSource, projectAsynchronousTasksService, solutionRestoreService, fileSystem, logger, projectDependentFileChangeNotificationService)); }
public async Task CreateFile_InRootFolder(string input, string expected, string expectedFilePath) { var inputTree = ProjectTreeParser.Parse(input); var expectedTree = ProjectTreeParser.Parse(expected); var projectTreeService = IProjectTreeServiceFactory.Create(inputTree); var sourceItemsProvider = IProjectItemProviderFactory.CreateWithAdd(inputTree); var fileSystem = IFileSystemFactory.Create(path => false, path => { // Verify that file is created on disk. Assert.Equal(expectedFilePath, path); return(null); }); var provider = new AppConfigFileSpecialFileProvider(projectTreeService, sourceItemsProvider, null, fileSystem); var filePath = await provider.GetFileAsync(SpecialFiles.AppConfig, SpecialFileFlags.CreateIfNotExist); Assert.Equal(expectedFilePath, filePath); AssertAreEquivalent(expectedTree, inputTree); }
public UpdateManager(string urlOrPath, string applicationName, FrameworkVersion appFrameworkVersion, string rootDirectory = null, IFileSystemFactory fileSystem = null, IUrlDownloader urlDownloader = null) { Contract.Requires(!String.IsNullOrEmpty(urlOrPath)); Contract.Requires(!String.IsNullOrEmpty(applicationName)); log = LogManager.GetLogger<UpdateManager>(); updateUrlOrPath = urlOrPath; this.applicationName = applicationName; this.appFrameworkVersion = appFrameworkVersion; this.rootAppDirectory = Path.Combine(rootDirectory ?? getLocalAppDataDirectory(), applicationName); this.fileSystem = fileSystem ?? AnonFileSystem.Default; this.urlDownloader = urlDownloader ?? new DirectUrlDownloader(fileSystem); }
public DotLiquidViewEngineFixture() { this.environment = new DefaultNancyEnvironment(); this.environment.AddValue(ViewConfiguration.Default); this.factory = A.Fake<IFileSystemFactory>(); this.engine = new DotLiquidViewEngine(this.factory, new RubyNamingConvention()); this.engineCSharp = new DotLiquidViewEngine(this.factory, new CSharpNamingConvention()); var cache = A.Fake<IViewCache>(); A.CallTo(() => cache.GetOrAdd(A<ViewLocationResult>.Ignored, A<Func<ViewLocationResult, Template>>.Ignored)) .ReturnsLazily(x => { var result = x.GetArgument<ViewLocationResult>(0); return x.GetArgument<Func<ViewLocationResult, Template>>(1).Invoke(result); }); var context = new NancyContext(); this.renderContext = A.Fake<IRenderContext>(); A.CallTo(() => this.renderContext.ViewCache).Returns(cache); A.CallTo(() => this.renderContext.Context).Returns(context); }
public UpdateManager(string urlOrPath, string applicationName, FrameworkVersion appFrameworkVersion, string rootDirectory = null, IFileSystemFactory fileSystem = null, IUrlDownloader urlDownloader = null) { Contract.Requires(!String.IsNullOrEmpty(urlOrPath)); Contract.Requires(!String.IsNullOrEmpty(applicationName)); // XXX: ALWAYS BE LOGGING log = new WrappingFullLogger(new FileLogger(applicationName), typeof(UpdateManager)); updateUrlOrPath = urlOrPath; this.applicationName = applicationName; this.appFrameworkVersion = appFrameworkVersion; this.rootAppDirectory = Path.Combine(rootDirectory ?? getLocalAppDataDirectory(), applicationName); this.fileSystem = fileSystem ?? AnonFileSystem.Default; this.urlDownloader = urlDownloader ?? new DirectUrlDownloader(fileSystem); }
/// <summary> /// Initializes a new instance of the <see cref="DotLiquidViewEngine"/> class. /// </summary> /// <param name="fileSystemFactory">Factory used to retrieve the <see cref="IFileSystem"/> instance that should be used by the engine.</param> /// <param name="namingConvention">The naming convention used by filters and DotLiquid's <c>Drop</c>s</param> public DotLiquidViewEngine(IFileSystemFactory fileSystemFactory, INamingConvention namingConvention) { this.fileSystemFactory = fileSystemFactory; this.namingConvention = namingConvention; }
public ReplicationManager( IPersister persister, IItemFinder finder, IReplicationStorage repstore, IFileSystemFactory fileSystemFactory, DatabaseSection dataBaseSection, ISecurityManager security, IIndexer indexer, // optional IFlushable flushable // optional ) { _repstore = repstore; _security = security; _persister = persister; _finder = finder; _indexer = indexer; _flushable = flushable; // detect sync direction from Database Type and double check via config string value = ConfigurationManager.AppSettings["XmlReplication"] ?? "false"; IsSlave = value.Equals("Slave", StringComparison.InvariantCultureIgnoreCase) & (dataBaseSection.Flavour == DatabaseFlavour.Xml); IsMaster = value.Equals("Master", StringComparison.InvariantCultureIgnoreCase) & !IsSlave; if (IsMaster || IsSlave) { // only initialize if replication is active var storageConfig = (FileSystemNamespace) Enum.Parse(typeof (FileSystemNamespace), ConfigurationManager.AppSettings["AzureReplicationStorageContainerName"] ?? "ReplicationStorageDebug"); _fileSystem = fileSystemFactory.Create(storageConfig); // constructing these dependencies to ensure same filesystem and simplify construction _replicationWriteLockManager = new ReplicationWriteLockManager(_fileSystem); _replicationReadLockManager = new ReplicationReadLockManager(_fileSystem); } _replicationLogPath = "/_Xml_Sync_Log"; }
public InstallerHookOperations(IRxUIFullLogger log, IFileSystemFactory fileSystem, string applicationName) { this.log = log; this.fileSystem = fileSystem; this.applicationName = applicationName; }
public static void BuildReleasesFile(string releasePackagesDir, IFileSystemFactory fileSystemFactory = null) { fileSystemFactory = fileSystemFactory ?? AnonFileSystem.Default; var packagesDir = fileSystemFactory.GetDirectoryInfo(releasePackagesDir); // Generate release entries for all of the local packages var entries = packagesDir.GetFiles("*.nupkg").MapReduce(x => Observable.Start(() => { using (var file = x.OpenRead()) { return GenerateFromFile(file, x.Name); } }, RxApp.TaskpoolScheduler)).First(); // Write the new RELEASES file to a temp file then move it into // place var tempFile = fileSystemFactory.CreateTempFile(); try { if (entries.Count > 0) WriteReleaseFile(entries, tempFile.Item2); } finally { tempFile.Item2.Dispose(); } var target = Path.Combine(packagesDir.FullName, "RELEASES"); if (File.Exists(target)) { File.Delete(target); } fileSystemFactory.GetFileInfo(tempFile.Item1).MoveTo(target); }
public void RegisterFileSystemFactory(IFileSystemFactory fileSystemFactory) { if (Factories.ContainsKey(fileSystemFactory.Type)) throw new Exception("There is already a FileSystemFactory with type '" + fileSystemFactory.Type + "' registered."); Factories.Add(fileSystemFactory.Type, fileSystemFactory); }
/// <summary> /// Initializes a new instance of the <see cref="DotLiquidViewEngine"/> class. /// </summary> /// <param name="fileSystemFactory">Factory used to retrieve the <see cref="IFileSystem"/> instance that should be used by the engine.</param> public DotLiquidViewEngine(IFileSystemFactory fileSystemFactory) { this.fileSystemFactory = fileSystemFactory; }
public WixUiBootstrapper(IWiXEvents wixEvents, TinyIoCContainer testKernel = null, IRoutingState router = null, IFileSystemFactory fileSystem = null, string currentAssemblyDir = null) { Kernel = testKernel ?? createDefaultKernel(); this.fileSystem = fileSystem ?? AnonFileSystem.Default; this.currentAssemblyDir = currentAssemblyDir ?? Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); RxApp.ConfigureServiceLocator( (type, contract) => String.IsNullOrEmpty(contract) ? Kernel.Resolve(type) : Kernel.Resolve(type, contract), (type, contract) => Kernel.ResolveAll(type, true), (c, t, s) => { if (String.IsNullOrEmpty(s)) { Kernel.Register(t, c, Guid.NewGuid().ToString()); } else { Kernel.Register(t, c, s); } }); RxRouting.ViewModelToViewFunc = findViewClassNameForViewModelName; Kernel.Register<IWixUiBootstrapper>(this); Kernel.Register<IScreen>(this); Kernel.Register(wixEvents); Router = router ?? new RoutingState(); WiXEvents = wixEvents; _BundledRelease = new Lazy<ReleaseEntry>(readBundledReleasesFile); registerExtensionDlls(Kernel); UserError.RegisterHandler(ex => { if (wixEvents.DisplayMode != Display.Full) { this.Log().Error(ex.ErrorMessage); wixEvents.ShouldQuit(); } var errorVm = RxApp.GetService<IErrorViewModel>(); errorVm.Error = ex; RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(errorVm)); return Observable.Return(RecoveryOptionResult.CancelOperation); }); bundledPackageMetadata = new Lazy<IPackage>(openBundledPackage); wixEvents.DetectPackageCompleteObs.Subscribe(eventArgs => { var error = convertHResultToError(eventArgs.Status); if (error != null) { UserError.Throw(error); return; } if (wixEvents.Action == LaunchAction.Uninstall) { var uninstallVm = RxApp.GetService<IUninstallingViewModel>(); Router.Navigate.Execute(uninstallVm); wixEvents.Engine.Plan(LaunchAction.Uninstall); return; } // TODO: If the app is already installed, run it and bail // If Display is silent, we should just exit here. if (wixEvents.Action == LaunchAction.Install) { if (wixEvents.DisplayMode != Display.Full) { wixEvents.Engine.Plan(LaunchAction.Install); return; } var welcomeVm = RxApp.GetService<IWelcomeViewModel>(); welcomeVm.PackageMetadata = bundledPackageMetadata.Value; welcomeVm.ShouldProceed.Subscribe(_ => wixEvents.Engine.Plan(LaunchAction.Install)); // NB: WiX runs a "Main thread" that all of these events // come back on, and a "UI thread" where it actually runs // the WPF window. Gotta proxy to the UI thread. RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(welcomeVm)); } }); var executablesToStart = Enumerable.Empty<string>(); wixEvents.PlanCompleteObs.Subscribe(eventArgs => { var installManager = new InstallManager(BundledRelease); var error = convertHResultToError(eventArgs.Status); if (error != null) { UserError.Throw(error); return; } if (wixEvents.Action == LaunchAction.Uninstall) { installManager.ExecuteUninstall().Subscribe( _ => wixEvents.Engine.Apply(wixEvents.MainWindowHwnd), ex => UserError.Throw(new UserError("Failed to uninstall", ex.Message, innerException: ex))); return; } IObserver<int> progress = null; if (wixEvents.DisplayMode == Display.Full) { var installingVm = RxApp.GetService<IInstallingViewModel>(); progress = installingVm.ProgressValue; installingVm.PackageMetadata = bundledPackageMetadata.Value; RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(installingVm)); } installManager.ExecuteInstall(this.currentAssemblyDir, bundledPackageMetadata.Value, progress).Subscribe( toStart => { executablesToStart = toStart ?? executablesToStart; wixEvents.Engine.Apply(wixEvents.MainWindowHwnd); }, ex => UserError.Throw("Failed to install application", ex)); }); wixEvents.ApplyCompleteObs.Subscribe(eventArgs => { var error = convertHResultToError(eventArgs.Status); if (error != null) { UserError.Throw(error); return; } if (wixEvents.DisplayMode == Display.Full && wixEvents.Action == LaunchAction.Install) { foreach (var path in executablesToStart) { Process.Start(path); } } wixEvents.ShouldQuit(); }); wixEvents.ErrorObs.Subscribe(eventArgs => UserError.Throw("An installation error has occurred: " + eventArgs.ErrorMessage)); wixEvents.Engine.Detect(); }
public WixUiBootstrapper( IWiXEvents wixEvents, TinyIoCContainer testKernel = null, IRoutingState router = null, IFileSystemFactory fileSystem = null, string currentAssemblyDir = null, string targetRootDirectory = null) { Kernel = testKernel ?? createDefaultKernel(); this.fileSystem = fileSystem ?? AnonFileSystem.Default; this.currentAssemblyDir = currentAssemblyDir ?? Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); RxApp.ConfigureServiceLocator( (type, contract) => { this.Log().Debug("Resolving type '{0}' with contract '{1}'", type, contract); return String.IsNullOrEmpty(contract) ? Kernel.Resolve(type) : Kernel.Resolve(type, contract); }, (type, contract) => Kernel.ResolveAll(type, true), (c, t, s) => { this.Log().Debug("Registering type '{0}' for interface '{1}' and contract '{2}'", c, t, s); if (String.IsNullOrEmpty(s)) { Kernel.Register(t, c, Guid.NewGuid().ToString()); } else { Kernel.Register(t, c, s); } }); RxRouting.ViewModelToViewFunc = findViewClassNameForViewModelName; Kernel.Register<IWixUiBootstrapper>(this); Kernel.Register<IScreen>(this); Kernel.Register(wixEvents); Router = router ?? new RoutingState(); WiXEvents = wixEvents; _BundledRelease = new Lazy<ReleaseEntry>(readBundledReleasesFile); registerExtensionDlls(Kernel); UserError.RegisterHandler(ex => { this.Log().ErrorException("Something unexpected happened", ex.InnerException); if (wixEvents.DisplayMode != Display.Full) { this.Log().Error(ex.ErrorMessage); wixEvents.ShouldQuit(); } var errorVm = RxApp.GetService<IErrorViewModel>(); errorVm.Error = ex; errorVm.Shutdown.Subscribe(_ => wixEvents.ShouldQuit()); errorVm.OpenLogsFolder.Subscribe(_ => openLogsFolder()); RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(errorVm)); return Observable.Return(RecoveryOptionResult.CancelOperation); }); bundledPackageMetadata = new Lazy<IPackage>(openBundledPackage); wixEvents.DetectPackageCompleteObs.Subscribe(eventArgs => { this.Log().Info("DetectPackageCompleteObs: got id: '{0}', state: '{1}', status: '{2}'", eventArgs.PackageId, eventArgs.State, eventArgs.Status); var error = convertHResultToError(eventArgs.Status); if (error != null) { UserError.Throw(error); return; } // we now have multiple applications in the chain // only run this code after the last entry in the chain if (eventArgs.PackageId != "UserApplicationId") return; if (wixEvents.Action == LaunchAction.Uninstall) { if (wixEvents.DisplayMode != Display.Full) { this.Log().Info("Squirrel is doing a silent uninstall! Sneaky!"); wixEvents.Engine.Plan(LaunchAction.Uninstall); return; } this.Log().Info("Squirrel is doing an uninstall! Sadface!"); var uninstallVm = RxApp.GetService<IUninstallingViewModel>(); Router.Navigate.Execute(uninstallVm); wixEvents.Engine.Plan(LaunchAction.Uninstall); return; } // TODO: If the app is already installed, run it and bail // If Display is silent, we should just exit here. if (wixEvents.Action == LaunchAction.Install) { if (wixEvents.DisplayMode != Display.Full) { this.Log().Info("Squirrel is doing a silent install! Sneaky!"); wixEvents.Engine.Plan(LaunchAction.Install); return; } this.Log().Info("We are doing an UI install! Huzzah!"); var welcomeVm = RxApp.GetService<IWelcomeViewModel>(); welcomeVm.PackageMetadata = bundledPackageMetadata.Value; welcomeVm.ShouldProceed.Subscribe(_ => wixEvents.Engine.Plan(LaunchAction.Install)); // NB: WiX runs a "Main thread" that all of these events // come back on, and a "UI thread" where it actually runs // the WPF window. Gotta proxy to the UI thread. RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(welcomeVm)); } }); var executablesToStart = Enumerable.Empty<string>(); wixEvents.PlanCompleteObs.Subscribe(eventArgs => { this.Log().Info("PlanCompleteObs: got status: '{0}'", eventArgs.Status); var installManager = new InstallManager(BundledRelease, targetRootDirectory); var error = convertHResultToError(eventArgs.Status); if (error != null) { UserError.Throw(error); return; } if (wixEvents.Action == LaunchAction.Uninstall) { var task = installManager.ExecuteUninstall(BundledRelease.Version); task.Subscribe( _ => wixEvents.Engine.Apply(wixEvents.MainWindowHwnd), ex => UserError.Throw(new UserError("Failed to uninstall", ex.Message, innerException: ex))); // the installer can close before the uninstall is done // which means the UpdateManager is not disposed correctly // which means an error is thrown in the destructor // // let's wait for it to finish // // oh, and .Wait() is unnecesary here // because the subscriber handles an exception var result = task.FirstOrDefault(); return; } IObserver<int> progress = null; if (wixEvents.DisplayMode == Display.Full) { var installingVm = RxApp.GetService<IInstallingViewModel>(); progress = installingVm.ProgressValue; installingVm.PackageMetadata = bundledPackageMetadata.Value; RxApp.DeferredScheduler.Schedule(() => Router.Navigate.Execute(installingVm)); } installManager.ExecuteInstall(this.currentAssemblyDir, bundledPackageMetadata.Value, progress).Subscribe( toStart => { executablesToStart = toStart ?? executablesToStart; wixEvents.Engine.Apply(wixEvents.MainWindowHwnd); }, ex => UserError.Throw("Failed to install application", ex)); }); wixEvents.ApplyCompleteObs.Subscribe(eventArgs => { this.Log().Info("ApplyCompleteObs: got restart: '{0}', result: '{1}', status: '{2}'", eventArgs.Restart, eventArgs.Result, eventArgs.Status); var error = convertHResultToError(eventArgs.Status); if (error != null) { UserError.Throw(error); return; } if (wixEvents.DisplayMode == Display.Full && wixEvents.Action == LaunchAction.Install) { var processFactory = Kernel.Resolve<IProcessFactory>(); foreach (var path in executablesToStart) { processFactory.Start(path); } } wixEvents.ShouldQuit(); }); wixEvents.ErrorObs.Subscribe( eventArgs => { this.Log().Info("ErrorObs: got id: '{0}', result: '{1}', code: '{2}'", eventArgs.PackageId, eventArgs.Result, eventArgs.ErrorCode); UserError.Throw("An installation error has occurred: " + eventArgs.ErrorMessage); }); wixEvents.Engine.Detect(); }
public DirectUrlDownloader(IFileSystemFactory fileSystem) { this.fileSystem = fileSystem ?? AnonFileSystem.Default; }