/// <summary> /// Handles the specified command. /// </summary> /// <param name="command">The command.</param> public async void Handle(AmazonGetProductCategories3dPartyCommand command) { InfoAccumulator info = new InfoAccumulator(); IDictionary <string, IEnumerable <AmazonProductCategory> > categoriesPerSku = new Dictionary <string, IEnumerable <AmazonProductCategory> >(); foreach (var sku in command.SellerSKUs.Distinct()) { if (string.IsNullOrEmpty(sku)) { Log.Warn("got empty sku"); continue; } var categoriesRequest = new GetProductCategoriesForSKURequest { SellerId = command.SellerId, SellerSKU = sku, MarketplaceId = command.MarketplaceId }; GetProductCategoriesForSKUResponse response = await AmazonService.Products.GetProductCategoriesForSKU(categoriesRequest); IEnumerable <AmazonProductCategory> categories = Enumerable.Empty <AmazonProductCategory>(); if (response.IsSetGetProductCategoriesForSKUResult()) { categories = CreateCategories(response.GetProductCategoriesForSKUResult.Self); } categoriesPerSku.Add(sku, categories); } SendReply(info, command, resp => resp.CategoriesBySku = categoriesPerSku); }
/// <summary> /// Handles the specified command. /// </summary> /// <param name="command">The command.</param> public async void Handle(TwilioSendSmsCommand command) { InfoAccumulator info = new InfoAccumulator(); TwilioSms sms = null; if (string.IsNullOrEmpty(command.Message) || string.IsNullOrEmpty(command.PhoneNumber)) { info.AddError("got empty message or phone number"); } else { Message response = await Twilio.SendSms(command.PhoneNumber, command.Message); if (response == null) { info.AddError("error in sending sms"); } else { sms = GetTwilioSms(response); } } SendReply(info, command, resp => resp.Sms = sms); }
/// <summary> /// Handles the specified command. /// </summary> /// <param name="command">The command.</param> public void Handle(CompanyGetDetailsCommand command) { InfoAccumulator info = new InfoAccumulator(); int customerId, companyId; try { customerId = CustomerIdEncryptor.DecryptCustomerId(command.CustomerId, command.CommandOriginator); companyId = CompanyIdEncryptor.DecryptCompanyId(command.CompanyId, command.CommandOriginator); } catch (Exception ex) { Log.Error(ex.Message); SendReply(info, command, resp => { resp.CustomerId = command.CustomerId; resp.CompanyId = command.CompanyId; }); return; } var company = CompanyQueries.GetCompanyById(companyId) .Value; var directors = CompanyQueries.GetDirectors(customerId, companyId) .Value; var directorsAddresses = CompanyQueries.GetDirectorsAddresses(customerId, companyId) .Value; var companyEmployeeCount = CompanyQueries.GetCompanyEmployeeCount(customerId, companyId) .Value; var customer = CustomerQueries.GetCustomerPartiallyById(customerId, o => o.PersonalInfo.IndustryType, o => o.PersonalInfo.OverallTurnOver); SendReply(info, command, resp => { resp.CompanyDetails = ConvertToCompanyDetails(company, customer, companyEmployeeCount); resp.Authorities = GetAuthorities(directors, directorsAddresses); }); }
/// <summary> /// Handles the specified request. /// </summary> /// <param name="command">The request.</param> public async void Handle(CustomerSendVerificationSmsCommand command) { string verificationWord = StringUtils.GenerateRandomEnglishString(); TwilioSendSmsCommand sendSmsCommand = CreateSendSmsCommand(command, verificationWord); InfoAccumulator info = new InfoAccumulator(); try { var response = await TwilioSmsAsyncSendReceive.SendAsync(Config.Address, sendSmsCommand); if (response.Sms != null) { response.Sms.UserId = int.Parse(EncryptionUtils.SafeDecrypt(command.CustomerId)); MobilePhoneQueries.SaveTwilioSms(response.Sms); } else { info.AddError("error sending sms"); } SendReply(info, command); } catch (TaskCanceledException ex) { Log.Error("Time out on sending sms"); info.AddError("Time out sending sms"); SendReply(info, command); } }
/// <summary> /// Handles the specified command. /// </summary> /// <param name="cmd">The command.</param> public void Handle(YodleeUserAddedAccountCommand cmd) { InfoAccumulator info = new InfoAccumulator(); var userAccount = YodleeQueries.GetUserAccount(cmd.CustomerId); if (userAccount == null) { string err = "could not get useraccount from db for id: " + cmd.CustomerId; info.AddError(err); Log.Error(err); RegisterError(info, cmd); //go to retry throw new InvalidDataException(err); } YodleeGetUserAccountsCommand userAccountsCommand = new YodleeGetUserAccountsCommand { UserName = userAccount.Username, UserPassword = userAccount.Password, CobrandUserName = Config.CoBrandUserName, CobrandPassword = Config.CoBrandPassword, CustomerId = cmd.CustomerId }; SendCommand(ThirdPartyService.Address, userAccountsCommand, cmd); }
/// <summary> /// Handles the specified command. /// </summary> /// <param name="command">The command.</param> public void Handle(CustomerLoginCommand command) { InfoAccumulator info = new InfoAccumulator(); bool res = CustomerQueries.IsUserExists(command.EmailAddress, EncryptPassword(command.Password)); if (!res) { Log.ErrorFormat("Could not find user. EmailAddress: {0}, Password: {1}"); info.AddError("User does not exists."); SendReply(info, command); return; } Customer customer = CustomerQueries.GetCustomerPartiallyByProperty(where => where.Name, command.EmailAddress, select => select.Id); if (customer == null) { Log.ErrorFormat("We have a security user with email: {0}, but do not have a customer with this email"); info.AddError("Server error"); RegisterError(info, command); SendReply(info, command); return; } SendReply(info, command, resp => resp.CustomerId = CustomerIdEncryptor.EncryptCustomerId(customer.Id, command.CommandOriginator)); }
public void Handle(CustomerGetDetailsCommand command) { InfoAccumulator info = new InfoAccumulator(); int customerId; try { customerId = CustomerIdEncryptor.DecryptCustomerId(command.CustomerId, command.CommandOriginator); } catch (Exception ex) { Log.Error(ex.Message); info.AddError("Invalid customer id."); SendReply(info, command); return; } Customer customer = CustomerQueries.GetCustomerById(customerId); IEnumerable <CustomerAddress> addresses = CustomerQueries.GetCustomerAddresses(customerId); IEnumerable <CustomerPhone> phones = CustomerQueries.GetCustomerPhones(customerId); var requesetedLoan = LoanQueries.GetCustomerRequestedLoan(customerId); SendReply(info, command, resp => { resp.PersonalDetails = GetPersonalDetails(customer); resp.ContactDetails = GetContactDetails(phones, customer); resp.CurrentLivingAddress = GetCurrentLivingAddress(addresses, customer); resp.PreviousLivingAddress = GetPreviousLivingAddress(addresses, customer); resp.AdditionalOwnedProperties = GetAdditionalOwnedProperties(addresses, customer) .ToArray(); resp.RequestedAmount = (decimal)requesetedLoan.Map(o => o.Amount.HasValue ? o.Amount.Value : 0); }); }
/// <summary> /// Handles the specified command. /// </summary> /// <param name="command">The command.</param> public async void Handle(EbayGetUserData3dPartyCommand command) { InfoAccumulator info = new InfoAccumulator(); string token = command.Token; if (string.IsNullOrEmpty(token)) { token = await EBayService.FetchToken(command.SessionId); } var userTask = EBayService.GetUserData(token); var accountTask = EBayService.GetAccount(token); var feedbackTask = EBayService.GetUserFeedback(token); var getOrdersCallsTask = EBayService.GetOrders(token, command.GetOrdersTimeFrom, DateTime.Now); await Task.WhenAll(userTask, accountTask, feedbackTask, getOrdersCallsTask); SendReply(info, command, resp => { resp.Token = token; resp.EbayUserRegistrationAddressData = GetUserAddress(userTask.Result.RegistrationAddress); resp.EbayUserSellerPaymentAddressData = GetUserAddress(userTask.Result.SellerInfo.SellerPaymentAddress); resp.EbayUserData = GetUserData(userTask.Result); resp.EbayUserAccountData = GetUserAccountData(accountTask.Result); resp.AdditionalUserAccounts = GetAdditionalUserAccountData(accountTask.Result); resp.EbayFeedback = GetFeedback(feedbackTask.Result); resp.EbayRatings = GetRatings(feedbackTask.Result); resp.EbayFeedbackItems = GetFeedbackItems(feedbackTask.Result); resp.EbayOrders = GetOrders(getOrdersCallsTask.Result); resp.Payload = command.Payload; }); }
/// <summary> /// Handles the specified command. /// </summary> /// <param name="command">The command.</param> public void Handle(DocsUploadCommand command) { InfoAccumulator info = new InfoAccumulator(); int customerId; try { customerId = CustomerIdEncryptor.DecryptCustomerId(command.CustomerId, command.CommandOriginator); } catch (Exception ex) { Log.Error(ex.Message); info.AddError("Invalid customer id."); SendReply(info, command, resp => resp.CustomerId = command.CustomerId); return; } var fileMetaData = command.Files.Select(path => ConvertToFileMetadata(path, command.IsBankDocuments, customerId)); bool res = DocsUploadQueries.SaveCompanyUploadedFiles(fileMetaData); if (!res) { string error = string.Format("could not save some or all uploaded files for customer: {0}", command.CustomerId); info.AddError(error); RegisterError(info, command); throw new Exception("Failed to save some files");//we want to retry } SendReply(info, command, resp => resp.CustomerId = command.CustomerId); }
/// <summary> /// Handles the specified response. /// </summary> /// <param name="response">The response.</param> public void Handle(YodleeGetUserAccountsCommandResponse response) { if (response.IsFailed) { ReplyToOrigin(response); return; } var existingContentServicesIds = YodleeQueries.GetUserContentServicesIds(response.CustomerId) .ToLookup(o => o); List <YodleeContentServiceAccount> newAccounts = response.Accounts.Where(o => !existingContentServicesIds.Contains(o.ContentServiceId)) .ToList(); if (newAccounts.Count > 0) { InfoAccumulator info = new InfoAccumulator(); info.AddInfo("customer " + response.CustomerId + "added " + newAccounts.Count + " accounts"); SaveAccounts(newAccounts, response.UserName, response.UserPassword); SendTransactionsRequestCommand(newAccounts, response.UserName, response.UserPassword); SendReply(info, response); } else { InfoAccumulator info = new InfoAccumulator(); info.AddError("could not find added account for customer: " + response.CustomerId); SendReply(info, response); } }
/// <summary> /// Authorizes the mobile phone number. /// </summary> /// <param name="mobilePhoneNumber">The mobile phone number.</param> /// <param name="countryName">Name of the country.</param> /// <returns></returns> public InfoAccumulator AuthorizeMobilePhoneNumber(string mobilePhoneNumber, CountryName countryName = CountryName.UK) { InfoAccumulator errors = new InfoAccumulator(); //validate debug mode if (IsInDebugMode(mobilePhoneNumber)) { return(errors); } CountInfo countInfo = MobilePhoneQueries.GetCurrentMobileCodeCountInfo(mobilePhoneNumber); //check whether can continue or not if (!CanGenerateCodeAndSendSms(countInfo, mobilePhoneNumber, errors)) { return(errors); } //generate code string code = GenerateAuthorizationCode(); //save phone number and generated code //we do not care whether this operation is succeeded or not (only put logs) and continue SaveGeneratedCodeAndPhoneNumber(mobilePhoneNumber, code, errors); string message = string.Format("Your authentication code is: {0}", code); //send sms and save it in DB //we do not care whether this operation is succeeded or not and continue SendSmsAndSave(mobilePhoneNumber, message, countryName, errors); return(errors); }
/// <summary> /// Gets the ids. /// </summary> /// <param name="command">The command.</param> /// <param name="customerId">The customer identifier.</param> /// <param name="info">The information.</param> /// <param name="companyId">The company identifier.</param> /// <returns></returns> private bool GetIds(UpdateCompanyCommand command, InfoAccumulator info, out int customerId, out int companyId) { DateTime date; try { customerId = CustomerIdEncryptor.DecryptCustomerId(command.CustomerId, command.RequestOrigin, out date); } catch (Exception ex) { Log.Error(ex.Message); info.AddError("Invalid customer id."); customerId = -1; companyId = -1; return(false); } try { companyId = CompanyIdEncryptor.DecryptCompanyId(command.CustomerId, command.RequestOrigin, out date); } catch (Exception ex) { Log.Error(ex.Message); info.AddError("Invalid company id."); customerId = -1; companyId = -1; return(false); } return(true); }
/// <summary> /// Gets the user vat identifier and tax office number. /// </summary> /// <param name="url">The URL.</param> /// <returns></returns> public async Task <TaxOfficeNumberAndVatId> GetUserVatIdAndTaxOfficeNumber(string url, IEzBobWebBrowser browser) { string html = await browser.DownloadPageAsyncAsString(url + "/home/services"); HtmlDocument document = new HtmlDocument(); document.LoadHtml(html); InfoAccumulator info = new InfoAccumulator(); string vatId = GetUserVatIdOldFashionedWay(document, info); if (string.IsNullOrEmpty(vatId)) { vatId = GetUserVatIdNewFashionedWay(document, info); if (string.IsNullOrEmpty(vatId)) { LogErrors(info); return(new TaxOfficeNumberAndVatId(null, null)); } } info = new InfoAccumulator(); string taxOfficeNumber = ExtractTaxOfficeNumber(document, info); if (string.IsNullOrEmpty(taxOfficeNumber)) { LogErrors(info); } return(new TaxOfficeNumberAndVatId(taxOfficeNumber, vatId)); }
/// <summary> /// Validates the mobile phone number. /// </summary> /// <param name="phoneNumber">The phone number.</param> /// <param name="code">The code.</param> /// <returns></returns> public InfoAccumulator ValidateMobilePhoneNumber(string phoneNumber, string code) { InfoAccumulator errors = new InfoAccumulator(); if (string.IsNullOrEmpty(phoneNumber)) { String errorMsg = "got empty phone number"; Log.Error(errorMsg); errors.AddError(errorMsg); return(errors); } if (string.IsNullOrEmpty(code)) { String errorMsg = "got empty code"; Log.Error(errorMsg); errors.AddError(errorMsg); return(errors); } if (!MobilePhoneQueries.ValidateMobilePhoneNumber(phoneNumber, code)) { String errorMsg = String.Format("failed to validate phone number: {0} and code: {1}", phoneNumber, code); Log.Warn(errorMsg); errors.AddInfo(errorMsg); } return(errors); }
/// <summary> /// Customers the login. /// </summary> private void CustomerLogin() { Post["CustomerLogin", "api/v1/customer/login", runAsync : true] = async(o, ct) => { CustomerLoginCommand command; //Bind try { command = this.Bind <CustomerLoginCommand>(); } catch (ModelBindingException ex) { return(CreateErrorResponse(b => b.WithModelBindingException(ex))); } //Validate InfoAccumulator info = Validate(command, LoginValidator); if (info.HasErrors) { return(CreateErrorResponse(b => b.WithErrorMessages(info.GetErrors()))); } CustomerLoginCommandResponse response; //Send command try { response = await LoginCommandSendRecieve.SendAsync(Config.ServiceAddress, command); } catch (TaskCanceledException ex) { Log.Error("Timeout on get customer login."); return(CreateErrorResponse(HttpStatusCode.InternalServerError)); } return(CreateOkResponse(b => b.WithCustomerId(response.CustomerId))); }; }
/// <summary> /// Validates the signup command. /// </summary> /// <param name="command">The command.</param> /// <returns></returns> private InfoAccumulator ValidateSignupCommand(CustomerSignupCommand command) { InfoAccumulator info = new InfoAccumulator(); if (command.EmailAddress.IsEmpty()) { info.AddError("Got empty email address."); } if (command.Password.IsEmpty()) { info.AddError("Got empty password."); } if (command.SequrityQuestionId.HasValue) { if (command.SequrityQuestionId.Value < 1 || command.SequrityQuestionId > 3) { info.AddError("Invalid security question id"); } else if (command.SecurityQuestionAnswer.IsEmpty()) { info.AddError("Empty security question"); } } return(info); }
/// <summary> /// Returns the error. /// </summary> /// <param name="info">The information.</param> /// <returns></returns> private HmrcVatReturnsInfo ReturnError(InfoAccumulator info) { return(new HmrcVatReturnsInfo { Info = info }); }
/// <summary> /// Handles the specified command. /// </summary> /// <param name="command">The command.</param> public void Handle(HmrcRegisterCustomerCommand command) { InfoAccumulator info = Validate(command); if (info.HasErrors) { SendReply(info, command); return; } info = MarketPlaceQueries.ValidateCustomerMarketPlace(HmrcInternalId, command.UserName); if (info.HasErrors) { SendReply(info, command); return; } int customerId = int.Parse(EncryptionUtils.SafeDecrypt(command.CustomerId)); AccountModel hmrcAccountModel = new AccountModel { login = command.UserName, password = command.Password }; byte[] securityData = SerializationUtils.SerializeToBinaryXml(hmrcAccountModel); securityData = EncryptionUtils.Encrypt(securityData); int marketplaceId = (int)MarketPlaceQueries.CreateNewMarketPlace(customerId, command.UserName, securityData, HmrcInternalId); if (marketplaceId < 1) { string msg = string.Format("could not create marketplace for customer {0}", command.CustomerId); //writes encrypted customer id Log.Error(msg); throw new Exception(msg); } var updateHistory = new CustomerMarketPlaceUpdateHistory() { CustomerMarketPlaceId = marketplaceId, UpdatingStart = DateTime.UtcNow }; int marketPlaceHistoryId = (int)MarketPlaceQueries.UpsertMarketPlaceUpdatingHistory(updateHistory); if (marketPlaceHistoryId < 1) { string message = string.Format("could not upsert marketplace history for customer: {0}", command.CustomerId); Log.Error(message); throw new Exception(message); } HmrcGetVatReturns3dPartyCommand commandToSend = new HmrcGetVatReturns3dPartyCommand { UserName = command.UserName, Password = command.Password, CustomerId = command.CustomerId }; SendCommand(ThirdPartyServiceConfig.Address, commandToSend, command); }
/// <summary> /// Handles the specified command. /// </summary> /// <param name="command">The command.</param> public async void Handle(AmazonGetCustomerInfo3dPartyCommand command) { var ratingInfo = await CustomerRating.GetRating(command.SellerId); InfoAccumulator info = new InfoAccumulator(); SendReply(info, command, resp => resp.BusinessName = ratingInfo.Name); }
/// <summary> /// Handles the specified command. /// </summary> /// <param name="command">The command.</param> public async void Handle(AmazonGetOrdersDetails3PartyCommand command) { IDictionary <string, IList <AmazonOrderItemDetail> > orderDetailsByOrderId = await GetOrdersDetailsByOrderId(command); InfoAccumulator info = new InfoAccumulator(); SendReply(info, command, resp => resp.OrderDetailsByOrderId = orderDetailsByOrderId); }
public async void Handle(PayPalGetPermissionsRedirectUrl3dPartyCommand command) { var url = await PayPalService.GetPermissionsRedirectUrl(command.Callback); InfoAccumulator info = new InfoAccumulator(); SendReply(info, command, resp => resp.PermissionsRedirectUrl = url); }
/// <summary> /// Registers the error. /// </summary> /// <param name="info">The information.</param> /// <param name="command">The command.</param> protected void RegisterError(InfoAccumulator info, CommandBase command) { Tuple <Guid, InfoAccumulator> cacheItem = new Tuple <Guid, InfoAccumulator>(command.MessageId, info); ErrorCache.Set(Bus.CurrentMessageContext.Id, cacheItem, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60) }); }
private static void ValidateMarketPlace(IContainer container, AmazonGetCustomerInfo3dPartyCommandResponse customerInfoResponse) { IMarketPlaceQueries marketPlaceQueries = container.GetInstance <IMarketPlaceQueries>(); InfoAccumulator info = marketPlaceQueries.ValidateCustomerMarketPlace(amazonInternalId, customerInfoResponse.BusinessName); Assert.False(info.HasErrors, "marketplace validation failed"); }
/// <summary> /// Handles the specified message. /// </summary> /// <param name="handledCommand">The message.</param> public void Handle(EbayGetLoginUrl3dPartyCommandResponse handledCommand) { InfoAccumulator info = new InfoAccumulator(); SendReply(info, handledCommand, resp => { resp.EbayLoginUrl = handledCommand.Url; resp.SessionId = handledCommand.SessionId; }); }
/// <summary> /// Handles a message. /// </summary> /// <param name="command">The command to handle.</param> /// <remarks> /// This method will be called when a message arrives on the bus and should contain /// the custom logic to execute when the command is received. /// </remarks> public void Handle(CustomerUpdateCommand command) { InfoAccumulator info = new InfoAccumulator(); if (!ValidateCommand(command, info)) { SendReply(info, command, response => response.CustomerId = command.CustomerId); return; } int customerId; try { customerId = CustomerIdEncryptor.DecryptCustomerId(command.CustomerId, command.CommandOriginator); } catch (Exception ex) { Log.Error(ex.Message); info.AddError("Invalid customer id."); SendReply(info, command, resp => resp.CustomerId = command.CustomerId); return; } //requests only PropertyStatusId from DB Customer customer = CustomerQueries.GetCustomerPartiallyById(customerId, o => o.PropertyStatusId); FillCustomerProperties(customer, command, info); if (info.HasErrors) { SendReply(info, command, resp => resp.CustomerId = command.CustomerId); return; } IEnumerable <CustomerAddress> addresses = FillCustomerPropertyStatusAndTimeAtAddressAndGetAddresses(command, customer, customerId); IEnumerable <CustomerPhone> phones = ExtractPhoneNumbers(command, customerId); string referenceSource = null; string visitTimes = null; if (command.Cookies != null) { referenceSource = command.Cookies.ReferenceSource; visitTimes = command.Cookies.VisitTimes; } var errors = CustomerProcessor.UpdateCustomer(customer, command.RequestedAmount, referenceSource, visitTimes, command.CampaignSourceRef, addresses, phones); if (errors.HasErrors) { if (errors.IsRetry) { RegisterError(info, command); } return; } SendReply(errors, command, response => response.CustomerId = command.CustomerId); }
/// <summary> /// Handles the upload. /// </summary> /// <param name="o">The context.</param> /// <param name="ct">The cancellation token.</param> /// <param name="validator">The validator.</param> /// <param name="isBankDocuments">Designates whether the specified document is bank document or not</param> /// <returns></returns> private async Task <Response> HandleUpload(dynamic o, CancellationToken ct, AbstractValidator <FilesUploadModel> validator, bool isBankDocuments) { string customerId = o.customerId; FilesUploadModel model; //Bind try { model = this.Bind <FilesUploadModel>(); model.Files = this.Request.Files; } catch (ModelBindingException ex) { Log.Warn("binding documents upload request: " + customerId, ex); return(CreateErrorResponse(b => b .WithCustomerId(customerId) .WithModelBindingException(ex))); } //Validate InfoAccumulator info = Validate(model, validator); if (info.HasErrors) { return(CreateErrorResponse(b => b .WithCustomerId(customerId) .WithErrorMessages(info.GetErrors()))); } Dictionary <string, Task <string> > fileToTask = this.Request.Files.ToDictionary(f => f.Name, ProcessFile); try { var paths = await Task.WhenAll(fileToTask.Values); var command = new DocsUploadCommand { CustomerId = model.CustomerId, Files = paths, IsBankDocuments = isBankDocuments }; var cts = new CancellationTokenSource(Config.SendReceiveTaskTimeoutMilis); var response = await UploadCommandSendReceive.SendAsync(Config.ServiceAddress, command, cts); if (response.HasErrors) { return(CreateErrorResponse(b => b .WithCustomerId(customerId) .WithErrorMessages(response.Errors))); } } catch (AggregateException ex) { var failedFileNames = fileToTask .Where(p => p.Value.Exception != null) .Select(f => f.Key); return(CreateErrorResponse(b => b .WithCustomerId(customerId) .WithErrorMessages(failedFileNames), HttpStatusCode.InternalServerError)); } return(CreateOkResponse(b => b.WithCustomerId(customerId))); }
/// <summary> /// HMRCs the vat upload. /// </summary> private void HmrcVatUpload() { Post["UploadHmrcPdf", "api/v1/marketplace/hmrc/upload/vat/{customerId}", runAsync : true] = async(o, ct) => { string customerId = o.customerId; FilesUploadModel model; //Bind try { model = this.Bind <FilesUploadModel>(); model.Files = this.Request.Files; } catch (ModelBindingException ex) { Log.Warn("binding error on hmrc registration request: " + customerId, ex); return(CreateErrorResponse(b => b .WithCustomerId(customerId) .WithModelBindingException(ex))); } //Validate InfoAccumulator info = Validate(model, PdfValidator); if (info.HasErrors) { return(CreateErrorResponse(b => b .WithCustomerId(customerId) .WithErrorMessages(info.GetErrors()))); } Dictionary <string, Task <string> > fileToTask = this.Request.Files.ToDictionary(f => f.Name, ProcessFile); try { var paths = await Task.WhenAll(fileToTask.Values); var command = new HmrcProcessUploadedFilesCommand { CustomerId = model.CustomerId, Files = paths }; var cts = new CancellationTokenSource(Config.SendReceiveTaskTimeoutMilis); var response = await ProcessUploadedFilesSendReceive.SendAsync(Config.ServiceAddress, command, cts); if (response.HasErrors) { return(CreateErrorResponse(b => b .WithCustomerId(customerId) .WithErrorMessages(response.Errors))); } } catch (AggregateException ex) { var failedFileNames = fileToTask .Where(p => p.Value.Exception != null) .Select(f => f.Key); return(CreateErrorResponse(b => b .WithCustomerId(customerId) .WithErrorMessages(failedFileNames), HttpStatusCode.InternalServerError)); } return(CreateOkResponse(b => b.WithCustomerId(customerId))); }; }
/// <summary> /// Validates the command. /// </summary> /// <param name="command">The command.</param> /// <param name="info">The information.</param> /// <returns></returns> private bool ValidateCommand(UpdateCompanyCommand command, InfoAccumulator info) { if (StringUtils.IsEmpty(command.CustomerId)) { info.AddError("invalid customer id"); return(false); } return(true); }
/// <summary> /// Validates the command. /// </summary> /// <param name="cmd">The command.</param> /// <param name="info">The information.</param> /// <returns></returns> private bool ValidateCommand(CustomerUpdateCommand cmd, InfoAccumulator info) { if (StringUtils.IsEmpty(cmd.CustomerId)) { LogError(gotEmptyCustomerID, info); return(false); } return(true); }
/// <summary> /// Returns the error. /// </summary> /// <param name="errorMessage">The error message.</param> /// <returns></returns> private HmrcVatReturnsInfo ReturnError(string errorMessage) { InfoAccumulator info = new InfoAccumulator(); info.AddError(errorMessage); Log.Error(errorMessage); return(new HmrcVatReturnsInfo { Info = info }); }