Пример #1
0
        public UserViewModel Create(UserInputViewModel input)
        {
            try
            {
                var newUser = new User()
                {
                    UserId    = Guid.NewGuid().ToString(),
                    FirstName = input.FirstName,
                    LastName  = input.LastName,
                    UserName  = input.UserName,
                    Password  = input.Password,
                    UserType  = input.UserType,
                    CreatedBy = _userInfo.UserId,
                    CreatedOn = DateTime.Now
                };

                _databaseContext.Users.Add(newUser);
                _databaseContext.SaveChanges();

                return(new UserViewModel()
                {
                    UserId = newUser.UserId,
                    FirstName = newUser.FirstName,
                    LastName = newUser.LastName,
                    UserName = newUser.UserName,
                    UserType = newUser.UserType
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task AddUserViaApi_FailsDueToMissingFirstName()
        {
            var client = Factory.CreateClient();

            var viewModel = new UserInputViewModel
            {
                FirstName = "",
                LastName  = "Montoya"
            };

            var response = await client.PostAsJsonAsync("/api/users", viewModel);

            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);

            var result = await response.Content.ReadAsStringAsync();

            var problemDetails = JsonConvert.DeserializeObject <ProblemDetails>(result);

            var errors = problemDetails.Extensions["errors"] as JObject;

            var firstError = (JProperty)errors.First;

            var errorMessage = firstError.Value[0];

            Assert.AreEqual("The FirstName field is required.", ((JValue)errorMessage).Value);
        }
Пример #3
0
        public async Task <IActionResult> Index(UserInputViewModel inputData)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.Message = "Please enter a valid data.";
                return(View());
            }

            inputData.BaseCurrency   = inputData.BaseCurrency.ToUpper();
            inputData.TargetCurrency = inputData.TargetCurrency.ToUpper();

            if (!decimal.TryParse(inputData.Amount.Replace('.', ','), out decimal amount))
            {
                ViewBag.Message = "Please enter a valid amount.";
                return(View());
            }

            //no localization ./,
            string request = $"/Rates/{inputData.BaseCurrency}/{inputData.TargetCurrency}/{amount.ToString().Replace(",",".")}"
                             + (inputData.Date != null ? $"/{inputData.Date.Value.ToString("yyyy.MM.dd")}" : "");

            HttpResponseMessage response = await client.GetAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                ViewBag.Message = "Something's gone wrong :(";
                return(View());
            }

            var result = await response.Content.ReadAsStringAsync();

            ViewBag.Message = "Converted amount: ";
            ViewBag.Amount  = result + " " + inputData.TargetCurrency;
            return(View());
        }
        public ParametriScanalatoreViewModel(OperazioneScanalatore operazioneScanalatore, EditStageTreeViewItem parent)
            : base(operazioneScanalatore.Descrizione, parent)
        {
            _operazioneScanalatore = operazioneScanalatore;

            NumeroGiri     = new UserInputViewModel(_operazioneScanalatore.NumeroGiri, GetValidationError, PropNumeroGiri);
            VelocitaTaglio = new UserInputViewModel(_operazioneScanalatore.VelocitaTaglio, GetValidationError, PropVelocitaTaglio);

            LarghezzaPassata      = new UserInputViewModel(_operazioneScanalatore.LarghezzaPassata, GetValidationError, PropLarghezzaPassata);
            LarghezzaPassataPerc  = new UserInputViewModel(_operazioneScanalatore.LarghezzaPassataPerc, GetValidationError, PropLarghezzaPassataPerc);
            ProfonditaPassata     = new UserInputViewModel(_operazioneScanalatore.ProfonditaPassata, GetValidationError, PropProfPassata);
            ProfonditaPassataPerc = new UserInputViewModel(_operazioneScanalatore.ProfonditaPassataPerc, GetValidationError, PropProfPassataPerc);

            AvanzamentoSincrono         = new UserInputViewModel(_operazioneScanalatore.AvanzamentoSincrono, GetValidationError, PropAvanzamentoSincrono);
            AvanzamentoSincronoPiantata = new UserInputViewModel(_operazioneScanalatore.AvanzamentoSincronoPiantata, GetValidationError, PropAvanzamentoSincronoPiantata);

            NumeroGiri.OnSourceUpdated     += UserInput_SourceUpdated;
            VelocitaTaglio.OnSourceUpdated += UserInput_SourceUpdated;

            LarghezzaPassata.OnSourceUpdated      += UserInput_SourceUpdated;
            LarghezzaPassataPerc.OnSourceUpdated  += UserInput_SourceUpdated;
            ProfonditaPassata.OnSourceUpdated     += UserInput_SourceUpdated;
            ProfonditaPassataPerc.OnSourceUpdated += UserInput_SourceUpdated;

            AvanzamentoSincrono.OnSourceUpdated         += UserInput_SourceUpdated;
            AvanzamentoSincronoPiantata.OnSourceUpdated += UserInput_SourceUpdated;
        }
