Esempio n. 1
0
        public async Task ThrowError_AnonymousUserAndProductionEnvironment_ReturnsNoErrorDetails()
        {
            //Arrange
            await using var environment = await IntegrationTestEnvironment.CreateAsync(new EnvironmentSetupOptions ()
            {
                EnvironmentName = Environments.Production
            });

            //Act
            using var httpClient = new HttpClient();
            var response = await httpClient.GetAsync("http://localhost:14568/errors/throw");

            //Assert
            Assert.AreEqual(HttpStatusCode.InternalServerError, response.StatusCode);

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

            var responseObject = JsonSerializer.Deserialize <ProblemDetails>(responseString);

            Assert.AreEqual("An error occured while processing your request.", responseObject.Title);
            Assert.IsNull(responseObject.Detail);
            Assert.AreEqual(500, responseObject.Status);
        }
        public static async Task <IActionResult> GetProvincialCumulativeTimeline(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string csv = GetData("https://raw.githubusercontent.com/dsfsi/covid19za/master/data/covid19za_provincial_cumulative_timeline_confirmed.csv");

            StringBuilder stringBuilderCsv = new StringBuilder();

            stringBuilderCsv.Append(csv);

            List <ProvincialCumulativeTimeline> provincialCumulativeTimeline = new List <ProvincialCumulativeTimeline>();

            foreach (var e in new ChoCSVReader <ProvincialCumulativeTimeline>(stringBuilderCsv).WithFirstLineHeader())
            {
                provincialCumulativeTimeline.Add(e);
            }

            var json = JsonSerializer.Serialize(provincialCumulativeTimeline);

            return(new OkObjectResult(json));
        }
Esempio n. 3
0
        public async Task AddNewCINCaseStatus()
        {
            //create new case status
            var postUri = new Uri($"api/v1/residents/{_person.Id}/case-statuses", UriKind.Relative);

            var request = new CreateCaseStatusRequest()
            {
                CreatedBy = _worker.Email,
                StartDate = DateTime.Today.AddDays(-1),
                Type      = "CIN",
                PersonId  = _person.Id
            };

            var serializedRequest = JsonSerializer.Serialize(request);
            var requestContent    = new StringContent(serializedRequest, Encoding.UTF8, "application/json");

            var createCaseStatusResponse = await Client.PostAsync(postUri, requestContent).ConfigureAwait(true);

            createCaseStatusResponse.StatusCode.Should().Be(201);

            //Get request to check that the case status has been added
            var getUri = new Uri($"api/v1/residents/{_person.Id}/case-statuses", UriKind.Relative);
            var getCaseStatusesResponse = await Client.GetAsync(getUri).ConfigureAwait(true);

            getCaseStatusesResponse.StatusCode.Should().Be(200);

            var addedContent = await getCaseStatusesResponse.Content.ReadAsStringAsync().ConfigureAwait(true);

            var addedCaseStatusResponse = JsonConvert.DeserializeObject <List <CaseStatusResponse> >(addedContent).ToList();

            addedCaseStatusResponse.Count.Should().Be(1);
            addedCaseStatusResponse.Single().Answers.Should().BeEmpty();
            addedCaseStatusResponse.Single().EndDate.Should().BeNull();
            addedCaseStatusResponse.Single().Notes.Should().BeNull();
            addedCaseStatusResponse.Single().StartDate.Should().Be(request.StartDate.ToString("O"));
            addedCaseStatusResponse.Single().Type.Should().Be(request.Type);
        }
        protected async Task <HttpResponseMessage> UpdateItemAsync <TValidator>(HttpRequestMessage httpRequestMessage, string id)
            where TValidator : AbstractValidator <T>, new()
        {
            _ = httpRequestMessage ?? throw new ArgumentNullException(nameof(httpRequestMessage));

            var claimsPrincipal = await tokenValidator.ValidateTokenAsync(httpRequestMessage.Headers.Authorization);

            if (claimsPrincipal == null)
            {
                return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            var contentStream = await httpRequestMessage.Content.ReadAsStreamAsync();

            var item = await jsonTextSerializer.DeserializeObjectAsync <T>(contentStream);

            if (Guid.Parse(id) != item.Id)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            var jsonValidationResult = await jsonHttpContentValidator.ValidateJsonAsync <T, TValidator>(httpRequestMessage.Content);

            if (!jsonValidationResult.IsValid)
            {
                return(jsonValidationResult.Message);
            }

            var updatedItem = await dataRepository.UpdateItemAsync(item);

            var content = new StringContent(JsonSerializer.Serialize(updatedItem), Encoding.UTF8, ContentTypes.Application.Json);

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = content
            });
        }
Esempio n. 5
0
        public async Task <bool> UpdateS3ReaderCount(bool isFromFile)
        {
            var s3readCount = await GetFileFromS3(@"News/S3ReadCount.json");

            if (s3readCount == null)
            {
                // return new NewsCategories();
                return(false);
            }

            var s3count = DeserializeObject <NewsCategories>(s3readCount);

            var today = DateTime.Today.ToString("dd-MM-yyyy");

            today = isFromFile? $"{today}-FromFile" : today;
            var todayCount = new CategoryModel {
                CategoryId = 0, Name = today
            };

            if (s3count.Categories.Any(s => s.Name == today))
            {
                todayCount = s3count.Categories.First(s => s.Name == today);
            }
            if (todayCount != null)
            {
                s3count.Categories.Remove(todayCount);
            }

            todayCount.CategoryId = todayCount.CategoryId + 1;

            s3count.Categories.Add(todayCount);
            var jsonString = JsonSerializer.Serialize(s3count);

            await SaveFileAsync(@"News/S3ReadCount.json", jsonString);

            return(true);
        }
