Exemple #1
0
        public Task <IReadOnlyCollection <OrganizationInfo> > GetTargetsAsync(CancellationToken cancellationToken)
        {
            string jsonTargetsFile = _configuration.SourceFile.WithDefault(Path.Combine(_environment.ApplicationBasePath, "targets.json"));

            _logger.Information("Reading targets from JSON file '{JsonFile}'", jsonTargetsFile);

            IKeyValueConfiguration keyValueConfiguration = new JsonKeyValueConfiguration(jsonTargetsFile);

            IReadOnlyCollection <DeploymentTarget> targets = keyValueConfiguration.GetInstances <DeploymentTarget>();

            IReadOnlyCollection <OrganizationInfo> organizations =
                targets.GroupBy(target => target.Organization.WithDefault("Global"))
                .Select(
                    organizationGroup => new
            {
                Organization = organizationGroup.Key,
                Projects     = organizationGroup
                               .GroupBy(target => target.ProjectInvariantName.WithDefault(Constants.NotAvailable))
                               .Select(
                    projectGroup => new ProjectInfo(organizationGroup.Key,
                                                    projectGroup.Key,
                                                    projectGroup.OrderBy(target => target.Name)))
            })
                .Select(
                    organizationGroup =>
                    new OrganizationInfo(organizationGroup.Organization,
                                         organizationGroup.Projects.OrderBy(project => project.ProjectDisplayName)))
                .OrderBy(organization => organization.Organization)
                .SafeToReadOnlyCollection();

            return(Task.FromResult(organizations));
        }
        public UserJsonConfiguration(string?basePath = null)
        {
            string?fileFullPath = TryGetConfigUser(basePath);

            if (!string.IsNullOrWhiteSpace(fileFullPath) && File.Exists(fileFullPath))
            {
                var jsonConfiguration = new JsonKeyValueConfiguration(fileFullPath);
                _configuration = jsonConfiguration !;
            }

            _configuration ??= NoConfiguration.Empty !;

            _fileFullPath = fileFullPath;
        }
        private void WatcherOnChanged(object sender, FileSystemEventArgs fileSystemEventArgs)
        {
            ImmutableArray <Type> types = _configurationHolder.RegisteredTypes;

            var jsonKeyValueConfiguration = new JsonKeyValueConfiguration(_fileName);

            foreach (Type type in types)
            {
                ImmutableArray <INamedInstance <object> > allInstances = jsonKeyValueConfiguration.GetNamedInstances(type);

                foreach (INamedInstance <object> instance in allInstances)
                {
                    if (instance.Value is IValidationObject validationObject)
                    {
                        if (validationObject.IsValid)
                        {
                            _configurationHolder.Add(instance);
                        }
                    }
                }
            }
        }