Пример #5
0
        public UserInputView(Storage data)
        {
            InitializeComponent();

            _model      = new UserInputViewModel(data);
            DataContext = _model;
        }
Пример #6
0
        private UserViewModel CreateBackOfficeUser()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddDbContext <KitchenKanbanDB>(options => options.UseInMemoryDatabase("KitchenKanbanDB"), ServiceLifetime.Transient);
            ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
            IUserInfo       userInfo        = new UserInfo()
            {
                UserId   = "95632324-a9f8-44ba-9b3d-4c90dd5d9650",
                UserType = Models.Enums.UserEnum.UserType.Administrator
            };
            IImageService imageService = new ImageService(serviceProvider, userInfo);
            IUserService  userService  = new UserService(serviceProvider, imageService, userInfo);
            var           input        = new UserInputViewModel()
            {
                FirstName = "Richard",
                LastName  = "Townsend",
                Password  = "******",
                UserName  = "******",
                UserType  = UserType.BackOffice
            };
            var user = userService.Create(input);

            return(user);
        }
Пример #7
0
        public async Task <bool> AddNewUser(UserInputViewModel userInputVm)
        {
            var user = new User {
                UserName = userInputVm.Username, Email = userInputVm.Email
            };
            var randomPassword = RandomString.GenerateRandomString();
            var result         = await _userService.CreateAsync(user, randomPassword);

            if (!result.Succeeded)
            {
                return(false);
            }

            await _userService.AddUserToRolesAsync(user, userInputVm.Roles);

            var context = _httpContextAccessor.HttpContext;
            var code    = await _userService.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl  = _urlHelperExtension.EmailConfirmationLink(user.Id, code, context.Request.Scheme);
            var emailOptions = new EmailOptions
            {
                Url      = callbackUrl,
                Password = randomPassword,
                UserName = userInputVm.Username
            };

            await _emailSender.SendEmailAsync(userInputVm.Email, "", emailOptions, EmailType.AccountConfirm);

            return(true);
        }
Пример #8
0
        public ParametroFresaBaseViewModel(Utensile parametroFresaBase)
            : base(parametroFresaBase)
        {
            NumeroGiri     = new UserInputViewModel(ParametroFresaBase.NumeroGiri, GetValidationError, PropNumeroGiri);
            VelocitaTaglio = new UserInputViewModel(ParametroFresaBase.VelocitaTaglio, GetValidationError, PropVelocitaTaglio);

            LarghezzaPassata      = new UserInputViewModel(ParametroFresaBase.LarghezzaPassata, GetValidationError, PropLarghezzaPassata);
            LarghezzaPassataPerc  = new UserInputViewModel(ParametroFresaBase.LarghezzaPassataPerc, GetValidationError, PropLarghezzaPassataPerc);
            ProfonditaPassata     = new UserInputViewModel(ParametroFresaBase.ProfonditaPassata, GetValidationError, PropProfPassata);
            ProfonditaPassataPerc = new UserInputViewModel(ParametroFresaBase.ProfonditaPassataPerc, GetValidationError, PropProfPassataPerc);

            AvanzamentoSincrono  = new UserInputViewModel(ParametroFresaBase.AvanzamentoSincrono, GetValidationError, PropAvanzamentoSincrono);
            AvanzamentoAsincrono = new UserInputViewModel(ParametroFresaBase.AvanzamentoAsincrono, GetValidationError, PropAvanzamentoAsincrono);

            AvanzamentoSincronoPiantata  = new UserInputViewModel(ParametroFresaBase.AvanzamentoSincronoPiantata, GetValidationError, PropAvanzamentoSincronoPiantata);
            AvanzamentoAsincronoPiantata = new UserInputViewModel(ParametroFresaBase.AvanzamentoAsincronoPiantata, GetValidationError, PropAvanzamentoAsincronoPiantata);

            AvanzamentoSincronoPiantata.OnSourceUpdated  += UserInput_SourceUpdated;
            AvanzamentoAsincronoPiantata.OnSourceUpdated += UserInput_SourceUpdated;

            NumeroGiri.OnSourceUpdated     += UserInput_SourceUpdated;
            VelocitaTaglio.OnSourceUpdated += UserInput_SourceUpdated;

            LarghezzaPassata.OnSourceUpdated      += UserInput_SourceUpdated;
            LarghezzaPassataPerc.OnSourceUpdated  += UserInput_SourceUpdated;
            ProfonditaPassata.OnSourceUpdated     += UserInput_SourceUpdated;
            ProfonditaPassataPerc.OnSourceUpdated += UserInput_SourceUpdated;

            AvanzamentoSincrono.OnSourceUpdated  += UserInput_SourceUpdated;
            AvanzamentoAsincrono.OnSourceUpdated += UserInput_SourceUpdated;
        }
