public async Task <IEnumerable <Book> > SearchBooks( string searchValue = "", string genre = "", DateTime?startDate = null, DateTime?endDate = null, int take = 10) { var searchResponseData = ConstructSearchDate( searchValue?.ToLower(), genre?.ToLower(), startDate, endDate, take); var searchResponse = _client.Search <StringResponse>( IndexName, PostData.Serializable(searchResponseData)); if (!searchResponse.Success) { throw searchResponse.OriginalException; } var data = (JObject)JsonConvert.DeserializeObject(searchResponse.Body); var hits = data["hits"]["hits"] as JArray; var books = new List <Book>(); foreach (var hit in hits) { var source = hit["_source"].ToString(); var book = JsonSerializer.Deserialize <Book>(source); books.Add(book); } return(books); }
public IActionResult SelectMovies(string title) { string movieJSON2 = HttpContext.Session.GetString("MovieSession") ?? "empty"; string movieJSON3 = HttpContext.Session.GetString("MovieSession2") ?? "empty"; if (movieJSON2 != "empty" && movieJSON3 != "empty") { sessionMovies = JsonSerializer.Deserialize <List <Movie> >(movieJSON2); selectedMovies = JsonSerializer.Deserialize <List <Movie> >(movieJSON3); } Movie selectedMovie = sessionMovies.Where(x => x.Title == title).First(); var duplicate = selectedMovie.Title; if (!selectedMovies.Any(t => t.Title == duplicate)) { selectedMovies.Add(selectedMovie); movieJSON2 = JsonSerializer.Serialize(selectedMovies); HttpContext.Session.SetString("MovieSession2", movieJSON2); } else { return(View("ErrorPage")); } return(View("MovieList", sessionMovies)); }
public static void Announcers() { var jsonString = File.ReadAllText(@"D:\School\High School\Year 2\SDE - Software & Development\PoC\PoC - createFile\CreateFile\Hellya.json"); var weatherForecast = JsonSerializer.Deserialize <People>(jsonString); Console.WriteLine(weatherForecast); var fileData = new List <Person>(); fileData.Add(new Person(1, "Josh", "Hasselaar")); fileData.Add(new Person(2, "Yoeri", "Sanz Walter")); string json = JsonConvert.SerializeObject(fileData.ToArray()); //write string to file System.IO.File.WriteAllText(@"D:\School\High School\Year 2\SDE - Software & Development\PoC\PoC - createFile\CreateFolder_Test\personTest.json", json); Process pdfProcess = new Process(); pdfProcess.StartInfo.FileName = @"C:\Program Files (x86)\Foxit Software\Foxit Reader\Foxit Reader.exe"; pdfProcess.StartInfo.Arguments = string.Format(@"-p {0}", @"D:\D&D\Files\Project Players Handbook V1.1/Players Handbook 1.1 Back Cover - No Art"); pdfProcess.Start(); /*File.WriteAllText(@"D:\School\High School\Year 2\SDE - Software & Development\PoC\PoC - createFile\CreateFolder_Test\personTest.json", JsonConverter.SerializeObject(fileData)); * * using (var file = File.CreateText(@"D:\School\High School\Year 2\SDE - Software & Development\PoC\PoC - createFile\CreateFolder_Test\personTest.json")) * { * var serializer = new JsonSerializer(); * serializer.Serialize(file, fileData); * }*/ }
private async Task ProcessEvent(string eventName, string message) { if (_subsManager.HasSubscriptionsForEvent(eventName)) { using var scope = ServiceProvider.CreateScope(); var subscriptions = _subsManager.GetHandlersForEvent(eventName); foreach (var subscription in subscriptions) { var handler = scope.ServiceProvider.GetService(subscription.HandlerType); if (handler is null) { continue; } var eventType = _subsManager.GetEventTypeByName(eventName); var integrationEvent = JsonSerializer.Deserialize(message, eventType); var concreteType = typeof(IIntegrationEventHandler <>).MakeGenericType(eventType); await Task.Yield(); await(Task) concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent }); } } else { _logger.LogWarning("No subscription for RabbitMQ event: {EventName}", eventName); } }
private AuthTokenResponse DecryptToken(string encryptedToken, string salt) => JsonSerializer.Deserialize <AuthTokenResponse>( Encoding.UTF8.GetString( ProtectedData.Unprotect( Convert.FromBase64String(encryptedToken), Convert.FromBase64String(salt), DataProtectionScope.CurrentUser)));
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (token == null || expiry <= DateTime.Now) { using var tokenRequest = new HttpRequestMessage(HttpMethod.Post, "https://us.battle.net/oauth/token"); var clientId = Environment.GetEnvironmentVariable("BNET_CLIENTID"); var clientSecret = Environment.GetEnvironmentVariable("BNET_SECRET"); if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret)) { throw new InvalidOperationException("OAuth credentials not found"); } var authHeader = Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret)); tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", authHeader); tokenRequest.Content = new FormUrlEncodedContent(new [] { new KeyValuePair <string, string>("grant_type", "client_credentials") }); using var response = await HttpClientHelper.Client.SendAsync(tokenRequest, cancellationToken); response.EnsureSuccessStatusCode(); var tokenString = await response.Content.ReadAsStringAsync(); var tokenValue = JsonSerializer.Deserialize <TokenValue>(tokenString); token = tokenValue.AccessToken; expiry = DateTime.Now.AddSeconds((int)tokenValue.ExpiresIn); } request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); return(await base.SendAsync(request, cancellationToken)); }
public async Task <List <Family> > GetAllFamiliesAsync() { Console.WriteLine("\t\tGet all families async called"); string message = await client.GetStringAsync(uri + "/Families"); return(JsonSerializer.Deserialize <List <Family> >(message)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); try { string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var registrantDb = JsonSerializer.Deserialize <RegistrantDb>(requestBody); var organizationConnectionString = System.Environment.GetEnvironmentVariable("SQLCONNSTR_OrganizationModel"); var organizationOptions = new DbContextOptionsBuilder <PwsoContext>().UseSqlServer(organizationConnectionString ?? throw new InvalidOperationException()).Options; var organizationContext = new PwsoContext(organizationOptions); IOrganizationRepository organizationRepository = new OrganizationRepository(organizationContext); var athlete = await organizationRepository.FindAthleteByName(registrantDb.FirstName, registrantDb.LastName); var worker = new RegistrantMessageWorker(registrantDb); var registrantSQL = worker.BuildRegistrant(); var trainingConnectionString = System.Environment.GetEnvironmentVariable("SQLAZURECONNSTR_TrainingModel"); var trainingOptions = new DbContextOptionsBuilder <PwsodbContext>().UseSqlServer(trainingConnectionString ?? throw new InvalidOperationException()).Options; var trainingContext = new PwsodbContext(trainingOptions); ITrainingRepository trainingRepository = new TrainingRepository(trainingContext); await trainingRepository.AddRegistrant(registrantSQL); } catch (Exception e) { log.LogInformation(e.ToString()); return(new BadRequestResult()); } return(new OkResult()); }
public async Task <IActionResult> SaveAll(string jsonModel) { var model = JsonSerializer.Deserialize <List <ExportImportCredentialViewModel> >(jsonModel); if (model == null) { return(RedirectToAction("Index")); } var context = new ApplicationContext(); var user = await _userManager.GetUserAsync(User); foreach (var credentialToSave in model) { var newCredential = new Credential { Source = credentialToSave.Source, Login = credentialToSave.Login, Password = credentialToSave.Password, UserId = user.Id }; context.Credentials.Add(newCredential); } await context.SaveChangesAsync(); return(RedirectToAction("Index", "Credentials")); }
public Comunicacion ReadMessage() { string jsonString = File.ReadAllText("mensaje.json"); Comunicacion mensaje = JsonSerializer.Deserialize <Comunicacion>(jsonString); return(mensaje); }
public async Task <Result <PayResponseDto> > SendToPortal(PayRequestDto payRequestDto, CancellationToken cancellationToken) { var client = new RestClient(SendToPortalUrl); var request = new RestRequest { Method = Method.POST }; request.AddParameter("application/json", JsonSerializer.Serialize(payRequestDto), ParameterType.RequestBody); var result = await client.ExecuteAsync(request, cancellationToken); var response = JsonSerializer.Deserialize <PayResponseDto>(result.Content); if (result.IsSuccessful == false) { return(Result <PayResponseDto> .Failed(response.errorMessage)); } response.Url = $"{PortalUrl}/{response.token}"; return(Result <PayResponseDto> .SuccessFul(response)); }
//TODO: Make private https://github.com/aspnet/Blazor/issues/1218 public void DevToolsCallback(string messageAsJson) { if (string.IsNullOrWhiteSpace(messageAsJson)) { return; } var message = Json.Deserialize <BaseCallbackObject>(messageAsJson); switch (message?.payload?.type) { case FromJsDevToolsDetectedActionTypeName: DevToolsBrowserPluginDetected = true; break; case "COMMIT": Commit?.Invoke(null, EventArgs.Empty); break; case "JUMP_TO_STATE": case "JUMP_TO_ACTION": OnJumpToState(Json.Deserialize <JumpToStateCallback>(messageAsJson)); break; } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, [TwilioSms(AccountSidSetting = "AccountSid", AuthTokenSetting = "AuthToken")] IAsyncCollector <CreateMessageOptions> messages, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); try { var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var registrantDb = JsonSerializer.Deserialize <RegistrantDb>(requestBody); var worker = new RegistrantMessageWorker(registrantDb, System.Environment.GetEnvironmentVariable("FromPhone")); var textMessageList = worker.PrepareRegistrationText(); foreach (var textMessage in textMessageList) { await messages.AddAsync(textMessage); } } catch (Exception e) { log.LogInformation(e.ToString()); return(new BadRequestResult()); } return(new OkResult()); }
public void RunElevatedShouldEnableAlwaysRunElevatedWhenSuccessful() { // Assert Func <string, int> sendMockIPCConfigMSG = msg => { OutGoingGeneralSettings snd = JsonSerializer.Deserialize <OutGoingGeneralSettings>(msg); Assert.IsTrue(snd.GeneralSettings.RunElevated); return(0); }; Func <string, int> sendRestartAdminIPCMessage = msg => { return(0); }; Func <string, int> sendCheckForUpdatesIPCMessage = msg => { return(0); }; // Arrange GeneralViewModel viewModel = new GeneralViewModel( settingsRepository: SettingsRepository <GeneralSettings> .GetInstance(mockGeneralSettingsUtils.Object), "GeneralSettings_RunningAsAdminText", "GeneralSettings_RunningAsUserText", false, false, UpdateUIThemeMethod, sendMockIPCConfigMSG, sendRestartAdminIPCMessage, sendCheckForUpdatesIPCMessage, GeneralSettingsFileName); Assert.IsFalse(viewModel.RunElevated); // act viewModel.RunElevated = true; }
public void IsDarkThemeRadioButtonCheckedShouldThemeToDarkWhenSuccessful() { // Arrange // Assert Func <string, int> sendMockIPCConfigMSG = msg => { OutGoingGeneralSettings snd = JsonSerializer.Deserialize <OutGoingGeneralSettings>(msg); Assert.AreEqual("dark", snd.GeneralSettings.Theme); return(0); }; Func <string, int> sendRestartAdminIPCMessage = msg => { return(0); }; Func <string, int> sendCheckForUpdatesIPCMessage = msg => { return(0); }; GeneralViewModel viewModel = new GeneralViewModel( settingsRepository: SettingsRepository <GeneralSettings> .GetInstance(mockGeneralSettingsUtils.Object), "GeneralSettings_RunningAsAdminText", "GeneralSettings_RunningAsUserText", false, false, UpdateUIThemeMethod, sendMockIPCConfigMSG, sendRestartAdminIPCMessage, sendCheckForUpdatesIPCMessage, GeneralSettingsFileName); Assert.IsFalse(viewModel.IsDarkThemeRadioButtonChecked); // act viewModel.IsDarkThemeRadioButtonChecked = true; }
public static async Task <int> MakePredictionRequest(string imageFilePath) { var client = new HttpClient(); //todo Store in user secrets. client.DefaultRequestHeaders.Add("Prediction-Key", "3c11f60367a846d5b05dbdd92e2900c1"); //todo Store in AppSettings.json const string url = "https://southcentralus.api.cognitive.microsoft.com/customvision/v3.0/Prediction/cfe3f19d-c988-483a-9dc5-63275acacd49/detect/iterations/Iteration2/image"; byte[] byteData; try { byteData = GetImageAsByteArray(imageFilePath); } catch (Exception e) { Console.WriteLine(e); throw; } using var content = new ByteArrayContent(byteData); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); var response = await client.PostAsync(url, content); var json = await response.Content.ReadAsStringAsync(); var results = JsonSerializer.Deserialize <PredictionObject>(json); return(results.Predictions.Count(p => p.Probability >= 0.8M)); }
protected virtual void OnMessageHandler(RedisValue message) { countTime++; lock (mapLock) { var promiseIdActualMessageDto = JsonSerializer.Deserialize <PromiseIdActualMessageDto>(message.ToString()); var promiseId = promiseIdActualMessageDto.PromiseId; var realmsg = promiseIdActualMessageDto.ActualMessage; if (_mapper.ContainsKey(promiseId)) { var promise = _mapper[promiseId]; _mapper.Remove(promiseId); promise.Payload = realmsg; promise._OnResolveBase(); if (_mapper.Count == 0) { canClose.Release(); // to prevent another thread which calls GetPubSubServer to start a subscription while we are closing it, wait until closing thread cleans subscription before releasing mapLock canContinue.WaitOne(); } } } }
public async Task InvokeAsync(HttpContext context, RequestDelegate next) { var request = context.Request; if (!ValidMethods.Contains(request.Method)) { await next(context); return; } if (!request.Headers.ContainsKey("authorization")) { await next(context); return; } var path = context.Request.Path.Value; if (path.Contains("sign-in") || path.Contains("sign-up")) { await next(context); return; } var authenticateResult = await context.AuthenticateAsync(); if (!authenticateResult.Succeeded) { context.Response.StatusCode = 401; return; } var content = string.Empty; if (request.Body is null) { await next(context); return; } context.User = authenticateResult.Principal; using (var reader = new StreamReader(request.Body)) { content = await reader.ReadToEndAsync(); } var payload = JsonSerializer.Deserialize <Dictionary <string, object> >(content); payload["UserId"] = context.User.Identity.Name; var json = JsonSerializer.Serialize(payload); await using var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json)); context.Request.Body = memoryStream; context.Request.ContentLength = json.Length; await next(context); }
public async Task <IActionResult> ReserveSeats(string Seatstring, long TimeSlotId)//todo remove testdata { var SeatingArrangement = JsonSerializer.Deserialize <DeserializeRoot>(Seatstring); List <ReservedSeat> SeatList = new List <ReservedSeat>(); SeatingArrangement.selected.ForEach(s => { ReservedSeat ReservedSeat = new ReservedSeat { SeatId = s.seatNumber, RowId = s.GridRowId, TimeSlotId = TimeSlotId, SeatState = SeatState.Reserved }; SeatList.Add(ReservedSeat); }); if (COVID) { SeatList = await COVIDSeats(SeatList); } var PlayListList = await playListRepository.FindAllAsync(); var PlayList = PlayListList.FirstOrDefault(p => p.TimeSlotId == TimeSlotId); await seatRepository.ReserveSeats(SeatList); return(RedirectToAction("Pay", "Payment", new { id = PlayList.Id })); }
public async Task ThenThePersonCreatedEventIsRaised(ISnsFixture snsFixture) { var responseContent = await _lastResponse.Content.ReadAsStringAsync().ConfigureAwait(false); var apiPerson = JsonSerializer.Deserialize <PersonResponseObject>(responseContent, CreateJsonOptions()); Action <PersonSns> verifyFunc = (actual) => { actual.CorrelationId.Should().NotBeEmpty(); actual.DateTime.Should().BeCloseTo(DateTime.UtcNow, 1000); actual.EntityId.Should().Be(apiPerson.Id); var newData = JsonSerializer.Deserialize <Person>(responseContent, CreateJsonOptions()); var newDataAsResponse = new ResponseFactory(null).ToResponse(newData); newDataAsResponse.Should().BeEquivalentTo(apiPerson, c => c.Excluding(y => y.Links)); actual.EventType.Should().Be(CreateEventConstants.EVENTTYPE); actual.Id.Should().NotBeEmpty(); actual.SourceDomain.Should().Be(CreateEventConstants.SOURCEDOMAIN); actual.SourceSystem.Should().Be(CreateEventConstants.SOURCESYSTEM); actual.User.Email.Should().Be("*****@*****.**"); actual.User.Name.Should().Be("Tester"); actual.Version.Should().Be(CreateEventConstants.V1VERSION); }; var snsVerifer = snsFixture.GetSnsEventVerifier <PersonSns>(); var snsResult = await snsVerifer.VerifySnsEventRaised(verifyFunc); if (!snsResult && snsVerifer.LastException != null) { throw snsVerifer.LastException; } }
private List <ServerVersion> GetVanillaVersionsFromCache(Manifest.VersionType versionType) { if (vanillaDict.ContainsKey(versionType) && VanillaCacheUpToDate(versionType)) { return(vanillaDict[versionType]); } string path = Path.Combine(App.ApplicationPath, "persistence", "vanilla-" + versionType + ".json"); if (File.Exists(path)) { try { string json = File.ReadAllText(path, Encoding.UTF8); VanillaVersionCache versionCache = JsonSerializer.Deserialize <VanillaVersionCache>(json); if (DateTime.Now.Subtract(versionCache.CacheCreation).TotalHours < 12) { return(versionCache.Versions); } //TODO update visual list after updating UpdateVanillaVersionsAsync(versionType); return(versionCache.Versions); } catch (Exception e) { ErrorLogger.Append(e); Console.WriteLine("Error while reading Vanilla version cache. Skipping..."); } } UpdateVanillaVersions(versionType); return(GetVanillaVersionsFromCache(versionType)); }
public async Task <object> Get(Type type, string key, Provider?provider = null) { object res = null; try { if (string.IsNullOrWhiteSpace(key)) { return(null); } key = GetKeyName(type, key); var r = await _cache.Get(provider ?? _initProject.Provider, key); if (r == null || r?.ExpireDate < DateTime.Now) { return(null); } res = JsonSerializer.Deserialize(r?.Data ?? string.Empty, type); //res=JsonConvert.DeserializeObject(r?.Data ?? string.Empty, type); //res =((JObject) JsonConvert.DeserializeObject(r?.Data)).ToObject(type); } catch (Exception e) { //_logger.Error(e, new {key, res1}); } return(res); }
public async Task <IActionResult> ProductPage(string productId, string toReplyComment, int commentsPage, int commentsOrderingOption) { //Check if the product in question exists if (this.productService.ProductExistsById(productId) == false) { return(this.NotFound()); } var product = this.productService.GetProductById(productId, true); var viewModel = mapper.Map <ProductInfoViewModel>(product); viewModel.ProductCategories = this.categoryService.GetCategoriesForProduct(productId); //Sanitize commentsPage commentsPage = int.Parse(this.htmlEncoder.Encode(commentsPage.ToString())); var currentUserId = this.userService.GetUserId(this.User.Identity.Name); viewModel.CurrentUserId = currentUserId; //Short description viewModel.ShortDescription = this.productService.GetShordDescription(viewModel.Description, 40); //Overall product rating viewModel.ProductRating = new ProductRatingViewModel(this.productService.GetAverageRating(viewModel.ProductRatings)); await FillProductInfoViewModel(viewModel, productId, commentsPage, toReplyComment, commentsOrderingOption); //Add each model state error from the last action to this one if (TempData[GlobalConstants.ErrorsFromPOSTRequest] != null) { ModelStateHelper.MergeModelStates(TempData, this.ModelState); } object complexModel = null; var typeOfInputModel = TempData[GlobalConstants.InputModelFromPOSTRequestType]; //If input model is for adding review if (typeOfInputModel?.ToString() == nameof(AddReviewInputModel)) { complexModel = AssignViewAndInputModels <AddReviewInputModel, ProductInfoViewModel>(viewModel); } //If input model is for replying to a comment else if (typeOfInputModel?.ToString() == nameof(ReplyCommentInputModel)) { var replyCommentInputModelsJSON = TempData[GlobalConstants.InputModelFromPOSTRequest]?.ToString(); var replyCommentInputModel = JsonSerializer.Deserialize <ReplyCommentInputModel>(replyCommentInputModelsJSON); viewModel.ReplyCommentInputModel = replyCommentInputModel; complexModel = AssignViewAndInputModels <AddReviewInputModel, ProductInfoViewModel>(viewModel, true); } //If there isn't an input model else { complexModel = AssignViewAndInputModels <AddReviewInputModel, ProductInfoViewModel>(viewModel, true); } return(this.View("ProductPage", complexModel)); }
public static T GetJson <T>(this ISession session, string key) { var sessionData = session.GetString(key); return(sessionData == null ? default(T) : JsonSerializer.Deserialize <T>(sessionData)); }
public void DeserializeFromStringWithoutBOM() { var messageAsString = ConvertToString(stream, true); var returnTestObject = CoreJsonSerializer.Deserialize <TestObject>(messageAsString); Assert.Equal(testObject, returnTestObject); }
public async Task FunctionHandler_WithRequestAndContext_ReturnsNewGameName() { var response = await TestSubject.FunctionHandler(Request, Context); Game game = JsonSerializer.Deserialize <Game>(response.Body); Assert.That(game.GameName.StartsWith(GameFunction.GAME_PREFIX)); }
public async Task <IList <User> > GetAllUsersAsync(string username) { string message = await client.GetStringAsync(uri + "/users"); List <User> result = JsonSerializer.Deserialize <List <User> >(message); return(result); }
public ConfigurationService() { Serialized serialized = JsonSerializer.Deserialize <Serialized>(myConfig); token = serialized.token; prefix = serialized.prefix; imgurid = serialized.imgurid; }
public void DeserializeFromBytesWithoutBOM() { var bytes = RemoveByteOrderMarkIfFound(stream.ToArray()); var returnTestObject = CoreJsonSerializer.Deserialize <TestObject>(bytes); Assert.Equal(testObject, returnTestObject); }
public async Task <User> ValidateUserAsync(string username, string password) { Console.WriteLine("\t\t Validate user called"); HttpClient client = new HttpClient(); string response = await client.GetStringAsync($"{uri}/{username}&{password}"); return(JsonSerializer.Deserialize <User>(response)); }