/// <summary>
        /// Выполняет "умную" сериализацию в JSON (с учетом настроек протокола).
        /// </summary>
        /// <typeparam name="TValue">Тип сериализуемого объекта.</typeparam>
        /// <param name="value">Сериализуемый объект.</param>
        /// <param name="protocolSettings">Настройки протокола.</param>
        /// <param name="jsonSerializerOptions">Настройки сериализатора.</param>
        /// <returns>JSON-строка сериализованного объекта.</returns>
        public static string SerializeJson <TValue>(TValue value, ProtocolSettings protocolSettings, JsonSerializerOptions jsonSerializerOptions)
        {
            value            = value ?? throw new ArgumentNullException(nameof(value));
            protocolSettings = protocolSettings ?? throw new ArgumentNullException(nameof(protocolSettings));

            string text;

            if (typeof(TValue) == typeof(GetProgramsResponse) && protocolSettings.SingularGetProgramsResponse)
            {
                var helper = new Internal.GetProgramsResponseHelper((GetProgramsResponse)(object)value);
                helper.ProgramsPlural = null;
                text = JsonSerializer.Serialize(helper, jsonSerializerOptions);
            }
            else
            {
                text = JsonSerializer.Serialize(value, jsonSerializerOptions);
            }

            if (protocolSettings.UrlEncodedRequests && typeof(TValue).IsSubclassOf(typeof(RequestBase)))
            {
                text = System.Net.WebUtility.UrlEncode(text);
            }

            if (protocolSettings.UrlEncodedResponses && typeof(TValue).IsSubclassOf(typeof(ResponseBase)))
            {
                text = System.Net.WebUtility.UrlEncode(text);
            }

            return(text);
        }
Ejemplo n.º 2
0
        public ResponseBaseValidationTests()
        {
            ProtocolSettings = ProtocolSettings.CreateEmpty();
            Validator        = new LikePharmaValidator(ProtocolSettings);

            ValidValue.Status    = Globals.StatusSuccess;
            ValidValue.ErrorCode = Globals.ErrorCodeNoError;
#pragma warning disable CA1303 // Do not pass literals as localized parameters
            ValidValue.Message = "Hello, World";
#pragma warning restore CA1303 // Do not pass literals as localized parameters
        }
        public RegisterRequestValidationTests()
        {
            this.protocolSettings = ProtocolSettings.CreateEmpty();
            this.validator        = new LikePharmaValidator(protocolSettings);

            validValue = new RegisterRequest
            {
                PosId       = "A12BC",
                CardNumber  = "12345",
                PhoneNumber = "12345",
                TrustKey    = "abc",
            };
        }
        public ConfirmPurchaseRequestValidationTests()
        {
            this.protocolSettings = ProtocolSettings.CreateEmpty();
            this.validator        = new LikePharmaValidator(protocolSettings);

            validValue = new ConfirmPurchaseRequest
            {
                PosId        = "A12BC",
                CardNumber   = "1234567890123",
                Transactions = new List <string>()
                {
                    "abc123", "abcd1234"
                },
            };
        }
Ejemplo n.º 5
0
        public void UrlEncodingWorks(bool use)
        {
            var ps = new ProtocolSettings().UseUrlEncode(use, use);

            var json = Helper.ReformatJson(Internal.GetProgramsResponseHelperSerializationTests.ValidJsonPlural);

            json = use ? System.Net.WebUtility.UrlEncode(json) : json;

            var value = LikePharmaClient.DeserializeJson <GetProgramsResponse>(json, ps, jsonSerializerOptions);

            Validate(value, "p");

            var newJson = LikePharmaClient.SerializeJson(value, ps, jsonSerializerOptions);

            Assert.Equal(json, newJson);
        }
Ejemplo n.º 6
0
        public void SerializeGetProgramsResponseAutomatically(bool singular, string expectedJson)
        {
            var ps = new ProtocolSettings()
            {
                SingularGetProgramsResponse = singular
            };

            // вместо конструирования просто десериализуем, так проще
            var value = LikePharmaClient.DeserializeJson <GetProgramsResponse>(expectedJson, ps, jsonSerializerOptions);

            Validate(value, singular ? "s" : "p");

            var newJson = LikePharmaClient.SerializeJson(value, ps, jsonSerializerOptions);

            Assert.Equal(Helper.ReformatJson(expectedJson), newJson);
        }
        public GetDiscountRequestValidationTests()
        {
            this.protocolSettings = ProtocolSettings.CreateEmpty();
            this.validator        = new LikePharmaValidator(protocolSettings);

            validValue = new GetDiscountRequest
            {
                PosId      = PosIdAttributeTests.ValidPosIdValue,
                CardNumber = "12345",
                AnyData    = "Hello, World!",
                Orders     = new List <GetDiscountRequest.Order>
                {
                    new GetDiscountRequest.Order
                    {
                        Barcode = "1234567890123",
                        Count   = 11,
                        Price   = 123.45M,
                        AnyData = "AnyData1",
                    },
                },
            };
        }
        /// <summary>
        /// Выполняет "умную" десериализацию из JSON (с учетом настроек протокола).
        /// </summary>
        /// <typeparam name="TValue">Результирующий (целевой) тип.</typeparam>
        /// <param name="text">Сериализованный (json) объект.</param>
        /// <param name="protocolSettings">Настройки протокола.</param>
        /// <param name="jsonSerializerOptions">Настройки сериализатора.</param>
        /// <returns>Десериализованый ответ запрошенного типа.</returns>
        /// <remarks>
        /// Ответы типа <see cref="GetProgramsResponse"/> десериализуются корректно автоматически, независимо от значения <see cref="ProtocolSettings.SingularGetProgramsResponse"/>.
        /// </remarks>
        public static TValue DeserializeJson <TValue>(string text, ProtocolSettings protocolSettings, JsonSerializerOptions jsonSerializerOptions)
        {
            protocolSettings = protocolSettings ?? throw new ArgumentNullException(nameof(protocolSettings));

            if (protocolSettings.UrlEncodedRequests && typeof(TValue).IsSubclassOf(typeof(RequestBase)))
            {
                text = System.Net.WebUtility.UrlDecode(text);
            }

            if (protocolSettings.UrlEncodedResponses && typeof(TValue).IsSubclassOf(typeof(ResponseBase)))
            {
                text = System.Net.WebUtility.UrlDecode(text);
            }

            if (typeof(TValue) == typeof(GetProgramsResponse))
            {
                var helper = JsonSerializer.Deserialize <Internal.GetProgramsResponseHelper>(text, jsonSerializerOptions);
                return((TValue)(object)helper.CreateResponse());
            }

            return(JsonSerializer.Deserialize <TValue>(text, jsonSerializerOptions));
        }
Ejemplo n.º 9
0
 public ProtocolSettingsServiceProvider(ProtocolSettings protocolSettings)
 {
     this.protocolSettings = protocolSettings;
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Конструктор по умолчанию.
 /// </summary>
 /// <param name="protocolSettings"><see cref="ProtocolSettings"/>, которую необходимо использовать в процессе валидации.</param>
 public LikePharmaValidator(ProtocolSettings protocolSettings)
 {
     this.protocolSettings = protocolSettings ?? throw new ArgumentNullException(nameof(protocolSettings));
 }