Пример #9
0
        private static string AskForInput(UserInputOptions options)
        {
            var viewModel = new UserInputViewModel()
            {
                Message   = options.Message,
                Text      = options.DefaultText,
                Icon      = options.Icon,
                InputTest = options.InputTest
            };
            var window  = new System.Windows.Window();
            var control = new UserInputWindow()
            {
                window      = window,
                context     = viewModel,
                DataContext = viewModel,
            };

            window.Content               = control;
            window.Width                 = options.Width;
            window.WindowStyle           = System.Windows.WindowStyle.ThreeDBorderWindow;
            window.Height                = options.Height;
            window.Title                 = options.Title;
            window.ResizeMode            = System.Windows.ResizeMode.NoResize;
            window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;

            window.ShowDialog();

            return(viewModel.Text);
        }
Пример #10
0
        public async Task <IActionResult> Basket(int page, int userInputId)
        {
            Logger.LogDebug("[userInputId=|{userInputId}|] -> page=|{page}|", userInputId, page);
            UserInputViewModel viewModel       = UserInputService.GetUserInput(userInputId);
            BasketViewModel    basketViewModel = await Configurator.ComputeConfiguration(viewModel, page);

            return(View("Basket", basketViewModel));
        }
Пример #11
0
        public ActionResult ProcessText(UserInputViewModel viewModel)
        {
            /// Проверка значения
            if (ServerSideStringValidation == true)
            {
                if (string.IsNullOrEmpty(viewModel.Word) == true)
                {
                    ModelState.AddModelError(nameof(viewModel.Word), "Задана пустая строка");
                    return(View("Index", viewModel));
                }
            }
            using (var httpClient = new HttpClient()) {
                /// Выбор сервиса по заданному условию
                string selectedService;
                if (viewModel.IsActionChecked == true)
                {
                    selectedService = MicroService2Address;
                }
                else
                {
                    selectedService = MicroService1Address;
                }

                try {
                    httpClient.BaseAddress = new Uri(selectedService);

                    var responseTask = httpClient.PostAsync("convert/",
                                                            new StringContent(
                                                                content: viewModel.Word ?? string.Empty,
                                                                encoding: Encoding.UTF8,
                                                                mediaType: "text/plain"
                                                                ));

                    responseTask.Wait();
                    var result = responseTask.Result;

                    var readTask = result.Content.ReadAsAsync <string>(new[] { new PlainTextMediaTypeFormatter(Encoding.UTF8) });
                    readTask.Wait();

                    if (result.IsSuccessStatusCode == true)
                    {
                        ViewBag.Result = readTask.Result;
                    }
                    else
                    {
                        ViewBag.Result = FormatErrorString(selectedService, $"{result.StatusCode.ToString()} ({readTask.Result})");
                    }
                } catch (Exception ex) {
                    /// Поиск самого "вложенного" исключения
                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                    }
                    ViewBag.Result = FormatErrorString(selectedService, ex.Message);
                }
            }
            return(View());
        }
Пример #12
0
 internal UserInputWindow(List<object> inputQuestions, Func<ObservableCollection<object>> returnlist, IEnumerable<InputMode> eingabeModi, Dispatcher fromThread)
 {
     InitializeComponent();
     DataContext = new UserInputViewModel(inputQuestions, returnlist, () =>
     {
         DialogResult = true;
         Close();
     }, eingabeModi, fromThread);
 }
