Beispiel #1
0
        public async Task <IActionResult> AddOverride(OverrideValueModel model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.Value))
                {
                    return(JsonErrorValidationResult("Value is required", "#override_value"));
                }

                var overrideValue = new OverrideValue
                {
                    NetworkId = model.NetworkId,
                    Value     = model.Value
                };

                var keyValue = await _keyValuesRepository.GetKeyValueAsync(model.Key);

                if (keyValue.Override == null)
                {
                    keyValue.Override = new[] { overrideValue }
                }
                ;
                else
                {
                    var list = keyValue.Override.ToList();
                    list.Add(overrideValue);
                    keyValue.Override = list.ToArray();
                }

                await _keyValuesRepository.UpdateKeyValueAsync(new[] { keyValue });

                await AddToHistoryAsync(keyValue);

                return(JsonRequestResult("#overrideValues", Url.Action("List"), false, new { key = model.Key }));
            }
            catch (Exception ex)
            {
                _log.Error(ex, context: model);
                return(JsonRequestResult("#overrideValues", Url.Action("List"), false, new { key = String.Empty }));
            }
        }
Beispiel #2
0
        public async Task <ApiOverrideModel> Put([FromBody] KeyValueToUpdate entity)
        {
            try
            {
                var keyValues = await _keyValuesRepository.GetKeyValuesAsync();

                var keyValue = keyValues.FirstOrDefault(x => x.RowKey == entity.RowKey);
                if (keyValue == null)
                {
                    return(new ApiOverrideModel
                    {
                        Status = UpdateSettingsStatus.NotFound
                    });
                }

                var duplicatedKeys = keyValues.Where(x => x.RowKey != keyValue.RowKey && x.Value == entity.Value).ToList();
                if (entity.Forced == false && IS_PRODUCTION)
                {
                    if (duplicatedKeys.Count > 0)
                    {
                        return(new ApiOverrideModel
                        {
                            Status = UpdateSettingsStatus.HasDuplicated,
                            DuplicatedKeys = duplicatedKeys.Select(x => x.RowKey)
                        });
                    }
                }

                var keyValueEntity = new KeyValueEntity
                {
                    RowKey          = keyValue.RowKey,
                    Value           = entity.Value,
                    IsDuplicated    = duplicatedKeys.Count > 0,
                    Override        = keyValue.Override,
                    Types           = keyValue.Types,
                    RepositoryNames = keyValue.RepositoryNames,
                    EmptyValueType  = keyValue.EmptyValueType
                };
                var entitiesToUpload = new List <IKeyValueEntity>()
                {
                    keyValueEntity
                };

                if (duplicatedKeys.Any())
                {
                    var duplicationsToUpload = duplicatedKeys.Where(x => !x.IsDuplicated.HasValue || !x.IsDuplicated.Value);
                    duplicationsToUpload.ToList().ForEach(item =>
                    {
                        item.IsDuplicated = true;
                        entitiesToUpload.Add(item);
                    });
                }

                var oldDuplications = keyValues.Where(x => x.RowKey != keyValue.RowKey && x.Value == keyValue.Value);
                if (oldDuplications.Count() == 1)
                {
                    var oldDuplication = oldDuplications.First();
                    oldDuplication.IsDuplicated = false;
                    entitiesToUpload.Add(oldDuplication);
                }

                var result = await _keyValuesRepository.UpdateKeyValueAsync(entitiesToUpload);

                string strObj = JsonConvert.SerializeObject(keyValues);
                await _keyValueHistoryRepository.SaveKeyValueHistoryAsync(
                    keyValueEntity?.RowKey,
                    keyValueEntity?.Value,
                    strObj,
                    UserInfo.UserEmail,
                    UserInfo.Ip);

                var updatedKeyValues = await _keyValuesRepository.GetKeyValuesAsync();

                return(new ApiOverrideModel
                {
                    Status = result ? UpdateSettingsStatus.Ok : UpdateSettingsStatus.InternalError,
                    KeyValues = updatedKeyValues
                });
            }
            catch (Exception ex)
            {
                _log.Error(ex, context: entity);
                return(new ApiOverrideModel {
                    Status = UpdateSettingsStatus.InternalError
                });
            }
        }
        private async Task <RepositoriesServiceModel> UpdateRepositoryAsync(
            IRepository repository,
            string userName,
            string userIp,
            string userEmail,
            bool isProduction)
        {
            var repositoryEntity = await _repositoriesRepository.GetAsync(repository.RowKey);

            if (repositoryEntity == null)
            {
                return new RepositoriesServiceModel {
                           Result = UpdateSettingsStatus.NotFound
                }
            }
            ;

            repository.GitUrl = repositoryEntity.GitUrl;
            repository.Tag    = repositoryEntity.Tag;

            //check if type if github or bitbucket. since we have only github and bitbucket I am checking url for github.com
            var type = repository.GitUrl.Contains(GITHUB_URL) ? SourceControlTypes.Github : SourceControlTypes.Bitbucket;

            //get gitUrl for raw json format
            var settingsGitUrl = GitServices.GitServices.GenerateRepositorySettingsGitUrl(repository.GitUrl, type, repository.Branch);

            var name = GitServices.GitServices.GetGitRepositoryName(repository.GitUrl, type);

            string fileFullName = FILENAME;

            fileFullName += type == SourceControlTypes.Github ? "git_" : "bb_";
            fileFullName += name + "_" + repository.Branch;
            fileFullName += repository.Tag == null ? FILE_FORMAT : $"_{repository.Tag}{FILE_FORMAT}";

            repositoryEntity = new RepositoryEntity
            {
                RowKey       = Guid.NewGuid().ToString(),
                GitUrl       = repository.GitUrl,
                Branch       = repository.Branch,
                FileName     = fileFullName,
                UserName     = userName,
                Name         = name,
                OriginalName = name,
                Tag          = repository.Tag
            };

            var last = await _repositoriesUpdateHistoryRepository.GetAsync(repository.RowKey);

            repositoryEntity.ConnectionUrl = _repositoryFileInfoControllerAction + last.InitialCommit + "/"
                                             + (!string.IsNullOrWhiteSpace(repositoryEntity.Tag) ? repositoryEntity.Tag + "/" : string.Empty) + name;

            //get json from generated gitUrl
            var settingsResult = GitServices.GitServices.DownloadSettingsFileFromGit(
                _log,
                settingsGitUrl,
                type,
                _appSettings.BitBucketSettings?.BitbucketEmail,
                _appSettings.BitBucketSettings?.BitbucketPassword);

            if (!settingsResult.Success)
            {
                return new RepositoriesServiceModel
                       {
                           Result  = UpdateSettingsStatus.GitDownloadError,
                           Message = "Couldn't download settings file from git",
                           Data    = settingsResult.Message,
                       }
            }
            ;

            string settingsYaml = settingsResult.Data.ToString();
            var    settings     = settingsYaml.GetSettingsDataFromYaml();

            if (!settings.Success)
            {
                return new RepositoriesServiceModel
                       {
                           Result  = UpdateSettingsStatus.YamlProcessingError,
                           Message = "Couldn't get settings data from yaml",
                           Data    = settings.Message,
                       }
            }
            ;

            var settingsJson = (settings.Data as DataFromYaml)?.Json;

            // update key values
            var placeholders = (settings.Data as DataFromYaml)?.Placeholders;
            var keyRepoName  = !string.IsNullOrEmpty(repositoryEntity?.Tag) ? repositoryEntity?.Tag + "-" + repositoryEntity?.OriginalName : repositoryEntity?.OriginalName;
            var keyValues    = await InitKeyValuesAsync(
                repositoryEntity,
                placeholders,
                repository.Tag,
                keyRepoName,
                false);

            //no need to update if files are the same
            var existingBlob = await GetFileData(fileFullName);

            bool isDuplicated;

            if (existingBlob == settingsJson)
            {
                var oldKeyValues = await _keyValuesRepository.GetKeyValuesAsync(x => x.RepositoryNames != null && x.RepositoryNames.Contains(keyRepoName));

                if (oldKeyValues.Count() != keyValues.Count)
                {
                    isDuplicated = false;
                }
                else
                {
                    var changesCount = 0;
                    foreach (var item in keyValues)
                    {
                        var oldItem       = oldKeyValues.FirstOrDefault(x => x.RowKey == item.RowKey);
                        var areTypesEqual = oldItem != null && oldItem.Types == null && item.Types == null ||
                                            (oldItem.Types != null && item.Types != null && !oldItem.Types.Except(item.Types).Any() && !item.Types.Except(oldItem.Types).Any());
                        if (oldItem == null || !areTypesEqual)
                        {
                            changesCount++;
                        }
                    }
                    isDuplicated = changesCount == 0;
                }
            }
            else
            {
                isDuplicated = false;
            }

            if (isDuplicated)
            {
                return new RepositoriesServiceModel
                       {
                           Result = UpdateSettingsStatus.HasDuplicated
                       }
            }
            ;

            //Adding data to history repository
            await AddToHistoryRepository(repositoryEntity, settingsJson, repository.RowKey, userName : userName, userIp : userIp);

            //delete repository to add updated one
            await _repositoriesRepository.RemoveRepositoryAsync(repository.RowKey);

            // if updating file, we must not create new name for it
            await _repositoryDataRepository.UpdateBlobAsync(settingsJson, userName, userIp, fileFullName);

            await _repositoriesRepository.SaveRepositoryAsync(repositoryEntity);

            var repositoriesModel = await GetPaginatedRepositories();

            var repositories = repositoriesModel.Data as PaginatedList <IRepository>;

            //await _keyValuesRepository.UpdateKeyValueAsync(keyValues);
            await SaveKeyValuesAsync(keyValues, userEmail, userIp, isProduction);

            existingBlob = existingBlob.ReleaseFromComments();
            settingsJson = settingsJson.ReleaseFromComments();

            //If Update remove checking for placeholders change if any deleted fix RepositoryNames for that
            var lastPlaceholders = existingBlob.PlaceholderList();

            for (int i = 0; i < lastPlaceholders.Count; i++)
            {
                foreach (var item in keyValues)
                {
                    if (lastPlaceholders[i].RowKey != null &&
                        lastPlaceholders[i].RowKey == (string.IsNullOrEmpty(repository.Tag) ? item.RowKey : item.RowKey.SubstringFromString(item.Tag + "-")))
                    {
                        lastPlaceholders.Remove(lastPlaceholders[i]);
                        --i;
                        break;
                    }
                }
            }

            if (lastPlaceholders.Count > 0)
            {
                var keyValuesToUpdate = new List <IKeyValueEntity>();
                foreach (var lastItem in lastPlaceholders)
                {
                    var keyValueToUpdate = await _keyValuesRepository.GetKeyValueAsync(string.IsNullOrEmpty(repository.Tag)
                                                                                       ?lastItem.RowKey
                                                                                       : repository.Tag + "-" + lastItem.RowKey);

                    if (keyValueToUpdate != null)
                    {
                        var tempRepoNames = keyValueToUpdate.RepositoryNames?.ToList();
                        tempRepoNames?.Remove(keyRepoName);
                        keyValueToUpdate.RepositoryNames = tempRepoNames != null && tempRepoNames.Count > 0 ? tempRepoNames.ToArray() : null;
                        keyValuesToUpdate.Add(keyValueToUpdate);
                    }
                }
                await _keyValuesRepository.UpdateKeyValueAsync(keyValuesToUpdate);
            }

            return(new RepositoriesServiceModel
            {
                Result = UpdateSettingsStatus.Ok,
                Json = JsonConvert.SerializeObject(repositories),
                Data = new
                {
                    Last = existingBlob,
                    Current = settingsJson,
                    Oldid = repository.RowKey,
                    Newid = repositoryEntity.RowKey,
                    repositories.PageIndex,
                    repositories.TotalPages
                }
            });
        }
    }
}