Esempio n. 6
0
        private async Task TimerElapsed()
        {
            using var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _auth);
            var formContent = new FormUrlEncodedContent(new[] {
                new KeyValuePair <string, string>("refresh_token", RefreshToken),
                new KeyValuePair <string, string>("grant_type", "refresh_token"),
            });
            var result = await client.PostAsync("https://accounts.spotify.com/api/token", formContent);

            if (!result.IsSuccessStatusCode)
            {
                return;
            }

            var newValues = JsonSerializer.Deserialize <SpotifyAuth>(await result.Content.ReadAsStringAsync());

            AccessToken    = newValues.AccessToken;
            TokenType      = newValues.TokenType;
            ExpiresIn      = newValues.ExpiresIn;
            Scope          = newValues.Scope;
            Service.Client = new SpotifyClient(AccessToken);
            EnableRefresh();
        }
        public async Task IncomingJson_WithOnlyAllowJsonFormatting_Succeeds()
        {
            // Arrange
            var options = new TestApiServerOptions()
                          .ConfigureServices(services => services.AddMvc(opt =>
            {
                opt.InputFormatters.Add(new PlainTextInputFormatter());
                opt.OnlyAllowJsonFormatting();
            }));

            var country = new Country
            {
                Name = BogusGenerator.Address.Country(),
                Code = BogusGenerator.Random.Enum <CountryCode>()
            };

            string json = JsonSerializer.Serialize(country);

            await using (var server = await TestApiServer.StartNewAsync(options, _logger))
            {
                var request = HttpRequestBuilder
                              .Get(CountryController.GetJsonRoute)
                              .WithJsonBody(json);

                // Act
                using (HttpResponseMessage response = await server.SendAsync(request))
                {
                    // Assert
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    Assert.Equal("application/json", response.Content.Headers.ContentType.MediaType);
                    string content = await response.Content.ReadAsStringAsync();

                    Assert.Equal(json, content);
                }
            }
        }
        public async Task ThenThePersonUpdatedEventIsRaised(PersonFixture personFixture, ISnsFixture snsFixture)
        {
            var dbPerson = await personFixture._dbContext.LoadAsync <PersonDbEntity>(personFixture.Person.Id).ConfigureAwait(false);

            Action <string, PersonDbEntity> verifyData = (dataAsString, person) =>
            {
                var dataDic = JsonSerializer.Deserialize <Dictionary <string, object> >(dataAsString, CreateJsonOptions());
                dataDic["title"].ToString().Should().Be(Enum.GetName(typeof(Title), person.Title.Value));
                dataDic["firstName"].ToString().Should().Be(person.FirstName);
                dataDic["surname"].ToString().Should().Be(person.Surname);
            };

            Action <PersonSns> verifyFunc = (actual) =>
            {
                actual.CorrelationId.Should().NotBeEmpty();
                actual.DateTime.Should().BeCloseTo(DateTime.UtcNow, 1000);
                actual.EntityId.Should().Be(personFixture.PersonId);
                verifyData(actual.EventData.OldData.ToString(), personFixture.Person);
                verifyData(actual.EventData.NewData.ToString(), dbPerson);
                actual.EventType.Should().Be(UpdatePersonConstants.EVENTTYPE);
                actual.Id.Should().NotBeEmpty();
                actual.SourceDomain.Should().Be(UpdatePersonConstants.SOURCEDOMAIN);
                actual.SourceSystem.Should().Be(UpdatePersonConstants.SOURCESYSTEM);
                actual.User.Email.Should().Be("*****@*****.**");
                actual.User.Name.Should().Be("Tester");
                actual.Version.Should().Be(UpdatePersonConstants.V1VERSION);
            };

            var snsVerifer = snsFixture.GetSnsEventVerifier <PersonSns>();
            var snsResult  = await snsVerifer.VerifySnsEventRaised(verifyFunc);

            if (!snsResult && snsVerifer.LastException != null)
            {
                throw snsVerifer.LastException;
            }
        }
        static void TestHeap2(ReadOnlySpan <byte> data)
        {
            stopwatch.Restart();
            var products = JsonSerializer.Deserialize <List <HeapProduct> >(data);

            foreach (var product in products)
            {
                foreach (var color in product.Colors)
                {
                    if (color == "red")
                    {
                        foreach (var region in product.Regions)
                        {
                            if (region.Key == "PL")
                            {
                                price += product.AvailableItems * region.Value.Value;
                            }
                        }
                    }
                }
            }

            stopwatch.Stop();
        }
Esempio n. 10
0
        static void linqy()
        {
            object[] letters = { new Leaf <int>("", 2), new Leaf <int>("", 6), new Leaf <int>("", 8) };

            int[] numbers = { 1, 2, 3, 4 };

            string[] colours = { "Red", "Blue" };


            List <object[]> chilren = new List <object[]>();

            chilren.Add(letters);

            object[] orConnected = { 'A', 'B', 'C', 1, 2, 3, 4 };
            chilren.Add(orConnected);


            var cartesianProduct = Cartesian.CartesianProduct <object>(chilren);

            foreach (var x1 in cartesianProduct)
            {
                Console.WriteLine(JsonSerializer.Serialize(x1));
            }
        }
Esempio n. 11
0
        public override async Task <AuthenticationState> GetAuthenticationStateAsync()
        {
            var identity = new ClaimsIdentity();

            if (cachedUser == null)
            {
                string userAsJson = await jsRuntime.InvokeAsync <string>("sessionStorage.getItem", "currentUser");

                if (!string.IsNullOrEmpty(userAsJson))
                {
                    cachedUser = JsonSerializer.Deserialize <User>(userAsJson);

                    identity = SetupClaimsForUser(cachedUser);
                }
            }
            else
            {
                identity = SetupClaimsForUser(cachedUser);
            }

            ClaimsPrincipal cachedClaimsPrincipal = new ClaimsPrincipal(identity);

            return(await Task.FromResult(new AuthenticationState(cachedClaimsPrincipal)));
        }