Пример #13
0
 internal UserInputWindow(List<object> inputQuestions, Func<List<object>> returnlist,
                          IEnumerable<EingabeModus> eingabeModi)
 {
     DataContext = new UserInputViewModel(inputQuestions, returnlist, () =>
         {
             DialogResult = true;
             Close();
         }, eingabeModi);
     InitializeComponent();
 }
Пример #14
0
        public IActionResult Register([FromBody] UserInputViewModel userModel)
        {
            var response = _userService.Register(userModel);

            if (response.ServiceResponse != ServiceResponseEnum.Ok)
            {
                return(StatusCode((int)HttpStatusCode.BadRequest, response.Message));
            }
            return(StatusCode((int)HttpStatusCode.OK));
        }
        public async Task <IActionResult> Post([FromBody] UserInputViewModel input)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            await _docSchedulerService.QueueDocument(input);

            return(Ok());
        }
        public async Task <IActionResult> AddNewUser([FromBody] UserInputViewModel userInputVm)
        {
            var result = await _accountService.AddNewUser(userInputVm);

            if (result)
            {
                return(Ok());
            }

            return(BadRequest());
        }
Пример #17
0
        public async Task <IActionResult> Post(UserInputViewModel viewModel)
        {
            if (User == null)
            {
                return(BadRequest());
            }

            var createdUser = await UserService.AddUser(Mapper.Map <User>(viewModel));

            return(CreatedAtAction(nameof(Get), new { id = createdUser.Id }, Mapper.Map <UserViewModel>(createdUser)));
        }
Пример #18
0
        public async Task RegisterAsync_Calls_UsersService()
        {
            //Arrange
            var user = new UserInputViewModel();

            //Act
            await _usersController.RegisterAsync(user);

            //Assert
            _mockUserService.Verify(x => x.RegisterAsync(user));
        }
Пример #19
0
        public async Task <PartialViewResult> UpsertUserModal(long?id)
        {
            UserInputViewModel model = new UserInputViewModel(new UserInputDto());

            if (id.HasValue)
            {
                var dto = await _userAppService.GetUser(id.Value);

                model = new UserInputViewModel(dto);
            }
            return(PartialView("_UpsertUserModal", model));
        }
Пример #20
0
        private UserInputViewModel GetUserInputViewModel()
        {
            var userInputViewModel = new UserInputViewModel
            {
                Email       = "*****@*****.**",
                Password    = "******",
                DisplayName = "UserTest",
                UserRole    = "testRole"
            };

            return(userInputViewModel);
        }
Пример #21
0
        private Task AddUserAsync(UserInputViewModel userViewModel)
        {
            var addUserCommand = new AddUserCommand
            {
                Email       = userViewModel.Email,
                Password    = Hash.ComputeSha256Hash(userViewModel.Password),
                DisplayName = userViewModel.DisplayName,
                UserRole    = userViewModel.UserRole
            };

            return(_mediator.Send(addUserCommand, default(CancellationToken)));
        }
Пример #22
0
 public IActionResult Put(UserInputViewModel model)
 {
     try
     {
         var user = _userService.Update(model);
         return(Ok(user));
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "Error occured in Put");
         return(BadRequest(ex.Message));
     }
 }
Пример #23
0
        public async Task <IActionResult> CompleteContacts(string name, string company, string mail, string phone, int id)
        {
            if (!ModelState.IsValid)
            {
                return(View("Contacts", UserInputService.GetUserInput(id)));
            }
            UserInputService.setContacts(name, company, mail, phone, id);
            UserInputViewModel viewModel = UserInputService.GetUserInput(id);

            Logger.LogDebug("[CompleteContacts] viewModel=|{viewModel}|", viewModel.ToString());
            BasketViewModel basketViewModel = await Configurator.ComputeConfiguration(viewModel, 1);

            return(View("Basket", basketViewModel));
        }
Пример #24
0
        public ActionResult Users_Update([DataSourceRequest]DataSourceRequest request, UserInputViewModel user)
        {
            if (ModelState.IsValid)
            {
                var entity = this.repoUsers.GetById(user.Id);
                entity.FirstName = user.FirstName;
                entity.LastName = user.LastName;
                entity.IsVet = user.IsVet;
                entity.SergeryLocation = user.SergeryLocation;

                this.repoUsers.Update(entity);
                this.repoUsers.SaveChanges();
            }

            return Json(new[] { user }.ToDataSourceResult(request, ModelState));
        }