Exemple #4
0
        public async Task ThenNewVersionShouldBeDeployed()
        {
            SemanticVersion?semanticVersion = null;

            var expectedVersion = new SemanticVersion(1, 2, 5);

            if (WebFixture is null)
            {
                throw new DeployerAppException($"{nameof(WebFixture)} is null");
            }

            if (WebFixture.ServerEnvironmentTestSiteConfiguration is null)
            {
                throw new DeployerAppException($"{nameof(WebFixture.ServerEnvironmentTestSiteConfiguration)} is null");
            }

            if (WebFixture is null)
            {
                throw new DeployerAppException($"{nameof(WebFixture)} is null");
            }

            Output.WriteLine(typeof(StartupModule).FullName);

            Assert.NotNull(WebFixture?.App?.Host?.Services);

            using (var httpClient = WebFixture !.App !.Host !.Services.GetRequiredService <IHttpClientFactory>().CreateClient())
            {
                using CancellationTokenSource cancellationTokenSource =
                          WebFixture !.App !.Host !.Services.GetRequiredService <CancellationTokenSource>();

                var lifeTime = WebFixture !.App !.Host !.Services.GetRequiredService <IHostApplicationLifetime>();

                cancellationTokenSource.Token.Register(() => Debug.WriteLine("Cancellation for app in test"));

                lifeTime.ApplicationStopped.Register(() => Debug.WriteLine("Stop for app in test"));

                while (!cancellationTokenSource.Token.IsCancellationRequested &&
                       semanticVersion != expectedVersion &&
                       !lifeTime.ApplicationStopped.IsCancellationRequested &&
                       !WebFixture !.CancellationToken.IsCancellationRequested)
                {
                    // ReSharper disable MethodSupportsCancellation
                    StartupTaskContext?startupTaskContext =
                        WebFixture !.App !.Host !.Services.GetService <StartupTaskContext>();

                    if (startupTaskContext is null)
                    {
                        return;
                    }

                    while (!startupTaskContext.IsCompleted &&
                           !cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        await Task.Delay(TimeSpan.FromMilliseconds(500));
                    }

                    var url = new Uri(
                        $"http://localhost:{WebFixture!.ServerEnvironmentTestSiteConfiguration.Port.Port + 1}/applicationmetadata.json");

                    string contents;
                    try
                    {
                        using HttpResponseMessage responseMessage = await httpClient.GetAsync(url);

                        contents = await responseMessage.Content.ReadAsStringAsync();

                        Output.WriteLine($"{responseMessage.StatusCode} {contents}");

                        if (responseMessage.StatusCode == HttpStatusCode.ServiceUnavailable ||
                            responseMessage.StatusCode == HttpStatusCode.NotFound)
                        {
                            await Task.Delay(TimeSpan.FromMilliseconds(100));

                            continue;
                        }

                        Assert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
                    }
                    catch (Exception ex) when(!ex.IsFatal())
                    {
                        throw new DeployerAppException($"Could not get a valid response from request to '{url}'",
                                                       ex);
                    }

                    string tempFileName = Path.GetTempFileName();
                    await File.WriteAllTextAsync(tempFileName,
                                                 contents,
                                                 Encoding.UTF8,
                                                 cancellationTokenSource.Token);

                    var jsonKeyValueConfiguration =
                        new JsonKeyValueConfiguration(tempFileName);

                    if (File.Exists(tempFileName))
                    {
                        File.Delete(tempFileName);
                    }

                    string actual = jsonKeyValueConfiguration["urn:versioning:semver2:normalized"];

                    semanticVersion = SemanticVersion.Parse(actual);
                    await Task.Delay(TimeSpan.FromSeconds(1));

                    // ReSharper restore MethodSupportsCancellation
                }
            }

            if (WebFixture?.Exception is { } exception)
            {
                throw new DeployerAppException("Fixture exception", exception);
            }

            Assert.Equal(expectedVersion, semanticVersion);
        }