Esempio n. 12
0
        private ComplexModel <InputModelType, ViewModelType> AssignViewAndInputModels <InputModelType, ViewModelType>(ViewModelType viewModel, bool onlyViewModel = false)
        {
            //Asign view model to complex model
            var complexModel = new ComplexModel <InputModelType, ViewModelType>();

            complexModel.ViewModel = viewModel;

            if (onlyViewModel)
            {
                return(complexModel);
            }

            //Get inputModel from TempDate
            var inputModelJSON = TempData[GlobalConstants.InputModelFromPOSTRequest]?.ToString();

            //Add input model the last post action to this one
            if (inputModelJSON != null)
            {
                var inputModel = JsonSerializer.Deserialize <InputModelType>(inputModelJSON);
                complexModel.InputModel = inputModel;
            }

            return(complexModel);
        }
        public async Task SuccessfulLinkingMatchesMashResidentToSavedPersonInDb()
        {
            _unlinkedResident.SocialCareId = null;
            DatabaseContext.SaveChanges();

            var request = new UpdateMashResidentRequest {
                SocialCareId = _existingDbPerson.Id
            };
            var patchUri          = new Uri($"/api/v1/mash-resident/{_unlinkedResident.Id}", UriKind.Relative);
            var serializedRequest = JsonSerializer.Serialize(request);
            var requestContent    = new StringContent(serializedRequest, Encoding.UTF8, "application/json");

            var linkMashResidentResponse = await Client.PatchAsync(patchUri, requestContent).ConfigureAwait(true);

            linkMashResidentResponse.StatusCode.Should().Be(200);

            _unlinkedResident.SocialCareId.Should().Be(_existingDbPerson.Id);

            var content = await linkMashResidentResponse.Content.ReadAsStringAsync().ConfigureAwait(true);

            var patchMashResidentResponse = JsonConvert.DeserializeObject <MashResidentResponse>(content);

            patchMashResidentResponse.SocialCareId.Should().Be(_existingDbPerson.Id);
        }
Esempio n. 14
0
        public async Task <ActionResult <object> > Completion(int num)
        {
            // Get userName and his Versus
            var userName = User.Identity.Name;
            var versus   = await _context.Versus
                           .OrderByDescending(u => u.DateTime).FirstOrDefaultAsync(v =>
                                                                                   (v.OpponentName == userName || v.InitiatorName == userName) &&
                                                                                   (v.Status == "Active" || v.Status == "Completion" || v.Status == "Canceled"));

            if (versus == null)
            {
                return(NotFound("Активного поединка для текущего пользователя не найдено"));
            }

            // If Versus is active now
            if (versus.Status == "Active")
            {
                versus.Status = "Completion";
                if (versus.OpponentName == userName)
                {
                    versus.OpponentIterations = num;
                }
                else
                {
                    versus.InitiatorIterations = num;
                }

                _context.Entry(versus).State = EntityState.Modified;
                await _context.SaveChangesAsync();

                return(Ok());
            }
            // If Versus has "Completion" or "Canceled" status
            versus.Status = "Closed";

            //Fix Results
            if (versus.OpponentName == userName)
            {
                versus.OpponentIterations = num;
            }
            else
            {
                versus.InitiatorIterations = num;
            }

            //Define winner
            if (versus.OpponentIterations > versus.InitiatorIterations)
            {
                versus.WinnerName = versus.OpponentName;
            }
            else if (versus.InitiatorIterations > versus.OpponentIterations)
            {
                versus.WinnerName = versus.InitiatorName;
            }
            else
            {
                versus.WinnerName = "Drawn Game";
            }

            // Fix results
            await FixVersusResults(versus);

            _context.Entry(versus).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            try
            {
                string winner;
                winner = versus.WinnerName == "DrawnGame" ? "DrawnGame" : versus.WinnerName;

                //Send messages
                var socketInitId = await UserToSocket(versus.InitiatorId);

                var socketOppId = await UserToSocket(versus.OpponentId);

                if (socketInitId != null)
                {
                    await _messagesHandler.SendMessageAsync(socketInitId,
                                                            JsonSerializer.Serialize(
                                                                new Dictionary <string, string>()
                    {
                        { "Type", "Result" },
                        { "Winner", winner }
                    }));
                }
                if (socketOppId != null)
                {
                    await _messagesHandler.SendMessageAsync(socketOppId,
                                                            JsonSerializer.Serialize(
                                                                new Dictionary <string, string>()
                    {
                        { "Type", "Result" },
                        { "Winner", winner }
                    }));
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ex));
            }
        }
Esempio n. 15
0
        public async Task <ActionResult <object> > Iteration(int num)
        {
            var userName = User.Identity.Name;
            var versus   = await _context.Versus
                           .OrderByDescending(u => u.DateTime).FirstOrDefaultAsync(v =>
                                                                                   (v.OpponentName == userName || v.InitiatorName == userName) &&
                                                                                   v.Status == "Active");

            if (versus == null)
            {
                return(NotFound("Активных поединков для текущего пользователя не найдено."));
            }

            if (versus.InitiatorName == userName)
            {
                // versus.InitiatorIterations = num;
                try
                {
                    var socketId = await UserToSocket(versus.OpponentId);

                    if (socketId == null)
                    {
                        return(NotFound("Пользователь вышел из сети"));
                    }

                    await _messagesHandler.SendMessageAsync(socketId,
                                                            JsonSerializer.Serialize(
                                                                new IterationResponse
                    {
                        Type = "Iteration",
                        Num  = num
                    }));


                    // await _hubContext.Clients.User(versus.OpponentName)
                    //     .SendAsync("Send", "Iteration", num.ToString());
                }
                catch (Exception ex)
                {
                    return(StatusCode(500, ex));
                }
            }

            if (versus.OpponentName == userName)
            {
                // versus.OpponentIterations = num;
                try
                {
                    var socketId = await UserToSocket(versus.InitiatorId);

                    if (socketId == null)
                    {
                        return(NotFound("Пользователь вышел из сети"));
                    }

                    await _messagesHandler.SendMessageAsync(socketId,
                                                            JsonSerializer.Serialize(
                                                                new IterationResponse
                    {
                        Type = "Iteration",
                        Num  = num
                    }));

                    // await _hubContext.Clients.User(versus.InitiatorName)
                    //     .SendAsync("Send", "Iteration", num.ToString());
                }
                catch (Exception ex)
                {
                    return(StatusCode(500, ex));
                }
            }

            // _context.Entry(versus).State = EntityState.Modified;
            // await _context.SaveChangesAsync();

            return(Ok());
        }
