static void Main(string[] args) { PetValidator petValidator = new PetValidator(); string petsFilename = "..\\..\\..\\data\\pets.txt"; PetsRepository petsRepository = new PetsRepository(petValidator, petsFilename); CustomerValidator customerValidator = new CustomerValidator(); string customersFilename = "..\\..\\..\\data\\customers.txt"; CustomersRepository customersRepository = new CustomersRepository(customerValidator, customersFilename); ServiceValidator serviceValidator = new ServiceValidator(); string servicesFilename = "..\\..\\..\\data\\services.txt"; ServicesRepository servicesRepository = new ServicesRepository(serviceValidator, servicesFilename); VetValidator vetValidator = new VetValidator(); string vetsFilename = "..\\..\\..\\data\\vets.txt"; VetsRepository vetsRepository = new VetsRepository(vetValidator, vetsFilename); AppointmentValidator appointmentValidator = new AppointmentValidator(); string appointmentsFilename = "..\\..\\..\\data\\appointments.txt"; AppointmentsRepository appointmentsRepository = new AppointmentsRepository(appointmentValidator, appointmentsFilename); Controller controller = new Controller(petsRepository, customersRepository, servicesRepository, vetsRepository,appointmentsRepository); runApp(controller); }
bool Save(object entity) { var service = entity as Service; var validated = new ServiceValidator().Validate(service); if (!validated) { return(false); } Service serviceToProcess = null; var existingService = _services.FirstOrDefault(s => s.Id == service.Id); if (existingService == null) { var profile = new ProfileServer().GetProfile(); service.UserId = profile.Id; service.Id = service.Id ?? Guid.NewGuid().ToString(); _services.Add(service); serviceToProcess = service; } else { service.Update(existingService); serviceToProcess = existingService; } SaveData(serviceToProcess); SaveMaterials(serviceToProcess); return(true); }
public TransactionService(CasinoContext dbContext, ICurrencyRateApiService currencyService) { ServiceValidator.ObjectIsNotEqualNull(dbContext); this.dbContext = dbContext; this.currencyService = currencyService; }
public async Task <Wallet> CreateWallet(string userId, int currencyId) { var wallet = await this.context.Wallets.FirstOrDefaultAsync(wa => wa.UserId == userId); var currency = await this.context.Currencies.FirstOrDefaultAsync(cu => cu.Id == currencyId); if (wallet != null) { throw new EntityAlreadyExistsException("The user already has wallet"); } ServiceValidator.ObjectIsNotEqualNull(currency); var newWallet = new Wallet() { Id = Guid.NewGuid().ToString(), UserId = userId, Currency = currency }; context.Wallets.Add(newWallet); await context.SaveChangesAsync(); return(newWallet); }
public static Stream WriteToStream <TBody>(TBody value, string contentType, Encoding encoding) { // formatters do not support non HTTP context processing var httpContext = new HttpContextMock(); httpContext.Response.Body = new MemoryStream(); var outputFormatterCanWriteContext = new OutputFormatterWriteContext( httpContext, (str, enc) => new StreamWriter(httpContext.Response.Body, encoding), value?.GetType(), value) { ContentType = new StringSegment(contentType) }; var outputFormatter = outputFormatters.GetOrAdd(contentType, _ => { var mvcOptions = TestServiceProvider.GetRequiredService <IOptions <MvcOptions> >(); var formatter = mvcOptions.Value?.OutputFormatters?.FirstOrDefault(f => f.CanWriteResult(outputFormatterCanWriteContext)); ServiceValidator.ValidateFormatterExists(formatter, contentType); return(formatter); }); AsyncHelper.RunSync(() => outputFormatter.WriteAsync(outputFormatterCanWriteContext)); // copy memory stream because formatters close the original one return(new MemoryStream(((MemoryStream)httpContext.Response.Body).ToArray())); }
public async Task <bool> processReverseToServerAsync(LTL_LotteryList pListObject) { bool successReversion = false; Console.WriteLine(" - Anulada "); ServiceResponseResult response = await this.reverseListNumberFromServerAsync(pListObject); if (ServiceValidator.isValidServiceResponse(response)) { // Cambiar el estado de la lista local a Sincronizado this.setListCompleteSync(pListObject); successReversion = true; } else { // Error de sincronización string responseType = response == null ? "N/A" : response.type; LogService.logErrorServiceResponse("No se pudo sincronizar la reversión", responseType, "Pendiente"); } if (response != null && response.message == "No se pudo actualizar. El elemento especificado no existe") { successReversion = true; } return(successReversion); }
/// <summary> ///Post service base. /// </summary> /// <param name="request"></param> /// <param name="attachProposedChannels"></param> /// <returns></returns> protected IActionResult Post(IVmOpenApiServiceInVersionBase request, bool attachProposedChannels = false) { if (request == null) { ModelState.AddModelError("RequestIsNull", CoreMessages.OpenApi.RequestIsNull); return(new BadRequestObjectResult(ModelState)); } // Validate the items if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } // Get the base model for service request = request.VersionBase(); // Check the item values from db and validate if (request.PublishingStatus != PublishingStatus.Published.ToString()) { request.PublishingStatus = PublishingStatus.Draft.ToString(); } ServiceValidator service = new ServiceValidator(request, generalDescriptionService, codeService, fintoService, commonService, channelService, request.AvailableLanguages, UserRole()); service.Validate(this.ModelState); if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } var result = serviceService.AddService(request, Settings.AllowAnonymous, versionNumber, attachProposedChannels); return(Ok(result)); }
// Método para procesar el resultado del envÃo de la lista al servidor public bool processResponseToSendList(ServiceResponseResult pResponseResult) { //Console.WriteLine("Ejecutando processResponseToSendList..."); bool processDone = false; if (ServiceValidator.isValidAndNotEmptyServiceResponse(pResponseResult)) { // Obtener el JSON resultado de la sincronización String resultString = pResponseResult.result.ToString(); SyncListResult listSyncResult = JsonConvert.DeserializeObject <SyncListResult>(resultString); long listId = listSyncResult.listNumber; //Console.WriteLine(listId); // Cambiar el estado de la lista local a Sincronizado this.setListCompleteSync(listId); if (this.appMediator != null) { this.appMediator.updateTotalBoxes(); } processDone = true; } else { // Error de sincronización string responseType = pResponseResult == null ? "N/A" : pResponseResult.type; LogService.logErrorServiceResponse("No se pudo sincronizar la venta", responseType, "Pendiente"); } return(processDone); }
public static ServiceValidator GetServiceValidatorInstance() { if (serviceValidator == null) { serviceValidator = new ServiceValidator(GetUnitOfWofkInstance()); } return(serviceValidator); }
/// <summary> /// Gets required service. Throws exception if such is not found or there are no registered services. /// </summary> /// <typeparam name="TInstance">Type of requested service.</typeparam> /// <returns>Instance of TInstance type.</returns> public static TInstance GetRequiredService <TInstance>() { ServiceValidator.ValidateServices(); var service = Current.GetService <TInstance>(); ServiceValidator.ValidateServiceExists(service); return(service); }
bool OnCanSave(object obj) { var name = Name; var laborCost = LaborCost; var taxPercentage = TaxPercentage; return(ServiceValidator.Validate(name, laborCost, taxPercentage)); }
public async Task <Transaction> AddDepositTransaction( string userId, string cardId, double amountInUserCurrency, string description) { ServiceValidator.IsInputStringEmptyOrNull(userId); ServiceValidator.IsInputStringEmptyOrNull(cardId); ServiceValidator.IsInputStringEmptyOrNull(description); ServiceValidator.CheckStringLength(description, 10, 100); ServiceValidator.ValueIsBetween(amountInUserCurrency, 0, double.MaxValue); var userWin = await this.dbContext.Users .Include(w => w.Wallet) .ThenInclude(wall => wall.Currency) .FirstOrDefaultAsync(u => u.Id == userId && u.IsDeleted != true); var bankCard = await this.dbContext.BankCards.FirstOrDefaultAsync(bc => bc.Id == cardId); ServiceValidator.ObjectIsNotEqualNull(userWin); ServiceValidator.ObjectIsNotEqualNull(bankCard); var userCurrency = userWin.Wallet.Currency.Name; var bankRates = await this.currencyService.GetRatesAsync(); double normalisedCurrency = 0; if (bankRates.ContainsKey(userCurrency)) { double normalisedUserCurrency = bankRates[userCurrency]; normalisedCurrency = amountInUserCurrency / normalisedUserCurrency; } else { throw new EntityCurrencyNotFoundException("Unknown user currency"); } var newTransaction = new Transaction() { UserId = userId, OriginalAmount = amountInUserCurrency, Description = description, TransactionTypeId = 3, NormalisedAmount = normalisedCurrency, CardId = bankCard.Id }; userWin.Wallet.NormalisedBalance += normalisedCurrency; userWin.Wallet.DisplayBalance = userWin.Wallet.NormalisedBalance * bankRates[userCurrency]; bankCard.MoneyAdded += amountInUserCurrency; await this.dbContext.Transactions.AddAsync(newTransaction); await this.dbContext.SaveChangesAsync(); return(newTransaction); }
private Result CanTransitionTo(ServiceStatuses status) { var currentStatus = Status; var acceptedTransitions = ServiceValidator.GetStatusTransitions(status); return(acceptedTransitions.Contains(currentStatus) ? Result.Success : Result.SingleError(Warnings.ServiceStatusTransitionNotAllowed, currentStatus, status)); }
public async Task <Transaction> AddStakeTransaction( string userId, double amountInUserCurrency, string description) { ServiceValidator.IsInputStringEmptyOrNull(userId); ServiceValidator.IsInputStringEmptyOrNull(description); ServiceValidator.CheckStringLength(description, 10, 100); ServiceValidator.ValueIsBetween(amountInUserCurrency, 0, double.MaxValue); var userWin = await this.dbContext.Users .Include(w => w.Wallet) .ThenInclude(w => w.Currency) .FirstOrDefaultAsync(u => u.Id == userId && u.IsDeleted != true); ServiceValidator.ObjectIsNotEqualNull(userWin); var userCurrency = userWin.Wallet.Currency.Name; var bankRates = await this.currencyService.GetRatesAsync(); double normalisedCurrency = 0; if (bankRates.ContainsKey(userCurrency)) { double normalisedUserCurrency = bankRates[userCurrency]; normalisedCurrency = amountInUserCurrency / normalisedUserCurrency; } else { throw new EntityCurrencyNotFoundException("Unknown user currency"); } var newTransaction = new Transaction() { UserId = userId, OriginalAmount = amountInUserCurrency, Description = description, TransactionTypeId = 2, NormalisedAmount = normalisedCurrency }; userWin.Wallet.NormalisedBalance -= normalisedCurrency; userWin.Wallet.DisplayBalance = userWin.Wallet.NormalisedBalance * bankRates[userCurrency]; if (userWin.Wallet.NormalisedBalance < 0) { throw new InsufficientFundsException("Insufficient funds for the requested operation"); } else { await this.dbContext.Transactions.AddAsync(newTransaction); await this.dbContext.SaveChangesAsync(); return(newTransaction); } }
public async Task <User> RetrieveUser(string id) { var user = await this.context.Users .Include(us => us.Wallet) .ThenInclude(wa => wa.Currency) .FirstOrDefaultAsync(us => us.Id == id); ServiceValidator.ObjectIsNotEqualNull(user); return(user); }
public static TDbContext GetDbContext <TDbContext>(this HttpTestContext httpTestContext) where TDbContext : class { ServiceValidator.ValidateScopedServiceLifetime <TDbContext>(nameof(GetDbContext)); return(httpTestContext .HttpContext .RequestServices .GetRequiredService <TDbContext>()); }
public async Task <string> Request(string connections) { ServiceValidator.IsInputStringEmptyOrNull(connections); var response = await client.GetStringAsync(connections); ServiceValidator.IsInputStringEmptyOrNull(response); return(response); }
/// <inheritdoc /> public IAndServicesBuilder WithSetupFor <TService>(Action <TService> scopedServiceSetup) where TService : class { CommonValidator.CheckForNullReference(scopedServiceSetup, nameof(scopedServiceSetup)); ServiceValidator.ValidateScopedServiceLifetime <TService>(nameof(WithSetupFor)); scopedServiceSetup(this.HttpContext.RequestServices.GetRequiredService <TService>()); return(this); }
public async Task <IEnumerable <BankCard> > GetAllCards(string userId) { ServiceValidator.IsInputStringEmptyOrNull(userId); var bankCardQuery = await this.dbContext.BankCards .Where(u => u.UserId == userId && u.IsDeleted == false) .ToListAsync(); return(bankCardQuery); }
public async Task <CyrrencyDaylyWinDTO> GetTransactionsCurrencyDaylyWins(int day) { ServiceValidator.DayIsInMonth(day); var allTransactionsQuery = await this.dbContext .Transactions .Include(tt => tt.TransactionType) .Include(u => u.User.Wallet.Currency) .ToListAsync(); var daylyTotalUsd = allTransactionsQuery .Where(tt => tt.TransactionType.Name == "Win") .Where(td => td.CreatedOn.Value.Month == DateTime.Now.Month && td.CreatedOn.Value.Day == day) .Select(t => t.NormalisedAmount).Sum(); var daylyWinsBGN = allTransactionsQuery .Where(tt => tt.TransactionType.Name == "Win") .Where(c => c.User.Wallet.Currency.Name == "BGN") .Where(td => td.CreatedOn.Value.Month == DateTime.Now.Month && td.CreatedOn.Value.Day == day) .Select(t => t.OriginalAmount).Sum(); var daylyWinsUSD = allTransactionsQuery .Where(tt => tt.TransactionType.Name == "Win") .Where(c => c.User.Wallet.Currency.Name == "USD") .Where(td => td.CreatedOn.Value.Month == DateTime.Now.Month && td.CreatedOn.Value.Day == DateTime.Now.Day) .Select(t => t.OriginalAmount).Sum(); var daylyWinsGBP = allTransactionsQuery .Where(tt => tt.TransactionType.Name == "Win") .Where(c => c.User.Wallet.Currency.Name == "GBP") .Where(td => td.CreatedOn.Value.Month == DateTime.Now.Month && td.CreatedOn.Value.Day == day) .Select(t => t.OriginalAmount).Sum(); var daylyWinsEUR = allTransactionsQuery .Where(tt => tt.TransactionType.Name == "Win") .Where(c => c.User.Wallet.Currency.Name == "EUR") .Where(td => td.CreatedOn.Value.Month == DateTime.Now.Month && td.CreatedOn.Value.Day == day) .Select(t => t.OriginalAmount).Sum(); var resultModel = new CyrrencyDaylyWinDTO() { DaylyTotalUSD = daylyTotalUsd, DaylyWinsBGN = daylyWinsBGN, DaylyWinsEUR = daylyWinsEUR, DaylyWinsGBP = daylyWinsGBP, DaylyWinsUSD = daylyWinsUSD }; return(resultModel); }
public async Task <BaseResponse> AddKeyAsync(string accesToken, string key, string title) { if (ServiceValidator.StringIsNullOrEmpty(accesToken)) { return(new BaseResponse(false, new List <string>() { ServiceValidator.MessageCreator( nameof(GitLabAPIClientService), nameof(AddKeyAsync), nameof(accesToken), "invalid_parameter_null_or_empty") })); } if (ServiceValidator.StringIsNullOrEmpty(key)) { return(new BaseResponse(false, new List <string>() { ServiceValidator.MessageCreator( nameof(GitLabAPIClientService), nameof(AddKeyAsync), nameof(key), "invalid_parameter_null_or_empty") })); } if (ServiceValidator.StringIsNullOrEmpty(title)) { return(new BaseResponse(false, new List <string>() { ServiceValidator.MessageCreator( nameof(GitLabAPIClientService), nameof(AddKeyAsync), nameof(title), "invalid_parameter_null_or_empty") })); } try { var result = await this.client.AddRepoKey(accesToken, key, title); return(new BaseResponse(true)); } catch (Exception ex) { return(new BaseResponse(false, new List <string>() { ex.Message })); } }
public static TOptions GetOptions <TOptions>(this HttpTestContext httpTestContext) where TOptions : class, new() { ServiceValidator.ValidateScopedServiceLifetime(typeof(IOptions <>), nameof(GetOptions)); return(httpTestContext .HttpContext .RequestServices .GetRequiredService <IOptions <TOptions> >() .Value); }
public async Task <User> EditUserAlias(string alias, string id) { ServiceValidator.IsInputStringEmptyOrNull(alias); var user = await this.context.Users.FirstOrDefaultAsync(us => us.Id == id && !us.IsDeleted); ServiceValidator.ObjectIsNotEqualNull(user); user.Alias = alias; await this.context.SaveChangesAsync(); return(user); }
private bool ValidateDataService() { ServiceValidator serviceValidator = new ServiceValidator(); FluentValidation.Results.ValidationResult dataValidationResult = serviceValidator.Validate(Service); IList <ValidationFailure> validationFailures = dataValidationResult.Errors; UserFeedback userFeedback = new UserFeedback(FormGrid, validationFailures); userFeedback.ShowFeedback(); return(dataValidationResult.IsValid && ValidateCity() && ValidateState()); }
//TO DO: FIX THIS public async Task <BankCard> GetCard(string cardNumber) { ServiceValidator.IsInputStringEmptyOrNull(cardNumber); //ServiceValidator.ValidateCardNumber(cardNumber); var bankCardQuery = await this.dbContext.BankCards .FirstOrDefaultAsync(c => c.Id == cardNumber && c.IsDeleted == false); ServiceValidator.ObjectIsNotEqualNull(bankCardQuery); return(bankCardQuery); }
public async Task <IEnumerable <Transaction> > RetrieveAllUsersTransaction(string id) { ServiceValidator.IsInputStringEmptyOrNull(id); var transactionsQuery = await this.dbContext .Transactions .Where(t => t.UserId == id && t.IsDeleted != true) .Include(tt => tt.TransactionType) .Include(u => u.User) .OrderByDescending(d => d.CreatedOn) .ToListAsync(); return(transactionsQuery); }
public async Task <IEnumerable <Transaction> > GetUserTransactions(string userId) { ServiceValidator.IsInputStringEmptyOrNull(userId); var transactionsQuery = await this.dbContext .Transactions .Include(tr => tr.TransactionType) .Where(t => t.UserId == userId && t.IsDeleted != true) .ToListAsync(); ServiceValidator.ValueNotEqualZero(transactionsQuery.Count); return(transactionsQuery); }
public async Task <Wallet> RetrieveWallet(string userId) { //TO DO: OPTIMIZE!!! var wallet = await this.context.Wallets .Include(wa => wa.User) .ThenInclude(us => us.Cards) .Include(wa => wa.User) .ThenInclude(us => us.Transactions) .ThenInclude(tr => tr.TransactionType) .FirstOrDefaultAsync(wa => wa.UserId == userId); ServiceValidator.ObjectIsNotEqualNull(wallet); return(wallet); }
public async Task <IEnumerable <Transaction> > GetTransactionByType(string transactionTypeName) { ServiceValidator.IsInputStringEmptyOrNull(transactionTypeName); ServiceValidator.CheckStringLength(transactionTypeName, 3, 20); var transactionsQuery = await this.dbContext .Transactions .Where(t => t.TransactionType.Name == transactionTypeName && t.IsDeleted != true) .ToListAsync(); ServiceValidator.ValueNotEqualZero(transactionsQuery.Count()); return(transactionsQuery); }
public async Task <Transaction> RetrieveUserTransaction(string id) { ServiceValidator.IsInputStringEmptyOrNull(id); var user = await this.dbContext.Transactions .Include(u => u.User) .Include(tt => tt.TransactionType) .Include(uc => uc.User.Wallet.Currency) .FirstOrDefaultAsync(t => t.Id == id); ServiceValidator.ObjectIsNotEqualNull(user); return(user); }