Пример #25
0
        //private double Diametro { get { return _punta.Diametro; } }

        public ParametroPuntaViewModel(DrillTool punta)
            : base(punta)
        {
            _punta = punta;

            NumeroGiri     = new UserInputViewModel(ParametroPunta.NumeroGiri, GetValidationError, PropNumeroGiri);
            VelocitaTaglio = new UserInputViewModel(ParametroPunta.VelocitaTaglio, GetValidationError, PropVelocitaTaglio);

            AvanzamentoSincrono  = new UserInputViewModel(ParametroPunta.AvanzamentoSincrono, GetValidationError, PropAvanzamentoSincrono);
            AvanzamentoAsincrono = new UserInputViewModel(ParametroPunta.AvanzamentoAsincrono, GetValidationError, PropAvanzamentoAsincrono);

            NumeroGiri.OnSourceUpdated     += UserInput_SourceUpdated;
            VelocitaTaglio.OnSourceUpdated += UserInput_SourceUpdated;

            AvanzamentoSincrono.OnSourceUpdated  += UserInput_SourceUpdated;
            AvanzamentoAsincrono.OnSourceUpdated += UserInput_SourceUpdated;
        }
Пример #26
0
        public async Task <IActionResult> AddRole(UserInputViewModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.RedirectToAction("Index", new { invalidEmail = GlobalConstants.Empty, roleName = model.RoleName }));
            }

            var user = await this.userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(this.RedirectToAction("Index", new { invalidEmail = model.Email, roleName = model.RoleName }));
            }

            await this.userManager.AddToRoleAsync(user, model.RoleName);

            return(this.RedirectToAction("Index"));
        }
Пример #27
0
        public async Task <IActionResult> Put(int id, UserInputViewModel viewModel)
        {
            if (viewModel == null)
            {
                return(BadRequest());
            }
            var fetchedUser = await UserService.GetById(id);

            if (fetchedUser == null)
            {
                return(NotFound());
            }

            Mapper.Map(viewModel, fetchedUser);
            await UserService.UpdateUser(fetchedUser);

            return(NoContent());
        }
Пример #28
0
        public MainWindowViewModel()
        {
            WindowPlotVM  = new PlotViewModel();
            userInputVM   = new UserInputViewModel();
            HedgingToolVM = new HedgingToolViewModel(UserInputVM);
            JsonHandlerVM = new JsonHandler();

            ComponentDatatypeList = new ObservableCollection <AbstractDataProviderViewModel>()
            {
                new SimulatedDataProviderViewModel(),
                new HistoricalDataProvioderViewModel()
            };
            ComponentOptionTypeList = new ObservableCollection <String>()
            {
                "VanillaCall",
                "BasketOption"
            };

            SelectedUnderlyingAndWeights = new Dictionary <string, double>();

            ComponentExistingSharesIds = new ObservableCollection <string>(ShareTools.GetAllShareIds());
            ComponentSelectedShareIds  = new ObservableCollection <string>();
            ComponentSelectedWeights   = new ObservableCollection <double>();
            ComponentSavedOptions      = new ObservableCollection <IOption>();
            JsonHandlerVM.LoadOptions();
            foreach (VanillaCall option in JsonHandlerVM.ListVanillaCalls)
            {
                ComponentSavedOptions.Add(option);
            }
            foreach (BasketOption option in JsonHandlerVM.ListBasketOptions)
            {
                ComponentSavedOptions.Add(option);
            }

            PlotCommand = new DelegateCommand(CanPlot);

            AddShareCommand = new DelegateCommand(AddShare);

            DeleteUnderlyingsCommand = new DelegateCommand(DeleteUnderlyings);
            AddOptionCommand         = new DelegateCommand(AddOption);
            RemoveOptionCommand      = new DelegateCommand(RemoveOption);
            LoadOptionCommand        = new DelegateCommand(LoadOption);
        }
Пример #29
0
        public async Task <IActionResult> Create(UserInputViewModel input)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(input));
            }

            var user   = AutoMapperConfig.MapperInstance.Map <ApplicationUser>(input);
            var result = await this.userManager.CreateAsync(user, input.Password);

            if (!result.Succeeded)
            {
                return(this.View(input));
            }

            await this.userManager.AddToRoleAsync(user, "Driver");

            return(this.RedirectToAction("All", "Drivers"));
        }