Esempio n. 16
0
        public async Task <ActionResult <object> > Ready()
        {
            var userName = User.Identity.Name;
            var versus   = await _context.Versus
                           .OrderByDescending(u => u.DateTime)
                           .FirstOrDefaultAsync(v =>
                                                (v.OpponentName == userName || v.InitiatorName == userName) &&
                                                (v.Status == "Preparing" || v.Status == "Ready" || v.Status == "BotReady"));

            if (versus == null)
            {
                return(NotFound("Поединки для текущего пользователя отсутствуют или недействительны"));
            }

            if (versus.Status == "Ready")
            {
                versus.Status = "Active";
                _context.Entry(versus).State = EntityState.Modified;
                await _context.SaveChangesAsync();

                try
                {
                    var socketInitId = await UserToSocket(versus.InitiatorId);

                    var socketOppId = await UserToSocket(versus.OpponentId);

                    if (socketInitId != null && socketOppId != null)
                    {
                        await _messagesHandler.SendMessageAsync(socketInitId,
                                                                JsonSerializer.Serialize(
                                                                    new Dictionary <string, string>()
                        {
                            { "Type", "Start" },
                        }));

                        await _messagesHandler.SendMessageAsync(socketOppId,
                                                                JsonSerializer.Serialize(
                                                                    new Dictionary <string, string>()
                        {
                            { "Type", "Start" },
                        }));

                        return(Ok());
                    }
                    return(NotFound("Пользователь вышел из сети"));
                }
                catch (Exception ex)
                {
                    return(StatusCode(500, ex));
                }
            }
            else if (versus.Status == "BotReady")
            {
                versus.Status = "BotActive";
                _context.Entry(versus).State = EntityState.Modified;
                await _context.SaveChangesAsync();

                try
                {
                    var socketInitId = await UserToSocket(versus.InitiatorId);

                    if (socketInitId != null)
                    {
                        await _messagesHandler.SendMessageAsync(socketInitId,
                                                                JsonSerializer.Serialize(
                                                                    new Dictionary <string, string>()
                        {
                            { "Type", "Start" },
                        }));

                        return(Ok());
                    }
                    return(BadRequest("Ошибка отправки сообщения"));
                }
                catch (Exception ex)
                {
                    return(StatusCode(500, ex));
                }
            }
            else if (versus.Status == "Preparing")
            {
                versus.Status = "Ready";
                _context.Entry(versus).State = EntityState.Modified;
                await _context.SaveChangesAsync();

                try
                {
                    var socketId = await UserToSocket(versus.InitiatorName == userName?
                                                      versus.OpponentId : versus.InitiatorId);

                    if (socketId != null)
                    {
                        await _messagesHandler.SendMessageAsync(socketId,
                                                                JsonSerializer.Serialize(
                                                                    new Dictionary <string, string>()
                        {
                            { "Type", "Ready" },
                            { "UserName", userName }
                        }));

                        return(Ok());
                    }
                    return(NotFound("Пользователь вышел из сети"));
                }
                catch (Exception ex)
                {
                    return(StatusCode(500, ex));
                }
            }
            else
            {
                return(StatusCode(409, "Неподходящий статус поединка"));
            }
        }
