Esempio n. 1
0
        public async Task <APIGatewayProxyResponse> QueryActors(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.LogLine($"Query request: {_jsonConverter.SerializeObject(request)}");

            var requestBody = _jsonConverter.DeserializeObject <ActorsSearchRequest>(request.Body);

            if (string.IsNullOrEmpty(requestBody.FirstName))
            {
                return(new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.BadRequest,
                    Body = "FirstName is mandatory"
                });
            }
            var queryRequest = BuildQueryRequest(requestBody.FirstName, requestBody.LastName);

            _logger.LogInformation("QueryActors invoked with {FirstName} and {LastName}, {@Content}",
                                   requestBody.FirstName, requestBody.LastName, requestBody);

            var response = await _dynamoDbReader.QueryAsync(queryRequest);

            context.Logger.LogLine($"Query result: {_jsonConverter.SerializeObject(response)}");

            var queryResults = BuildActorsResponse(response);

            _logger.LogInformation("QueryActors result for {FirstName} and {LastName} is {@Content}",
                                   requestBody.FirstName, requestBody.LastName, queryResults);

            return(new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body = _jsonConverter.SerializeObject(queryResults)
            });
        }
Esempio n. 2
0
        public async Task <APIGatewayProxyResponse> GetMovie(APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.LogLine($"Query request: {_jsonConverter.SerializeObject(request)}");

            var title = WebUtility.UrlDecode(request.PathParameters["title"]);

            _logger.LogInformation("GetMovie invoked with {Title}", title);

            var document = await _dynamoDbReader.GetDocumentAsync(TableName, title);

            context.Logger.LogLine($"Query response: {_jsonConverter.SerializeObject(document)}");

            if (document == null)
            {
                _logger.LogInformation("GetMovie produced no results for {Title}", title);
                return(new APIGatewayProxyResponse {
                    StatusCode = (int)HttpStatusCode.NotFound
                });
            }

            var movie = new Movie
            {
                Title = document["Title"],
                Genre = (MovieGenre)int.Parse(document["Genre"])
            };

            _logger.LogInformation("GetMovie result is {Title}, {@Content}", movie.Title, movie);

            return(new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body = _jsonConverter.SerializeObject(movie)
            });
        }
Esempio n. 3
0
        public async Task <APIGatewayCustomAuthorizerResponse> Authorize(APIGatewayCustomAuthorizerRequest request, ILambdaContext context)
        {
            context.Logger.LogLine($"Query request: {_jsonConverter.SerializeObject(request)}");

            var userInfo = await _userManager.Authorize(request.AuthorizationToken?.Replace("Bearer ", string.Empty));

            return(new APIGatewayCustomAuthorizerResponse
            {
                PrincipalID = userInfo.UserId,
                PolicyDocument = new APIGatewayCustomAuthorizerPolicy
                {
                    Version = "2012-10-17",
                    Statement = new List <APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>
                    {
                        new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement
                        {
                            Action = new HashSet <string> {
                                "execute-api:Invoke"
                            },
                            Effect = userInfo.Effect.ToString(),
                            Resource = new HashSet <string> {
                                request.MethodArn
                            }
                        }
                    }
                }
            });
        }
        protected override string SerializeObject(object o)
        {
            var sb = new StringBuilder();

            _serializer.SerializeObject(o, sb);
            var result = sb.ToString();

            return(result);
        }
Esempio n. 5
0
        public void Serialize()
        {
            var writer = new StringWriter();

            _converter.SerializeObject(_asset, writer);
            var serialized = writer.ToString();

            serialized.Should().NotBeNullOrWhiteSpace();
        }
Esempio n. 6
0
        public void SerializeObject(int value)
        {
            var stringWriter = new StringWriter();

            _converter.SerializeObject(value, stringWriter);

            var result = stringWriter.ToString();

            result.Should().Be(JsonConvert.SerializeObject(value));
        }
Esempio n. 7
0
        public void SerializeObject(Boo[] array)
        {
            var stringWriter = new StringWriter();

            _converter.SerializeObject(array, stringWriter);

            var result = stringWriter.ToString();

            result.Should().Be(JsonConvert.SerializeObject(array));
        }
Esempio n. 8
0
        public Request Compose(Params @params)
        {
            var request = _requestFactory.Get();

            request.Id     = _lastId++;
            request.Method = @params.Method;
            request.Params = @params;
            request.Json   = _jsonConverter.SerializeObject(request);
            return(request);
        }
Esempio n. 9
0
        public async Task AddBlockHeader(BlockHeader blockHeader)
        {
            var blockHeaderJson = _jsonConverter.SerializeObject(blockHeader);
            await _redisDbJsonContext.Set(blockHeader.Hash.BuildDataBlockKey(), blockHeaderJson);

            await _redisDbJsonContext.AddToIndex(RedisIndex.BlockTimestamp, blockHeader.Hash, blockHeader.Timestamp);

            await _redisDbJsonContext.AddToIndex(RedisIndex.BlockHeight, blockHeader.Hash, blockHeader.Index);
        }