Пример #30
0
        public async Task <bool> AddNewUser(UserInputViewModel userInputVm)
        {
            var user = new User {
                UserName = userInputVm.Username, Email = userInputVm.Email
            };
            var randomPassword = RandomString.GenerateRandomString(AppEnum.MinPasswordChar);
            var result         = await _userService.CreateAsync(user, randomPassword);

            if (!result.Succeeded)
            {
                return(false);
            }

            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    await _userService.AddUserToRolesAsync(user, userInputVm.Roles);

                    var context = _httpContextAccessor.HttpContext;
                    var code    = await _userService.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl  = _urlHelperExtension.EmailConfirmationLink(user.Id, code, context.Request.Scheme);
                    var emailOptions = new EmailOptions
                    {
                        Url      = callbackUrl,
                        Password = randomPassword,
                        UserName = userInputVm.Username
                    };

                    await _emailSender.SendEmailAsync(userInputVm.Email, "", emailOptions, EmailType.AccountConfirm);

                    transaction.Complete();
                }
                catch (Exception)
                {
                    _unitOfWork.Rollback();
                }
            }

            return(true);
        }
Пример #31
0
        public GlobalServiceModel Register(UserInputViewModel model)
        {
            if (string.IsNullOrWhiteSpace(model.Password))
            {
                return new GlobalServiceModel {
                           ServiceResponse = ServiceResponseEnum.Failed, Message = "Password is required"
                }
            }
            ;

            if (_context.AppUsers.Any(x => x.Email == model.Email))
            {
                return new GlobalServiceModel {
                           ServiceResponse = ServiceResponseEnum.Failed, Message = "Username \"" + model.Email + "\" is already taken"
                }
            }
            ;

            CreatePasswordHash(model.Password, out var passwordHash, out var passwordSalt);

            var userEntity = new AppUser
            {
                FirstName    = model.FirstName,
                LastName     = model.LastName,
                Email        = model.Email,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                PhoneNumber  = model.PhoneNumber,
                PostCode     = model.PostCode,
                City         = model.City,
                Street       = model.Street,
                HouseNumber  = model.HouseNumber,
                UserType     = UserType.User
            };

            _context.AppUsers.Add(userEntity);
            _context.SaveChanges();

            return(new GlobalServiceModel {
                ServiceResponse = ServiceResponseEnum.Ok
            });
        }
        public async Task AddUserViaApi_CompletesSuccessfully()
        {
            var client = Factory.CreateClient();

            var userViewModel = new UserInputViewModel
            {
                FirstName = "Inigo",
                LastName  = "Montoya"
            };

            var response = await client.PostAsJsonAsync("/api/users", userViewModel);

            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);

            var result = await response.Content.ReadAsStringAsync();

            var resultViewModel = JsonConvert.DeserializeObject <UserViewModel>(result);

            Assert.AreEqual(userViewModel.FirstName, resultViewModel.FirstName);
        }
Пример #33
0
        /// <summary>
        /// Queues the file names to document list by generating new document for each filename.
        /// Step 1: Get SLA from DB by UserId
        /// Step 2: Get FinishBy Time to determine, when this document should be processed and upserted
        /// into the list to be processed.
        /// Step 3: Use Parallel Foreach to utilize all the cores of the system and complete task in the loop.
        /// Step 4: Generate New Document for given filename
        /// step 5: Place the newly generated document into the list based on finish by time.
        /// </summary>
        /// <param name="input">User input.</param>
        public async Task QueueDocumentAsync(UserInputViewModel input)
        {
            var slaTier  = GetSLAByUserId(input.UserId);
            var finishBy = GetFinishByTime(slaTier);

            Parallel.ForEach(input.FileNames, fileName =>
            {
                try
                {
                    var newDoc = GetNewDocument(input.UserId, fileName, finishBy);

                    //If queue is empty, then add new document first
                    if (_docList.Count == 0)
                    {
                        _docList.AddFirst(newDoc);
                    }
                    else
                    {
                        var docLookup = _docList.FirstOrDefault(d => d.FinishBy <= finishBy);

                        if (docLookup is null)
                        {
                            _docList.AddFirst(newDoc);
                        }
                        else
                        {
                            var node = _docList.Find(docLookup);
                            _docList.AddAfter(node, newDoc);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogCritical($"Failed to Queue Document. UserId: {input.UserId}, FileName: {fileName}, ErrorMessage: {ex.Message}");
                }
            });

            await ProcessDocumentsAsync();
        }