Example #1
0
        public void ApiValidator_OtherValidationConditionsNotMet_ReturnsFalse()
        {
            // Arrange
            var entity = new TestEntity
            {
                IdentificationNumber = "123456789012345678901",
                Name            = "something",
                Rating          = 0,
                NonNullableDate = DateTime.Now,
                NullableDate    = DateTime.Now
            };

            // Act
            var result = ApiValidator.ValidateObject(entity, out var errors);

            // Assert
            Assert.False(result);
            Assert.AreEqual(4, errors.Count);
            var memberNames = errors.SelectMany(error => error.MemberNames).ToList();

            Assert.Contains(nameof(TestEntity.IdentificationNumber), memberNames);
            Assert.Contains(nameof(TestEntity.Rating), memberNames);
            Assert.Contains(nameof(TestEntity.NonNullableDate), memberNames);
            Assert.Contains(nameof(TestEntity.NullableDate), memberNames);
        }
Example #2
0
        private ErrorResponse ValidateRequest(RegisterRequest data)
        {
            if (!ApiValidator.ValidateFirstName(data.FirstName, out ErrorResponse error))
            {
                return(error);
            }

            if (!ApiValidator.ValidateLastName(data.LastName, out error))
            {
                return(error);
            }

            if (!ApiValidator.ValidatePhone(data.Phone, out error))
            {
                return(error);
            }

            if (!ApiValidator.ValidatePinCode(data.PinCode, out error))
            {
                return(error);
            }

            if (!ApiValidator.ValidateLinkParameter(data.LinkParameter, out error))
            {
                return(error);
            }

            ApiValidator.ValidatePlaceId(data.PlaceToJoinId, out error);
            return(error);
        }
        /// <summary>
        /// 准备请求数据
        /// </summary>
        /// <returns></returns>
        private async Task PrepareRequestAsync()
        {
            var apiAction        = this.ApiActionDescriptor;
            var validateProperty = this.HttpApiConfig.UseParameterPropertyValidate;

            foreach (var parameter in apiAction.Parameters)
            {
                ApiValidator.ValidateParameter(parameter, validateProperty);
            }

            foreach (var actionAttribute in apiAction.Attributes)
            {
                await actionAttribute.BeforeRequestAsync(this).ConfigureAwait(false);
            }

            foreach (var parameter in apiAction.Parameters)
            {
                foreach (var parameterAttribute in parameter.Attributes)
                {
                    await parameterAttribute.BeforeRequestAsync(this, parameter).ConfigureAwait(false);
                }
            }

            await apiAction.Return.Attribute.BeforeRequestAsync(this).ConfigureAwait(false);
        }
Example #4
0
        static void Main(string[] args)
        {
            var authClient = new OAuthClient("*****@*****.**", "password");
            var apiContext = new ApiContext(authClient.GetSecureToken())
            {
                AppName = "Application name",
            };

            var api = new ApiExplorer(apiContext);

            // get template for new contact
            var template = api.Contacts.Default();

            // cast to insert model
            var contact = (ContactCreate)template;

            // fill new contact
            contact.CompanyName = "New Company";

            // insert
            var addedContact = api.Contacts.Create(contact);

            // delete
            bool isDeleted = api.Contacts.Delete(addedContact.Id);


            List <ValidationMessage> errors;
            bool isValid = ApiValidator.ValidateObject(contact, out errors);

            if (isValid)
            {
                var result = api.Contacts.Create(new ContactCreate());
            }
        }
        /// <summary>
        /// 执行请求
        /// </summary>
        /// <returns></returns>
        private async Task ExecRequestAsync()
        {
            using (var cancellation = this.CreateLinkedTokenSource())
            {
                try
                {
                    var completionOption = this.ApiActionDescriptor.Return.DataType.IsHttpResponseWrapper ?
                                           HttpCompletionOption.ResponseHeadersRead :
                                           HttpCompletionOption.ResponseContentRead;

                    this.ResponseMessage = await this.HttpApiConfig.HttpClient
                                           .SendAsync(this.RequestMessage, completionOption, cancellation.Token)
                                           .ConfigureAwait(false);

                    var result = await this.ApiActionDescriptor.Return.Attribute
                                 .GetTaskResult(this)
                                 .ConfigureAwait(false);

                    ApiValidator.ValidateReturnValue(result, this.HttpApiConfig.UseReturnValuePropertyValidate);
                    this.Result = result;
                }
                catch (Exception ex)
                {
                    this.Exception = ex;
                }
            }
        }