Esempio n. 17
0
 private StringContent GetStringContent(object data)
 {
     return(new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json"));
 }
        public async Task UpdateWorkerWithNewTeamUpdatesAnyAllocationsAssociated()
        {
            // Create an allocation request for existingDbWorker
            var createAllocationUri = new Uri("/api/v1/allocations", UriKind.Relative);

            var allocationRequest = IntegrationTestHelpers.CreateAllocationRequest(_resident.Id, _existingDbTeam.Id, _existingDbWorker.Id, _allocationWorker);
            var serializedRequest = JsonSerializer.Serialize(allocationRequest);

            var requestContent = new StringContent(serializedRequest, Encoding.UTF8, "application/json");

            var allocationResponse = await Client.PostAsync(createAllocationUri, requestContent).ConfigureAwait(true);

            allocationResponse.StatusCode.Should().Be(201);

            // Create another allocation request for existingDbWorker
            var secondAllocationRequest = IntegrationTestHelpers.CreateAllocationRequest(_resident.Id, _existingDbTeam.Id, _existingDbWorker.Id, _allocationWorker);
            var secondSerializedRequest = JsonSerializer.Serialize(secondAllocationRequest);

            var secondRequestContent = new StringContent(secondSerializedRequest, Encoding.UTF8, "application/json");

            var allocationTwoResponse = await Client.PostAsync(createAllocationUri, secondRequestContent).ConfigureAwait(true);

            allocationTwoResponse.StatusCode.Should().Be(201);

            // Patch request to update team of existingDbWorker
            var patchUri = new Uri("/api/v1/workers", UriKind.Relative);

            var newTeamRequest = new WorkerTeamRequest {
                Id = _differentDbTeam.Id, Name = _differentDbTeam.Name
            };
            var patchRequest = IntegrationTestHelpers.CreatePatchRequest(_existingDbWorker, newTeamRequest);
            var patchTeamSerializedRequest = JsonSerializer.Serialize(patchRequest);

            var patchRequestContent = new StringContent(patchTeamSerializedRequest, Encoding.UTF8, "application/json");
            var patchWorkerResponse = await Client.PatchAsync(patchUri, patchRequestContent).ConfigureAwait(true);

            patchWorkerResponse.StatusCode.Should().Be(204);

            // Get request to check team has been updated on existingDbWorker's allocations
            var getAllocationsUri      = new Uri($"/api/v1/allocations?mosaic_id={_resident.Id}", UriKind.Relative);
            var getAllocationsResponse = await Client.GetAsync(getAllocationsUri).ConfigureAwait(true);

            getAllocationsResponse.StatusCode.Should().Be(200);

            var allocationsContent = await getAllocationsResponse.Content.ReadAsStringAsync().ConfigureAwait(true);

            var updatedAllocationResponse = JsonConvert.DeserializeObject <AllocationList>(allocationsContent);

            updatedAllocationResponse.Allocations.Count.Should().Be(2);

            var firstAllocation = updatedAllocationResponse.Allocations.ElementAtOrDefault(0);

            firstAllocation?.AllocatedWorkerTeam.Should().Be(newTeamRequest.Name);
            firstAllocation?.PersonId.Should().Be(_resident.Id);
            firstAllocation?.AllocatedWorker.Should().Be($"{_existingDbWorker.FirstName} {_existingDbWorker.LastName}");

            var secondAllocation = updatedAllocationResponse.Allocations.ElementAtOrDefault(1);

            secondAllocation?.AllocatedWorkerTeam.Should().Be(newTeamRequest.Name);
            secondAllocation?.PersonId.Should().Be(_resident.Id);
            secondAllocation?.AllocatedWorker.Should().Be($"{_existingDbWorker.FirstName} {_existingDbWorker.LastName}");
        }
Esempio n. 19
0
        public static void SystemTextJson()
        {
            var json = SystemTextJsonSerializer.Serialize(SignUpScenario.MutableObject, JsonSettings.SystemTextJsonOptions);

            json.Should().Be(SignUpScenario.Json);
        }
Esempio n. 20
0
        public static List <User> ReadJsonUser(string jsonFileName)
        {
            string jsonString = File.ReadAllText(jsonFileName);

            return(JsonSerializer.Deserialize <List <User> >(jsonString));
        }
Esempio n. 21
0
        public static List <Ware> ReadJsonWare(string JsonFileName)
        {
            string jsonString = File.ReadAllText(JsonFileName);

            return(JsonSerializer.Deserialize <List <Ware> >(jsonString));
        }
        public async Task EndLACCaseStatusThatHasScheduledAnswers()
        {
            //create new LAC case status, start date 12/01/2000
            var postUri = new Uri($"api/v1/residents/{_person.Id}/case-statuses", UriKind.Relative);

            var answers = CaseStatusHelper.CreateCaseStatusRequestAnswers(min: 2, max: 2);

            var request = CaseStatusHelper.CreateCaseStatusRequest(
                personId: _person.Id,
                type: "LAC",
                answers: answers,
                startDate: new DateTime(2000, 01, 12),
                createdBy: _worker.Email
                );

            request.Notes = null;

            var requestContent = new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json");

            var createCaseStatusResponse = await Client.PostAsync(postUri, requestContent).ConfigureAwait(true);

            createCaseStatusResponse.StatusCode.Should().Be(201);

            //Get request to check that the case status has been added
            var getUri = new Uri($"api/v1/residents/{_person.Id}/case-statuses", UriKind.Relative);
            var getCaseStatusesResponse = await Client.GetAsync(getUri).ConfigureAwait(true);

            getCaseStatusesResponse.StatusCode.Should().Be(200);

            var addedContent = await getCaseStatusesResponse.Content.ReadAsStringAsync().ConfigureAwait(true);

            var addedCaseStatusResponse = JsonConvert.DeserializeObject <List <CaseStatusResponse> >(addedContent).ToList();

            addedCaseStatusResponse.Count.Should().Be(1);
            addedCaseStatusResponse.Single().Answers.Count.Should().Be(2);
            addedCaseStatusResponse.Single().EndDate.Should().BeNull();
            addedCaseStatusResponse.Single().Notes.Should().BeNull();
            addedCaseStatusResponse.Single().StartDate.Should().Be(request.StartDate.ToString("O"));
            addedCaseStatusResponse.Single().Type.Should().Be(request.Type);

            //patch request to update the start date to 11/01/2000
            var caseStatusId = addedCaseStatusResponse.First().Id;

            var patchUri = new Uri($"api/v1/case-statuses/{caseStatusId}", UriKind.Relative);

            var patchRequest = TestHelpers.CreateUpdateCaseStatusRequest(startDate: new DateTime(2000, 01, 11), email: _worker.Email, caseStatusId: caseStatusId, min: 2, max: 2);

            patchRequest.Notes   = null;
            patchRequest.EndDate = null;

            var patchRequestContent = new StringContent(JsonSerializer.Serialize(patchRequest), Encoding.UTF8, "application/json");

            var patchStatusResponse = await Client.PatchAsync(patchUri, patchRequestContent).ConfigureAwait(true);

            patchStatusResponse.StatusCode.Should().Be(200);

            //Get request to check that the case status was update
            var getCaseStatusesResponseAfterUpdate = await Client.GetAsync(getUri).ConfigureAwait(true);

            getCaseStatusesResponseAfterUpdate.StatusCode.Should().Be(200);

            var updateContent = await getCaseStatusesResponseAfterUpdate.Content.ReadAsStringAsync().ConfigureAwait(true);

            var updatedCaseStatusResponse = JsonConvert.DeserializeObject <List <CaseStatusResponse> >(updateContent).ToList();

            updatedCaseStatusResponse.Count.Should().Be(1);
            updatedCaseStatusResponse.Single().Answers.Count.Should().Be(2);
            updatedCaseStatusResponse.Single().EndDate.Should().BeNull();
            updatedCaseStatusResponse.Single().Notes.Should().BeNull();
            updatedCaseStatusResponse.Single().StartDate.Should().Be(patchRequest.StartDate?.ToString("O"));
            updatedCaseStatusResponse.Single().Type.Should().Be(request.Type);

            //add new scheduled answer
            var postScheduledAnswersUri = new Uri($"api/v1/case-statuses/{caseStatusId}/answers", UriKind.Relative);

            var addScheduledAnswersRequest = CaseStatusHelper.CreateCaseStatusAnswerRequest(
                caseStatusId: caseStatusId,
                startDate: new DateTime(2040, 02, 01),
                createdBy: _worker.Email
                );

            request.Notes = null;

            var scheduledAnswersRequestContent = new StringContent(JsonSerializer.Serialize(addScheduledAnswersRequest), Encoding.UTF8, "application/json");

            var createScheduledAnswersResponse = await Client.PostAsync(postScheduledAnswersUri, scheduledAnswersRequestContent).ConfigureAwait(true);

            createScheduledAnswersResponse.StatusCode.Should().Be(201);

            //Get request to check that the scheduled answers were added
            var getCaseStatusesResponseAfterScheduledUpdate = await Client.GetAsync(getUri).ConfigureAwait(true);

            getCaseStatusesResponseAfterScheduledUpdate.StatusCode.Should().Be(200);

            var updatedContentWithScheduledStatus = await getCaseStatusesResponseAfterScheduledUpdate.Content.ReadAsStringAsync().ConfigureAwait(true);

            var updatedCaseStatusWithScheduledStatusResponse = JsonConvert.DeserializeObject <List <CaseStatusResponse> >(updatedContentWithScheduledStatus).ToList();

            updatedCaseStatusWithScheduledStatusResponse.Count.Should().Be(1);
            updatedCaseStatusWithScheduledStatusResponse.Single().Answers.Count.Should().Be(5);
            updatedCaseStatusWithScheduledStatusResponse.Single().Answers.Where(x => x.Option != CaseStatusAnswerOption.EpisodeReason).Last().StartDate.Should().Be(addScheduledAnswersRequest.StartDate);

            //patch case status to end it
            var endRequest = TestHelpers.CreateUpdateCaseStatusRequest(endDate: new DateTime(2000, 01, 11), email: _worker.Email, caseStatusId: caseStatusId, min: 1, max: 1);

            patchRequest.Notes     = null;
            patchRequest.StartDate = null;

            var serialisedEndRequest = JsonSerializer.Serialize(endRequest);
            var endRequestContent    = new StringContent(serialisedEndRequest, Encoding.UTF8, "application/json");

            var endStatusResponse = await Client.PatchAsync(patchUri, endRequestContent).ConfigureAwait(true);

            endStatusResponse.StatusCode.Should().Be(200);

            //get request to check that the case has been closed (end point only returns active ones at the moment)
            var getCaseStatusesResponseAfterEnd = await Client.GetAsync(getUri).ConfigureAwait(true);

            getCaseStatusesResponseAfterEnd.StatusCode.Should().Be(200);

            var contentAfterContent = await getCaseStatusesResponseAfterEnd.Content.ReadAsStringAsync().ConfigureAwait(true);

            var endCaseStatusResponse = JsonConvert.DeserializeObject <List <CaseStatusResponse> >(contentAfterContent).ToList();

            endCaseStatusResponse.Count.Should().Be(0);
        }
Esempio n. 23
0
        static async Task Main(string[] args)
        {
            // create an object graph
            var people = new List <Person>
            {
                new Person(30000M)
                {
                    FirstName = "Alice",
                    LastName  = "Smith", DateOfBirth = new DateTime(1974, 3, 14)
                },
                new Person(40000M)
                {
                    FirstName   = "Bob", LastName = "Jones",
                    DateOfBirth = new DateTime(1969, 11, 23)
                },
                new Person(20000M)
                {
                    FirstName   = "Charlie", LastName = "Cox",
                    DateOfBirth = new DateTime(1984, 5, 4),
                    Children    = new HashSet <Person>
                    {
                        new Person(0M)
                        {
                            FirstName   = "Sally", LastName = "Cox",
                            DateOfBirth = new DateTime(2000, 7, 12)
                        }
                    }
                }
            };

            // create object that will format a List of Persons as XML
            var xs = new XmlSerializer(typeof(List <Person>));

            // create a file to write to
            string path = Combine(CurrentDirectory, "people.xml");

            using (FileStream stream = File.Create(path))
            {
                // serialize the object graph to the stream
                xs.Serialize(stream, people);
            }

            WriteLine("Written {0:N0} bytes of XML to {1}",
                      arg0: new FileInfo(path).Length,
                      arg1: path);

            WriteLine();

            // Display the serialized object graph
            WriteLine(File.ReadAllText(path));

            // Deserializing with XML

            using (FileStream xmlLoad = File.Open(path, FileMode.Open))
            {
                // deserialize and cast the object graph into a List of Person
                var loadedPeople = (List <Person>)xs.Deserialize(xmlLoad);

                foreach (var item in loadedPeople)
                {
                    WriteLine("{0} has {1} children.",
                              item.LastName, item.Children.Count ?? 0);
                }
            }

            // create a file to write to
            string jsonPath = Combine(CurrentDirectory, "people.json");

            using (StreamWriter jsonStream = File.CreateText(jsonPath))
            {
                // create an object that will format as JSON
                var jss = new Newtonsoft.Json.JsonSerializer();

                // serialize the object graph into a string
                jss.Serialize(jsonStream, people);
            }

            WriteLine();
            WriteLine("Written {0:N0} bytes of JSON to: {1}",
                      arg0: new FileInfo(jsonPath).Length,
                      arg1: jsonPath);

            // Display the serialized object graph
            WriteLine(File.ReadAllText(jsonPath));

            // Deserializing JSON using new APIs

            using (FileStream jsonLoad = File.Open(
                       jsonPath, FileMode.Open))
            {
                // deserialize object graph into a List of Person
                var loadedPeople = (List <Person>)
                                   await NuJson.DeserializeAsync(
                    utf8Json : jsonLoad,
                    returnType : typeof(List <Person>));

                foreach (var item in loadedPeople)
                {
                    WriteLine("{0} has {1} children.",
                              item.LastName, item.Children?.Count ?? 0);
                }
            }
        }
Esempio n. 24
0
        public async Task <ActionResult <object> > CompletionWithBot(int num, int botNum)
        {
            // Get userName and his Versus
            var userName = User.Identity.Name;
            var versus   = await _context.Versus
                           .OrderByDescending(u => u.DateTime).FirstOrDefaultAsync(v =>
                                                                                   (v.OpponentName == userName || v.InitiatorName == userName) &&
                                                                                   v.Status == "BotActive");

            if (versus == null)
            {
                return(NotFound("Активного поединка с ботом для текущего пользователя не найдено"));
            }

            // If Versus is active now
            if (versus.Status == "BotActive")
            {
                versus.Status = "Closed";

                versus.InitiatorIterations = num;

                //Define winner
                if (botNum > versus.InitiatorIterations)
                {
                    versus.WinnerName = "Bot";
                }
                else if (versus.InitiatorIterations > botNum)
                {
                    versus.WinnerName = versus.InitiatorName;
                }
                else
                {
                    versus.WinnerName = "Drawn Game";
                }

                // Fix results
                await FixUserResults(
                    versus.InitiatorId,
                    versus.WinnerName == versus.InitiatorName,
                    versus.Exercise,
                    num);

                _context.Entry(versus).State = EntityState.Modified;
                await _context.SaveChangesAsync();

                try
                {
                    string winner;
                    winner = versus.WinnerName == "DrawnGame" ? "DrawnGame" : versus.WinnerName;

                    //Send messages
                    var socketInitId = await UserToSocket(versus.InitiatorId);

                    if (socketInitId != null)
                    {
                        await _messagesHandler.SendMessageAsync(socketInitId,
                                                                JsonSerializer.Serialize(
                                                                    new Dictionary <string, string>()
                        {
                            { "Type", "Result" },
                            { "Winner", winner }
                        }));
                    }
                    return(Ok());
                }
                catch (Exception ex)
                {
                    return(StatusCode(500, ex));
                }
            }
            else
            {
                return(StatusCode(409, "Неподходящий статус поединка"));
            }
        }
Esempio n. 25
0
        public async Task <ActionResult <object> > InviteFriend(string exercise, string userName)
        {
            var opponent = await _userManager.FindByNameAsync(userName);

            if (opponent == null)
            {
                return(NotFound("Оппонент не найден"));
            }

            var user = await _userManager.FindByNameAsync(User.Identity.Name);

            _context.Versus.Add(new Data.Entities.Versus
            {
                DateTime            = DateTime.Now,
                InitiatorId         = user.Id,
                InitiatorName       = user.UserName,
                Exercise            = exercise,
                Status              = "Searching",
                InitiatorIterations = 0,
                OpponentIterations  = 0,
                LastInvitedId       = opponent.Id
            });

            await _context.SaveChangesAsync();

            try
            {
                if (opponent.Online)
                {
                    var socketId = await UserToSocket(opponent.Id);

                    if (socketId != null)
                    {
                        await _messagesHandler.SendMessageAsync(socketId,
                                                                JsonSerializer.Serialize(
                                                                    new Dictionary <string, string>()
                        {
                            { "Type", "InviteFriend" },
                            { "Exercise", exercise },
                            { "UserName", user.UserName }
                        }));
                    }
                }
                else
                {
                    var result = await _mmc.SendAndroidNotification(opponent.Token, "Приглашение",
                                                                    user.UserName + " зовет вас на поединок",
                                                                    new Dictionary <string, string>
                    {
                        { "Type", "Invite" },
                        { "Exercise", exercise },
                        { "UserName", user.UserName }
                    });

                    return(Ok(result));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("An errof while send invite message " + ex.Message);
                return(StatusCode(500, ex));
            }

            return(Ok());
        }
Esempio n. 26
0
        /// <inheritdoc />
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            string modelBindingKey;

            if (bindingContext.IsTopLevelObject)
            {
                modelBindingKey = bindingContext.BinderModelName ?? string.Empty;
            }
            else
            {
                modelBindingKey = bindingContext.ModelName;
            }

            // Check the value sent in
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (valueProviderResult != ValueProviderResult.None)
            {
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

                // Attempt to convert the input value
                var valueAsString = valueProviderResult.FirstValue;

                object result;
                if (_jsonOptions != null)
                {
                    try {
                        result = JsonSerializer.Deserialize(valueAsString, bindingContext.ModelType,
                                                            _jsonOptions.Value.JsonSerializerOptions);
                    }
                    catch (JsonException e) {
                        bindingContext.ModelState.AddModelError(modelBindingKey, e, bindingContext.ModelMetadata);
                        return(Task.CompletedTask);
                    }
                }
                else if (_newtonsoftJsonOptions != null)
                {
                    try {
                        result = JsonConvert.DeserializeObject(valueAsString, bindingContext.ModelType,
                                                               _newtonsoftJsonOptions.Value.SerializerSettings);
                    }
                    catch (JsonReaderException e) {
                        bindingContext.ModelState.TryAddModelException(modelBindingKey, e);
                        return(Task.CompletedTask);
                    }
                }
                else
                {
                    try {
                        result = JsonSerializer.Deserialize(valueAsString, bindingContext.ModelType);
                    }
                    catch (JsonException e) {
                        bindingContext.ModelState.TryAddModelException(modelBindingKey, e);
                        return(Task.CompletedTask);
                    }
                }

                if (result != null)
                {
                    bindingContext.Result = ModelBindingResult.Success(result);
                    return(Task.CompletedTask);
                }
            }

            return(Task.CompletedTask);
        }
Esempio n. 27
0
        static async Task Main(string[] args)
        {
            var services = new ServiceCollection();

            services.AddMemoryCache();

            // CQRSLite

            services.AddSingleton(new Router());

            services.AddSingleton <ICommandSender>(y => y.GetService <Router>());
            services.AddSingleton <IEventPublisher>(y => y.GetService <Router>());
            services.AddSingleton <IHandlerRegistrar>(y => y.GetService <Router>());
            services.AddSingleton <IQueryProcessor>(y => y.GetService <Router>());

            services.AddSingleton <IEventStore, InMemoryEventStore>();

            services.AddSingleton <ICache, MemoryCache>();

            services.AddScoped <IRepository>(y => new CacheRepository(new Repository(y.GetService <IEventStore>()), y.GetService <IEventStore>(), y.GetService <ICache>()));

            services.AddScoped <ISession, Session>();

            // Scan for CommandHandlers and EventHandlers

            services.Scan(scan => scan
                          .FromAssemblies(typeof(Program).GetTypeInfo().Assembly)
                          .AddClasses(classes => classes.Where(x =>
            {
                var allInterfaces = x.GetInterfaces();
                return
                (allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IHandler <>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICancellableHandler <>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IQueryHandler <,>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICancellableQueryHandler <,>)));
            }))
                          .AsSelf()
                          .WithTransientLifetime());

            var provider = services.BuildServiceProvider();

            var registrar = new RouteRegistrar(provider);


            registrar.RegisterInAssemblyOf(typeof(Program));

            //
            // Execute

            var commandSender  = provider.GetRequiredService <ICommandSender>();
            var queryProcessor = provider.GetRequiredService <IQueryProcessor>();

            //

            var aggregateId = Guid.NewGuid();

            var createTopicCommand = new CreateTopicCommand(aggregateId, "Hello World!", "This is the initial post");

            await commandSender.Send(createTopicCommand);

            // Get the read model

            var data = await queryProcessor.Query(new GetTopicByIdQuery(aggregateId));

            Console.WriteLine(JsonSerializer.Serialize(data));

            //

            var       tasks = new List <Task>();
            const int limit = 499;

            for (var i = 0; i < limit; i++)
            {
                var replyToTopicCommand = new ReplyToTopicCommand(aggregateId, $"This is a reply #{i}", DateTime.UtcNow.AddDays(limit * -1 + i), data.Version);

                tasks.Add(commandSender.Send(replyToTopicCommand));
            }

            await Task.WhenAll(tasks);

            //

            data = await queryProcessor.Query(new GetTopicByIdQuery(aggregateId));

            Console.WriteLine(JsonSerializer.Serialize(data));

            Console.WriteLine("DONE!");
            Console.ReadKey();
        }
        async Task <IEnumerable <(EntityEntry EntityEntry, Audit Audit)> > OnBeforeSaveChanges()
        {
            if (!_auditSettings.Enabled)
            {
                return(null);
            }

            ChangeTracker.DetectChanges();
            var entitiesToTrack = ChangeTracker.Entries().Where(
                e => !(e.Entity is Audit) && e.State != EntityState.Detached && e.State != EntityState.Unchanged);

            foreach (var entityEntry in entitiesToTrack.Where(e => !e.Properties.Any(p => p.IsTemporary)))
            {
                var auditExcludedProps = entityEntry.Entity.GetType()
                                         .GetProperties()
                                         .Where(
                    p => p.GetCustomAttributes(
                        typeof(DoNotAudit),
                        false).Any())
                                         .Select(p => p.Name)
                                         .ToList();


                await Audits.AddRangeAsync(
                    new Audit
                {
                    Table     = entityEntry.Metadata.GetTableName(),
                    Date      = DateTime.Now.ToUniversalTime(),
                    UserId    = _currentUser.Id,
                    UserName  = _currentUser.Name,
                    KeyValues = JsonSerializer.Serialize(
                        entityEntry.Properties.Where(p => p.Metadata.IsPrimaryKey()).ToDictionary(
                            p => p.Metadata.Name,
                            p => p.CurrentValue)),
                    NewValues = JsonSerializer.Serialize(
                        entityEntry.Properties.Where(
                            p => entityEntry.State == EntityState.Added ||
                            entityEntry.State == EntityState.Modified &&
                            !auditExcludedProps.Contains(p.Metadata.Name))
                        .ToDictionary(
                            p => p.Metadata.Name,
                            p => p.CurrentValue)),
                    OldValues = JsonSerializer.Serialize(
                        entityEntry.Properties.Where(
                            p => entityEntry.State == EntityState.Deleted ||
                            entityEntry.State == EntityState.Modified &&
                            !auditExcludedProps.Contains(p.Metadata.Name))
                        .ToDictionary(
                            p => p.Metadata.Name,
                            p => p.OriginalValue))
                });
            }

            var returnList = new List <(EntityEntry EntityEntry, Audit Audit)>();

            foreach (var entityEntry in entitiesToTrack.Where(e => e.Properties.Any(p => p.IsTemporary)))
            {
                var auditExcludedProps = entityEntry.Entity.GetType()
                                         .GetProperties()
                                         .Where(
                    p => p.GetCustomAttributes(
                        typeof(DoNotAudit),
                        false).Any())
                                         .Select(p => p.Name)
                                         .ToList();

                returnList.Add(
                    (entityEntry,
                     new Audit
                {
                    Table = entityEntry.Metadata.GetTableName(),
                    Date = DateTime.Now.ToUniversalTime(),
                    UserId = _currentUser.Id,
                    UserName = _currentUser.Name,
                    NewValues = JsonSerializer.Serialize(
                        entityEntry.Properties.Where(
                            p => !p.Metadata.IsPrimaryKey() &&
                            !auditExcludedProps.Contains(p.Metadata.Name)).ToDictionary(
                            p => p.Metadata.Name,
                            p => p.CurrentValue))
                }
                    ));
            }

            return(returnList);
        }
Esempio n. 29
0
 public static T MapObject <T>(this string json)
 {
     return(JsonSerializer.Deserialize <T>(json));
 }
Esempio n. 30
0
 public void ToSystemTextJson()
 {
     var result = JsonSerializer.Serialize(WeatherForecast);
 }