public void CannotSwitchSpaceContextWhenTheRepositoryScopeIsSpecified(RepositoryScope scope) { var repository = Substitute.For <IOctopusAsyncRepository>(); repository.Scope.Returns(scope); repository.LoadRootDocument().Returns(GetRootResource()); ITeamsRepository teamRepo = new TeamsRepository(repository); Action switchContext = () => teamRepo.UsingContext(SpaceContext.AllSpaces()); switchContext.ShouldThrow <SpaceContextSwitchException>(); }
public async Task SpaceScoped_SingleSpaceContextShouldEnrichSpaceId(string spaceId) { var client = SetupAsyncClient(); await client.Create(Arg.Any <string>(), Arg.Do <ProjectGroupResource>(t => { t.SpaceId.Should().Be(spaceId); })); var repo = new ProjectGroupRepository(new OctopusAsyncRepository(client, RepositoryScope.ForSpace(CreateSpaceResource(spaceId)))); var _ = await repo.Create(new ProjectGroupResource { Name = "Test" }).ConfigureAwait(false); }
private static async Task UploadPackagesAsync() { try { var client = FeedzClient.Create(_apiKey); RepositoryScope repositoryScope = client.ScopeToRepository(_organization, _repository); // Load *ALL* the New Packages var files = Directory.GetFiles(_path); var numberOfFiles = files.Count(); var counterFiles = 1; Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine($"{numberOfFiles} (*.nupkg) file(s) found!"); Console.WriteLine(); foreach (var file in files) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine($"[{counterFiles}] Uploading {file}..."); try { await repositoryScope.PackageFeed.Upload(file); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"{file} correctly uploaded!"); Console.WriteLine(); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.Message); if (ex.Message == "Forbidden") { Console.WriteLine("Please, check the API Key to access and write into your own repo"); } Console.WriteLine(); Console.ResetColor(); } counterFiles += 1; } Console.ResetColor(); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("An error ocurred!"); Console.WriteLine(ex.Message); Console.WriteLine(); Console.ResetColor(); } }
public async Task NonSingleSpaceContextShouldNotChangeExistingSpaceId(string spaceIdsToUse, bool includeSystem) { var spaceIds = spaceIdsToUse.Split(','); var client = SetupAsyncClient(); await client.Create(Arg.Any <string>(), Arg.Do <TeamResource>(t => t.SpaceId.Should().Be("Spaces-4"))).ConfigureAwait(false); var teamRepo = new TeamsRepository(new OctopusAsyncRepository(client, RepositoryScope.Unspecified())); var multiScoped = teamRepo.UsingContext(SpaceContext.SpecificSpacesAndSystem(spaceIds.Select(CreateSpaceResource))); var _ = await multiScoped.Create(new TeamResource() { Name = "Test", SpaceId = "Spaces-4" }).ConfigureAwait(false); }
public async Task MixedScoped_SingleSpaceContextShouldEnrichSpaceId(string spaceId) { var client = SetupAsyncClient(); await client.Create(Arg.Any <string>(), Arg.Do <TeamResource>(t => { t.SpaceId.Should().Be(spaceId); })).ConfigureAwait(false); var teamRepo = new TeamsRepository(new OctopusAsyncRepository(client, RepositoryScope.ForSpace(CreateSpaceResource(spaceId)))); var created = await teamRepo.Create(new TeamResource() { Name = "Test" }).ConfigureAwait(false); }
public async Task NonSingleSpaceContextShouldNotEnrichSpaceId(string includingSpaceId, bool includeSystem) { var client = SetupAsyncClient(); await client.Create(Arg.Any <string>(), Arg.Do <TeamResource>(t => { t.SpaceId.Should().BeNullOrEmpty(); })).ConfigureAwait(false); var includingSpaceContext = includeSystem ? SpaceContext.SpecificSpaceAndSystem(CreateSpaceResource(includingSpaceId)) : SpaceContext.SpecificSpace(CreateSpaceResource(includingSpaceId)); var teamRepo = new TeamsRepository(new OctopusAsyncRepository(client, RepositoryScope.Unspecified())); var multiScoped = teamRepo.UsingContext(includingSpaceContext); var _ = await multiScoped.Create(new TeamResource() { Name = "Test" }).ConfigureAwait(false); }
public ICollection <IRepository> TryGetEnabledRepos(RepositoryScope scope) { var repos = new List <IRepository>(); if ((scope & RepositoryScope.Cache) == RepositoryScope.Cache) { repos.AddRange(GetCacheRepos()); } if ((scope & RepositoryScope.Standard) == RepositoryScope.Standard) { repos.AddRange(GetStandardRepos()); } return(repos); }
public async Task Can_get_by_id_not_found() { // Arrange const int notFoundId = 11; Preconditions.EnsureRandomFake(); // Act FakeAggregateRoot actual; using (RepositoryScope scope = CreateScope()) { actual = await scope .Repository .GetByIdAsync( notFoundId, _cancellationToken); } // Assert actual.ShouldBeNull(); }
public async Task Can_get_all() { // Arrange Preconditions.EnsureFakes(10); List <FakeAggregateRoot> expected = DbContext .FakeAggregateRoots .ToList(); // Act List <FakeAggregateRoot> actual; using (RepositoryScope scope = CreateScope()) { actual = (await scope.Repository.GetAllAsync(_cancellationToken)) ?.ToList(); } // Assert actual.ShouldNotBeNull(); actual.Count.ShouldBe(expected.Count); actual.SequenceEqual(expected).ShouldBeTrue(); }
public async Task Can_add() { // Arrange var newFakeAggregateRoot = new FakeAggregateRoot("expectedName"); // Act int actual; using (RepositoryScope scope = CreateScope()) { actual = await scope .Repository .AddAsync(newFakeAggregateRoot, _cancellationToken); } // Assert FakeAggregateRoot expected = await DbContext .FakeAggregateRoots .FirstAsync(f => f.Name == newFakeAggregateRoot.Name); actual.ShouldBe(expected.Id); }
public override async Task Execute(string[] commandLineArguments) { var remainingArguments = Options.Parse(commandLineArguments); if (printHelp) { GetHelp(Console.Out, commandLineArguments); return; } if (remainingArguments.Count > 0) { throw new CommandException("Unrecognized command arguments: " + string.Join(", ", remainingArguments)); } if (string.IsNullOrWhiteSpace(ServerBaseUrl)) { throw new CommandException("Please specify the Octopus Server URL using --server=http://your-server/. " + $"The Octopus Server URL can also be set in the {ServerUrlEnvVar} environment variable."); } if (!string.IsNullOrWhiteSpace(ApiKey) && !string.IsNullOrWhiteSpace(Username)) { throw new CommandException("Please provide an API Key OR a username and password, not both. " + "These values may have been passed in as command line arguments, or may have been set in the " + $"{ApiKeyEnvVar} and {UsernameEnvVar} environment variables."); } if (string.IsNullOrWhiteSpace(ApiKey) && string.IsNullOrWhiteSpace(Username)) { throw new CommandException("Please specify your API key using --apiKey=ABCDEF123456789 OR a username and password. " + $"The API key can also be set in the {ApiKeyEnvVar} environment variable, " + $"while the username and password can be set in the {UsernameEnvVar} and {PasswordEnvVar} " + "environment variables respectively. Learn more at: https://github.com/OctopusDeploy/Octopus-Tools"); } var endpoint = string.IsNullOrWhiteSpace(ApiKey) ? new OctopusServerEndpoint(ServerBaseUrl) : new OctopusServerEndpoint(ServerBaseUrl, ApiKey); #if NETFRAMEWORK /* * There may be a delay between the completion of a large file upload and when Octopus responds * to finish the HTTP connection. This delay can be several minutes. During this time, no traffic is * sent, and some networking infrastructure will close the connection. For example, Azure VMs will * close idle connections after 4 minutes, and AWS VMs will close them after 350 seconds. The * TCP keepalive option will ensure that the connection is not idle at the end of the file upload. * * This is the bug that explains why this doesn't work with .NET Core: * https://github.com/dotnet/corefx/issues/26013 */ if (keepAlive > 0) { ServicePointManager.FindServicePoint(new Uri(ServerBaseUrl)).SetTcpKeepAlive(true, keepAlive, keepAlive); } #endif #if HTTP_CLIENT_SUPPORTS_SSL_OPTIONS clientOptions.IgnoreSslErrors = ignoreSslErrors; #else ServicePointManager.ServerCertificateValidationCallback = ServerCertificateValidationCallback; #endif commandOutputProvider.PrintMessages = OutputFormat == OutputFormat.Default || enableDebugging; CliSerilogLogProvider.PrintMessages = commandOutputProvider.PrintMessages; commandOutputProvider.PrintHeader(); var client = await clientFactory.CreateAsyncClient(endpoint, clientOptions).ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(Username)) { await client.Repository.Users.SignIn(Username, Password).ConfigureAwait(false); } var serverHasSpaces = await client.ForSystem().HasLink("Spaces").ConfigureAwait(false); if (!string.IsNullOrEmpty(spaceNameOrId)) { if (!serverHasSpaces) { throw new CommandException($"The server {endpoint.OctopusServer} has no spaces. Try invoking {AssemblyExtensions.GetExecutableName()} without specifying the space name as an argument"); } var space = await client.ForSystem().Spaces.FindByNameOrIdOrFail(spaceNameOrId).ConfigureAwait(false); Repository = repositoryFactory.CreateRepository(client, RepositoryScope.ForSpace(space)); commandOutputProvider.Debug("Space name specified, process is now running in the context of space: {space:l}", space.Name); } else { Repository = repositoryFactory.CreateRepository(client); if (!serverHasSpaces) { commandOutputProvider.Debug("Process will run in backwards compatible mode for older versions of Octopus Server"); } else { var defaultSpace = await client.ForSystem() .Spaces.FindOne(space => space.IsDefault) .ConfigureAwait(false); if (defaultSpace == null) { throw new CommandException("Octopus Server does not have a default space enabled, hence you need to specify the space name as an argument"); } commandOutputProvider.Debug("Space name unspecified, process will run in the default space context"); } } RepositoryCommonQueries = new OctopusRepositoryCommonQueries(Repository, commandOutputProvider); if (enableDebugging) { Repository.Client.SendingOctopusRequest += request => commandOutputProvider.Debug("{Method:l} {Uri:l}", request.Method, request.Uri); } commandOutputProvider.Debug("Handshaking with Octopus Server: {Url:l}", ServerBaseUrl); var root = await Repository.LoadRootDocument().ConfigureAwait(false); commandOutputProvider.Debug("Handshake successful. Octopus version: {Version:l}; API version: {ApiVersion:l}", root.Version, root.ApiVersion); var user = await Repository.Users.GetCurrent().ConfigureAwait(false); if (user != null) { if (string.IsNullOrEmpty(user.EmailAddress)) { commandOutputProvider.Debug("Authenticated as: {Name:l} {IsService:l}", user.DisplayName, user.IsService ? "(a service account)" : ""); } else { commandOutputProvider.Debug("Authenticated as: {Name:l} <{EmailAddress:l}> {IsService:l}", user.DisplayName, user.EmailAddress, user.IsService ? "(a service account)" : ""); } } await ValidateParameters().ConfigureAwait(false); await Execute().ConfigureAwait(false); }
/// <summary> /// Ricerca fulltext nell'oggetto document /// /// nb: da fare anche ricerca allegati /// </summary> /// <param name="context"></param> /// <returns></returns> public ArrayList FullTextSearch(ref FullTextSearchContext context) { ArrayList result = new ArrayList(); try { List <string> fullTextResult = null; if (context.SearchResultList != null && context.SearchResultList.Length > 0) { // Ricerca già effettuata, reperimento dall'oggetto di contesto // dei risultati precedenti evitando così una dispendiosa // chiamata al sistema documentale fullTextResult = new List <string>(context.SearchResultList); } else { StructuredQuery strQuery = new StructuredQuery(); strQuery.AddRepository(DctmConfigurations.GetRepositoryName()); strQuery.ObjectType = ObjectTypes.DOCUMENTO; strQuery.IsDatabaseSearch = false; strQuery.IsIncludeAllVersions = false; strQuery.IsIncludeHidden = false; // Inserisce nella ricerca il solo cabinet dell'amministrazione RepositoryScope repositoryScope = new RepositoryScope(); repositoryScope.RepositoryName = DctmConfigurations.GetRepositoryName(); repositoryScope.LocationPath = DocsPaAdminCabinet.getRootAmministrazione(this.InfoUtente); repositoryScope.IsDescend = true; strQuery.Scopes.Add(repositoryScope); ExpressionSet set = new ExpressionSet(); set.AddExpression(new FullTextExpression(context.TextToSearch)); strQuery.RootExpressionSet = set; // Query execution int startIndex = (context.RequestedPageNumber * PAGE_SIZE) - PAGE_SIZE; int maxResults = this.GetMaxRowCount(); QueryExecution queryExec = new QueryExecution(startIndex, maxResults, maxResults); ISearchService searchService = DctmServiceFactory.GetServiceInstance <ISearchService>(this.InfoUtente.dst); QueryResult queryResult = searchService.Execute(strQuery, queryExec, null); QueryStatus queryStatus = queryResult.QueryStatus; RepositoryStatusInfo repStatusInfo = queryResult.QueryStatus.RepositoryStatusInfos[0]; if (repStatusInfo.Status == Status.FAILURE) { throw new ApplicationException("QueryResult: Status.FAILURE"); } fullTextResult = new List <string>(); foreach (DataObject dataObject in queryResult.DataObjects) { // Reperimento docnumber string docNumber = dataObject.Properties.Get(TypeDocumento.DOC_NUMBER).GetValueAsString(); if (!fullTextResult.Contains(docNumber)) // Eliminazione dei risultati duplicati { fullTextResult.Add(docNumber); } } context.SearchResultList = fullTextResult.ToArray(); context.TotalPageNumber = (fullTextResult.Count / PAGE_SIZE); context.TotalRecordCount = fullTextResult.Count; } // Paginazione dei risultati if (fullTextResult != null && fullTextResult.Count > 0) { int startIndex = (context.RequestedPageNumber * PAGE_SIZE) - PAGE_SIZE; int count = PAGE_SIZE; if (fullTextResult.Count < count) { count = fullTextResult.Count; } List <string> pageContent = fullTextResult.GetRange(startIndex, count); result = this.GetDocuments(pageContent.ToArray(), InfoUtente); } } catch (Exception ex) { result.Clear(); logger.Debug(string.Format("Errore in Documentum.FullTextSearch:\n{0}", ex.ToString())); } return(result); }
private void Install(IResolutionResult resolutionResult, PackageManifestRoot manifest, RepositoryScope scope) { if (scope != RepositoryScope.Cache) { var cacheRepo = new CacheRepository(_repositoryFactory.TryGetEnabledRepos(RepositoryScope.Cache)); cacheRepo.PackageDownloadToCacheRepositoryStarted += CacheRepositoryPackageDownloadToCacheRepositoryStarted; cacheRepo.PackageDownloadToCacheRepositoryFinished += CacheRepositoryOnPackageDownloadToCacheRepositoryFinished; cacheRepo.DownloadLocally(resolutionResult.ResolutionTable.GetSatisfyingInfos()); cacheRepo.PackageDownloadToCacheRepositoryStarted -= CacheRepositoryPackageDownloadToCacheRepositoryStarted; cacheRepo.PackageDownloadToCacheRepositoryFinished -= CacheRepositoryOnPackageDownloadToCacheRepositoryFinished; } using (var installer = _packageInstallerFactory.GetInstaller(_manifestResolver.CurrentDirectory, resolutionResult.ResolutionTable, manifest)) { installer.BeginInstallPackage += BeginInstallPackage; installer.FinishInstallPackage += FinishInstallPackage; if (Force) { _writer.Text($"Reinstalling {resolutionResult.ResolutionTable.GetPackages().Count()} packages... "); installer.Reinstall(Configuration); } else { var diff = installer.GetDiffWithCurrent(resolutionResult.ResolutionTable.GetSatisfyingInfos()).ToArray(); int changed = PrintSuccess(diff); if (changed > 0) { installer.Upgrade(Configuration, diff); } else { _writer.Success("No changes detected"); } } installer.BeginInstallPackage -= BeginInstallPackage; installer.FinishInstallPackage -= FinishInstallPackage; } }
public TreeModel GetTree(string path) { var isEmptyPath = string.IsNullOrEmpty(path); string referenceName; var commit = GetCommitByPath(ref path, out referenceName); if (commit == null) { if (isEmptyPath) { var branch = _repository.Branches["master"] ?? _repository.Branches.FirstOrDefault(); return(new TreeModel { ReferenceName = branch == null ? "HEAD" : branch.Name, }); } return(null); } var model = new TreeModel { ReferenceName = referenceName, Path = string.IsNullOrEmpty(path) ? "" : path, Commit = new CommitModel { Sha = commit.Sha, Author = commit.Author, Committer = commit.Committer, CommitMessageShort = commit.MessageShort.RepetitionIfEmpty(NoCommitMessage), Parents = commit.Parents.Select(s => s.Sha).ToArray() }, }; var tree = string.IsNullOrEmpty(path) ? commit.Tree : commit[path] == null ? null : commit[path].Target as Tree; if (tree == null) { return(null); } IEnumerable <Commit> ancestors = _repository.Commits .QueryBy(new CommitFilter { Since = commit, SortBy = CommitSortStrategies.Topological }); var scope = GitCache.Get <RepositoryScope>(commit.Sha, "scope"); if (scope == null) { ancestors = ancestors.ToList(); scope = new RepositoryScope { Commits = ancestors.Count(), Contributors = ancestors.Select(s => s.Author.ToString()).Distinct().Count(), }; GitCache.Set(commit.Sha, "scope", scope); } var entries = tree .OrderBy(s => s.TargetType == TreeEntryTargetType.Blob) .ThenBy(s => s.Name, new StringLogicalComparer()) .Select(s => new TreeEntryModel { Name = s.Name, ReferenceName = referenceName, Path = s.Path.Replace('\\', '/'), Commit = new CommitModel { CommitMessageShort = "???", Author = new Signature("???", "???", DateTimeOffset.MinValue), }, Sha = s.Target.Sha, EntryType = s.TargetType, }) .ToList(); var summary = GitCache.Get <RevisionSummaryCacheItem[]>(tree.Sha, "summary"); var missing = summary == null; double scale = scope.Commits * tree.Count; if ((missing || summary.Length == 0) && scale > 20000) { LazyLoadTree(entries, commit, path, scale); } else { summary = CalculateRevisionSummary(entries, ancestors, summary); } if (missing) { GitCache.Set(tree.Sha, "summary", summary ?? new RevisionSummaryCacheItem[0]); } model.Entries = entries; model.Readme = entries.FirstOrDefault(s => s.EntryType == TreeEntryTargetType.Blob && (string.Equals(s.Name, "readme", StringComparison.OrdinalIgnoreCase) //|| string.Equals(s.Name, "readme.txt", StringComparison.OrdinalIgnoreCase) || string.Equals(s.Name, "readme.md", StringComparison.OrdinalIgnoreCase))); if (model.Readme != null) { var data = ((Blob)tree[model.Readme.Name].Target).GetContentStream().ToBytes(); var encoding = FileHelper.DetectEncoding(data, CpToEncoding(commit.Encoding), _i18n.Value); if (encoding == null) { model.Readme.BlobType = BlobType.Binary; } else { model.Readme.BlobType = model.Readme.Name.EndsWith(".md", StringComparison.OrdinalIgnoreCase) ? BlobType.MarkDown : BlobType.Text; model.Readme.TextContent = FileHelper.ReadToEnd(data, encoding); model.Readme.TextBrush = "no-highlight"; } } model.BranchSelector = GetBranchSelectorModel(referenceName, commit.Sha, path); model.PathBar = new PathBarModel { Name = Name, Action = "Tree", Path = path, ReferenceName = referenceName, ReferenceSha = commit.Sha, HideLastSlash = false, }; if (model.IsRoot) { scope.Branches = _repository.Branches.Count(); scope.Tags = _repository.Tags.Count(); model.Scope = scope; } return(model); }