Example #6
0
        private ErrorResponse ValidateRequest(CheckVcodeRequest data)
        {
            if (!ApiValidator.ValidateVerificationId(data.VerificationId, out ErrorResponse error))
            {
                return(error);
            }

            ApiValidator.ValidateVerificationCode(data.Code, out error);
            return(error);
        }
Example #7
0
        private ErrorResponse ValidateRequest(EnterSsRequest data)
        {
            if (!ApiValidator.ValidatePhone(data.Phone, out ErrorResponse error))
            {
                return(error);
            }

            ApiValidator.ValidatePinCode(data.PinCode, out error);
            return(error);
        }
Example #8
0
        private ErrorResponse ValidateRequest(JoinPlaceRequest data)
        {
            if (!ApiValidator.ValidateLinkParameter(data.LinkParameter, out ErrorResponse error))
            {
                return(error);
            }

            ApiValidator.ValidatePlaceId(data.PlaceToJoinId, out error);
            return(error);
        }
Example #9
0
        static void Main(string[] args)
        {
            //var authCredentials = new AuthorizationCodeAuth("client_id", "client_secret", "code", "http://localhost:3432");
            //var url = AuthorizationCodeAuth.GetClientAuthenticationUrl("client_id", "http://localhost:3432");

            // choose authorization flow
            var clientCred = new ClientCredentialAuth("client_id", "client_secret");

            // initialise context with configuration
            var apiContext = new ApiContext(clientCred)
            {
                AppName = "Application name"
            };

            // initialise api explorer
            var api = new ApiExplorer(apiContext);

            // get template for new contact
            var template = api.Contacts.Default();

            // cast to insert model
            var contact = (ContactCreate)template;

            // fill new contact
            contact.CompanyName = "New Company";

            // insert
            var addedContact = api.Contacts.Create(contact);

            // delete
            bool isDeleted = api.Contacts.Delete(addedContact.Id);

            // get all
            var allContacts = api.Contacts.Contacts(new ApiFilter().WithPaging(1, int.MaxValue));

            // prepare custom filter for querying
            var contactFilter = new ContactFilter();

            contactFilter.DateLastChange.IsEqualOrGreatherThan(new DateTime(2016, 1, 1));

            // query data using custom filter
            var contacts = api.Contacts.ContactsExpand(
                new ApiFilter(contactFilter, FilterType.And).AddOrderDesc("Id").WithPaging(1, 5));

            List <ValidationMessage> errors;
            bool isValid = ApiValidator.ValidateObject(contact, out errors);

            if (isValid)
            {
                var result = api.Contacts.Create(new ContactCreate());
            }
        }
Example #10
0
        /// <summary>
        /// 执行请求
        /// </summary>
        /// <returns></returns>
        private async Task <object> ExecRequestAsync()
        {
            using (var cancellation = this.CreateLinkedTokenSource())
            {
                var cacheAttribute = this.ApiActionDescriptor.Cache;
                var cacheProvider  = this.HttpApiConfig.ResponseCacheProvider;

                var cacheKey    = default(string);
                var cacheResult = ResponseCacheResult.NoValue;
                var cacheEnable = cacheAttribute != null && cacheProvider != null;

                if (cacheEnable == true)
                {
                    cacheKey = await cacheAttribute.GetCacheKeyAsync(this).ConfigureAwait(false);

                    cacheResult = await cacheProvider.GetAsync(cacheKey).ConfigureAwait(false);
                }

                if (cacheResult.HasValue == true)
                {
                    this.ResponseMessage = cacheResult.Value.ToResponseMessage(this.RequestMessage, cacheProvider.Name);
                }
                else
                {
                    var completionOption = this.ApiActionDescriptor.Return.DataType.IsHttpResponseWrapper ?
                                           HttpCompletionOption.ResponseHeadersRead :
                                           HttpCompletionOption.ResponseContentRead;

                    this.ResponseMessage = await this.HttpApiConfig.HttpClient
                                           .SendAsync(this.RequestMessage, completionOption, cancellation.Token)
                                           .ConfigureAwait(false);

                    if (cacheEnable == true)
                    {
                        var cacheEntry = await ResponseCacheEntry.FromResponseMessageAsync(this.ResponseMessage).ConfigureAwait(false);

                        await cacheProvider.SetAsync(cacheKey, cacheEntry, cacheAttribute.Expiration).ConfigureAwait(false);
                    }
                }

                var result = await this.ApiActionDescriptor.Return.Attribute
                             .GetTaskResult(this)
                             .ConfigureAwait(false);

                ApiValidator.ValidateReturnValue(result, this.HttpApiConfig.UseReturnValuePropertyValidate);
                return(result);
            }
        }