Exemple #5
0
        private IEnumerable <KeyValuePair <string, string> > GetVersionVariables(
            IReadOnlyCollection <IVariable> buildVariables,
            ILogger logger)
        {
            List <KeyValuePair <string, string> > environmentVariables =
                buildVariables.Select(item => new KeyValuePair <string, string>(item.Key, item.Value)).ToList();

            int major = -1;
            int minor = -1;
            int patch = -1;
            int build = -1;

            string sourceRoot = buildVariables.GetVariable(WellKnownVariables.SourceRoot).ThrowIfEmptyValue().Value;

            string fileName = "version.json";

            string versionFileName = Path.Combine(sourceRoot, fileName);

            if (File.Exists(versionFileName))
            {
                logger.WriteVerbose(
                    $"A version file was found with name {versionFileName} at source root '{sourceRoot}'");
                IReadOnlyCollection <KeyValueConfigurationItem> keyValueConfigurationItems = null;
                try
                {
                    keyValueConfigurationItems =
                        new JsonFileReader(versionFileName).ReadConfiguration();
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    logger.WriteWarning($"Could not read the configuration content in file '{versionFileName}'");
                }

                if (keyValueConfigurationItems != null)
                {
                    var jsonKeyValueConfiguration = new JsonKeyValueConfiguration(keyValueConfigurationItems);

                    string majorKey = "major"; // TODO defined major key

                    string minorKey = "minor"; // TODO defined minor key

                    string patchKey = "patch"; // TODO defined patch key

                    var required = new Dictionary <string, string>
                    {
                        {
                            majorKey,
                            jsonKeyValueConfiguration.ValueOrDefault(
                                majorKey)
                        },
                        {
                            minorKey,
                            jsonKeyValueConfiguration.ValueOrDefault(
                                minorKey)
                        },
                        {
                            patchKey,
                            jsonKeyValueConfiguration.ValueOrDefault(
                                patchKey)
                        }
                    };

                    if (required.All(ValidateVersionNumber))
                    {
                        major = required[majorKey].TryParseInt32().Value;
                        minor = required[minorKey].TryParseInt32().Value;
                        patch = required[patchKey].TryParseInt32().Value;

                        logger.WriteVerbose(
                            $"All version numbers from the version file '{versionFileName}' were parsed successfully");
                    }
                    else
                    {
                        logger.WriteVerbose(
                            $"Not all version numbers from the version file '{versionFileName}' were parsed successfully");
                    }
                }
            }
            else
            {
                logger.WriteVerbose(
                    $"No version file found with name {versionFileName} at source root '{sourceRoot}' was found");
            }

            int envMajor =
                environmentVariables.Where(item => item.Key == WellKnownVariables.VersionMajor)
                .Select(item => (int?)int.Parse(item.Value))
                .SingleOrDefault() ?? -1;
            int envMinor =
                environmentVariables.Where(item => item.Key == WellKnownVariables.VersionMinor)
                .Select(item => (int?)int.Parse(item.Value))
                .SingleOrDefault() ?? -1;
            int envPatch =
                environmentVariables.Where(item => item.Key == WellKnownVariables.VersionPatch)
                .Select(item => (int?)int.Parse(item.Value))
                .SingleOrDefault() ?? -1;
            int envBuild =
                environmentVariables.Where(item => item.Key == WellKnownVariables.VersionBuild)
                .Select(item => (int?)int.Parse(item.Value))
                .SingleOrDefault() ?? -1;

            int teamCityBuildVersion =
                environmentVariables.Where(item => item.Key == WellKnownVariables.TeamCity.TeamCityVersionBuild)
                .Select(item =>
            {
                if (int.TryParse(item.Value, out int buildVersion) && buildVersion >= 0)
                {
                    return(buildVersion);
                }

                return(-1);
            })
                .SingleOrDefault();

            if (envMajor >= 0)
            {
                logger.WriteVerbose($"Found major {envMajor} version in build variable");
                major = envMajor;
            }

            if (envMinor >= 0)
            {
                logger.WriteVerbose($"Found minor {envMinor} version in build variable");
                minor = envMinor;
            }

            if (envPatch >= 0)
            {
                logger.WriteVerbose($"Found patch {envPatch} version in build variable");
                patch = envPatch;
            }

            if (envBuild >= 0)
            {
                logger.WriteVerbose($"Found build {envBuild} version in build variable");
                build = envBuild;
            }

            if (major < 0)
            {
                logger.WriteVerbose($"Found no major version, using version 0");
                major = 0;
            }

            if (minor < 0)
            {
                logger.WriteVerbose("Found no minor version, using version 0");
                minor = 0;
            }

            if (patch < 0)
            {
                logger.WriteVerbose("Found no patch version, using version 0");
                patch = 0;
            }

            if (build < 0)
            {
                if (teamCityBuildVersion >= 0)
                {
                    build = teamCityBuildVersion;
                    logger.WriteVerbose($"Found no build version, using version {build} from TeamCity ({WellKnownVariables.TeamCity.TeamCityVersionBuild})");
                }
                else
                {
                    logger.WriteVerbose("Found no build version, using version 0");
                    build = 0;
                }
            }

            if (major == 0 && minor == 0 && patch == 0)
            {
                logger.WriteVerbose("Major minor and build versions are all 0, setting minor version to 1");
                minor = 1;
            }

            var    netAssemblyVersion     = new Version(major, minor, 0, 0);
            var    fullVersion            = new Version(major, minor, patch, build);
            string fullVersionValue       = fullVersion.ToString(4);
            var    netAssemblyFileVersion = new Version(major, minor, patch, build);

            yield return
                (new KeyValuePair <string, string>(WellKnownVariables.NetAssemblyVersion, netAssemblyVersion.ToString(4)));

            yield return
                (new KeyValuePair <string, string>(
                     WellKnownVariables.NetAssemblyFileVersion,
                     netAssemblyFileVersion.ToString(4)));

            yield return(new KeyValuePair <string, string>(
                             WellKnownVariables.VersionMajor,
                             major.ToString(CultureInfo.InvariantCulture)));

            yield return(new KeyValuePair <string, string>(
                             WellKnownVariables.VersionMinor,
                             minor.ToString(CultureInfo.InvariantCulture)));

            yield return(new KeyValuePair <string, string>(
                             WellKnownVariables.VersionPatch,
                             patch.ToString(CultureInfo.InvariantCulture)));

            yield return(new KeyValuePair <string, string>(
                             WellKnownVariables.VersionBuild,
                             build.ToString(CultureInfo.InvariantCulture)));

            yield return(new KeyValuePair <string, string>("Version", fullVersionValue));

            yield return(new KeyValuePair <string, string>(WellKnownVariables.Version, fullVersionValue));
        }