public CodeService(IDataEncoder dataEncoder, ICodesCollection codesCollection, IRepository repository, ICodeGenerator codeGenerator) { _dataEncoder = dataEncoder; _codes = codesCollection; _repository = repository; _codeGenerator = codeGenerator; }
/// <summary> /// Generates and adds new unique codes to existingCodes. /// This operation does a roll back if it cannot generate enough /// unique keys in a certain amount of tries. /// </summary> /// <param name="existingCodes"></param> /// <param name="codeLength"></param> /// <param name="numberOfCodesToGenerate"></param> /// <returns>True if generation succeeded, false - if it failed.</returns> public bool TryAddNewUniqueCodes(ICodesCollection existingCodes, int codeLength, int numberOfCodesToGenerate, out List <Code> newCodesAdded) { var countOfAttempts = 0; newCodesAdded = new List <Code>(numberOfCodesToGenerate); while (newCodesAdded.Count < numberOfCodesToGenerate) { if (countOfAttempts > _maxFailedGenerationAttempts) { break; } var setOfCodes = GenerateCodes(codeLength, numberOfCodesToGenerate - newCodesAdded.Count); for (var idx = 0; idx < setOfCodes.Length; ++idx) { if (existingCodes.Add(setOfCodes[idx])) { newCodesAdded.Add(setOfCodes[idx]); } } countOfAttempts++; } if (newCodesAdded.Count == numberOfCodesToGenerate) { return(true); } existingCodes.RemoveRange(newCodesAdded); newCodesAdded = new List <Code>(); return(false); }