Example #11
0
        public void ValidateObject_ObjectIsNotValid_ReturnsFals()
        {
            // Arrange
            var model = new FakeApiModel()
            {
                Firstname = "ReallyLongName",
                Lastname  = null
            };

            List <ValidationMessage> errors;

            // Act
            bool isValid = ApiValidator.ValidateObject(model, out errors);

            // Assert
            Assert.That(isValid, Is.False);
            Assert.That(errors.Any(), Is.True);
        }
Example #12
0
        public void ApiValidator_AllConditionsAreMet_ReturnsTrue()
        {
            // Arrange
            var entity = new TestEntity
            {
                IdentificationNumber = "12345678901234567890",
                Name            = "something",
                Rating          = 1,
                NonNullableDate = DateTime.Now.SetKindUtc(),
                NullableDate    = DateTime.Now.AddDays(1).SetKindUtc(),
            };

            // Act
            var result = ApiValidator.ValidateObject(entity, out var errors);

            // Assert
            Assert.True(result);
            Assert.Zero(errors.Count);
        }
        public void ValidateReturnValueTest()
        {
            var value = default(User);

            ApiValidator.ValidateReturnValue(value, true);

            value = new User();
            Assert.Throws <ValidationException>(() => ApiValidator.ValidateReturnValue(value, true));

            value = new User {
                Account = "123"
            };
            ApiValidator.ValidateReturnValue(value, true);

            value = new User {
                Account = "123456"
            };
            Assert.Throws <ValidationException>(() => ApiValidator.ValidateReturnValue(value, true));
        }
Example #14
0
        public void ApiValidator_RequiredPropertiesNotSet_ReturnsFalse()
        {
            // Arrange
            var entity = new TestEntity
            {
                NonNullableDate = DateTime.Now.SetKindUtc(),
                NullableDate    = null
            };

            // Act
            var result = ApiValidator.ValidateObject(entity, out var errors);

            // Assert
            Assert.False(result);
            Assert.AreEqual(2, errors.Count);
            var memberNames = errors.SelectMany(error => error.MemberNames).ToList();

            Assert.Contains(nameof(TestEntity.IdentificationNumber), memberNames);
            Assert.Contains(nameof(TestEntity.Name), memberNames);
        }
        public void ValidateParameterTest()
        {
            var parameter = TestParameter.Create(null);

            Assert.Throws <ValidationException>(() => ApiValidator.ValidateParameter(parameter, true));

            parameter = TestParameter.Create(new User {
            });
            Assert.Throws <ValidationException>(() => ApiValidator.ValidateParameter(parameter, true));

            parameter = TestParameter.Create(new User {
                Account = "123"
            });
            ApiValidator.ValidateParameter(parameter, true);

            parameter = TestParameter.Create(new User {
                Account = "123456"
            });
            Assert.Throws <ValidationException>(() => ApiValidator.ValidateParameter(parameter, true));
        }
Example #16
0
 protected bool IsValidObject(object obj, out List <ValidationMessage> results)
 {
     return(ApiValidator.ValidateObject(obj, out results));
 }
Example #17
0
 private ErrorResponse ValidateRequest(SendVcodeRequest data)
 {
     ApiValidator.ValidatePhone(data.Phone, out ErrorResponse error);
     return(error);
 }
Example #18
0
 private ErrorResponse ValidateRequest(FollowReglinkRequest data)
 {
     ApiValidator.ValidateLinkParameter(data.LinkParameter, out ErrorResponse error);
     return(error);
 }
Example #19
0
 private ErrorResponse ValidateRequest(CheckStatusRequest data)
 {
     ApiValidator.ValidatePlaceId(data.PlaceId, out ErrorResponse error);
     return(error);
 }