Esempio n. 10
0
        /// <summary>
        /// save the open wallet into a specific filename
        /// </summary>
        /// <param name="filename">the filename</param>
        public void ExportWallet(String filename)
        {
            CheckWalletIsOpen();
            var json = _jsonConverter.SerializeObject(Wallet);

            if (String.IsNullOrWhiteSpace(json))
            {
                throw new ArgumentException("Serialization failed");
            }
            _fileWrapper.WriteToFile(json, filename);
        }
        public void Set <T>(string key, T value)
        {
            var type = typeof(T);

            var json = TypeHelper.IsPrimitiveOrString(type)
                ? string.Format(CultureInfo.InvariantCulture, "{0}", value)
                : _jsonConverter.SerializeObject(value);

            PlayerPrefs.SetString(key, json);
            PlayerPrefs.Save();
        }
        protected async Task <string> DoPostAsync <TRequest>(TRequest r11)
        {
            var request          = jsonConverter.SerializeObject(r11);
            HttpRequestMessage r = new HttpRequestMessage(HttpMethod.Post, string.Empty);

            r.Content = new StringContent(request, Encoding.UTF8, "application/json");

            var response = await this.client.SendAsync(r);

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

            return(stringContent);
        }
        public void Set <T>(string key, T value)
        {
            var type = typeof(T);

            var json = TypeHelper.IsPrimitiveOrString(type)
                ? string.Format(CultureInfo.InvariantCulture, "{0}", value)
                : _jsonConverter.SerializeObject(value);

            try
            {
                File.WriteAllText(GetPath(key), json);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
Esempio n. 14
0
        public async Task <HttpResponseMessage> AddUserToList(string email, string name, string lastname, string listId)
        {
            var sampleListMember = _jsonConverter.SerializeObject(
                new
            {
                email_address = email,
                merge_fields  =
                    new
                {
                    FNAME = name,
                    LNAME = lastname
                },
                status = "subscribed"
            });

            var hashedEmail = string.IsNullOrEmpty(email) ? "" : CalculateMD5Hash(email.ToLower());
            var uri         = string.Format("https://us16.api.mailchimp.com/3.0/lists/{0}/members/{1}", listId, hashedEmail);

            return(await _httpClient.PostAsync(uri, new JsonEncodedContent(sampleListMember)));
        }
Esempio n. 15
0
        public async Task <IActionResult> SlotGame(SlotGameViewModel model)
        {
            if (!ModelState.IsValid)
            {
                Response.StatusCode = 400;
                return(PartialView("_StatusMessage", "Error: Incorrect format!"));
            }
            var userId      = userManager.GetUserId(User);
            var balanceInfo = userServices.GetBalanceInformation(userId).Result;

            if (balanceInfo.Amount - model.Stake < 0)
            {
                Response.StatusCode = 400;
                return(PartialView("_StatusMessage", "Error: You cant bet more than what you have!"));
            }
            var usdChangeOfStake = userServices.UpdateUserBalanceByAmount(-model.Stake, userId).Result;

            transactionServices.CreateTransactionAsync(TypeOfTransaction.Stake, "Stake", usdChangeOfStake, userId).Wait();
            var gameMatrix = slotGameServices.Run(model.N, model.M);
            var coef       = slotGameServices.Evaluate(gameMatrix);
            var earnings   = model.Stake * coef;

            if (coef != 0)
            {
                var usdChangeOfEarnings = userServices.UpdateUserBalanceByAmount(earnings, userId).Result;
                transactionServices.CreateTransactionAsync(TypeOfTransaction.Win, "Win", usdChangeOfEarnings, userId).Wait();
            }
            //serialize matrix to json
            string result = jsonConverter.SerializeObject(gameMatrix, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                Formatting        = Formatting.None,
                Converters        = new List <JsonConverter> {
                    new StringEnumConverter()
                }
            });

            return(Json(result));
        }
Esempio n. 16
0
 protected override void WriteStringContent(StringBuilder builder, object[] parameterValues)
 {
     if (Target.Parameters.Count == 1 && string.IsNullOrEmpty(Target.Parameters[0].Name) && parameterValues[0] is string s)
     {
         // JsonPost with single nameless parameter means complex JsonLayout
         builder.Append(s);
     }
     else
     {
         builder.Append("{");
         string separator = string.Empty;
         for (int i = 0; i < Target.Parameters.Count; ++i)
         {
             var parameter = Target.Parameters[i];
             builder.Append(separator);
             builder.Append('"');
             builder.Append(parameter.Name);
             builder.Append("\":");
             _jsonConverter.SerializeObject(parameterValues[i], builder);
             separator = ",";
         }
         builder.Append('}');
     }
 }