public async Task AssignBatchActionResultsAsync(IODataClient client,
            ODataResponse batchResponse, IList<Func<IODataClient, Task>> actions, IList<int> responseIndexes)
        {
            var exceptions = new List<Exception>();
            for (var actionIndex = 0; actionIndex < actions.Count && !exceptions.Any(); actionIndex++)
            {
                var responseIndex = responseIndexes[actionIndex];
                if (responseIndex >= 0 && responseIndex < batchResponse.Batch.Count)
                {
                    var actionResponse = batchResponse.Batch[responseIndex];
                    if (actionResponse.Exception != null)
                    {
                        exceptions.Add(actionResponse.Exception);
                    }
                    else if (actionResponse.StatusCode >= (int)HttpStatusCode.BadRequest)
                    {
                        exceptions.Add(WebRequestException.CreateFromStatusCode((HttpStatusCode)actionResponse.StatusCode));
                    }
                    else
                    {
                        await actions[actionIndex](new ODataClient(client as ODataClient, actionResponse));
                    }
                }
            }

            if (exceptions.Any())
            {
                throw exceptions.First();
            }
        }
        public async Task<ODataRequest> CreateBatchRequestAsync(
            IODataClient client, IList<Func<IODataClient, Task>> actions, IList<int> responseIndexes)
        {
            // Write batch operations into a batch content
            var lastOperationId = 0;
            foreach (var action in actions)
            {
                await action(client);
                var responseIndex = -1;
                if (this.LastOperationId > lastOperationId)
                {
                    lastOperationId = LastOperationId;
                    responseIndex = lastOperationId - 1;
                }
                responseIndexes.Add(responseIndex);
            }

            if (this.HasOperations)
            {
                // Create batch request message
                var requestMessage = await EndBatchAsync();
                return new ODataRequest(RestVerbs.Post, _session, ODataLiteral.Batch, requestMessage);
            }
            else
            {
                return null;
            }
        }
Exemplo n.º 3
0
        public TestBase()
        {
#if NETFX_CORE
            _serviceUri = "http://NORTHWIND/Northwind.svc/";
#else
            _service = new TestService(typeof(NorthwindService));
            _serviceUri = _service.ServiceUri.AbsoluteUri;
#endif
            _client = CreateClientWithDefaultSettings();
        }
        public virtual async Task CustomActionMethodWithSingleDtoReturnValueTest()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                await client.TestModels()
                .CustomActionMethodWithSingleDtoReturnValueTest()
                .ExecuteAsSingleAsync();
            }
        }
        public override async Task <string> AddUserAsync(string username, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Username cannot be null or empty", nameof(username));
            }

            IODataClient client = GetODataClient();
            string       logon  = IDIR.Logon(username);

            Logger.Debug("Adding {Username} to project", username);

            User user = await _userSearchService.SearchAsync(username);

            SystemUser entry = await client
                               .For <SystemUser>()
                               .Filter(_ => _.DomainName == logon)
                               .Select(_ => _.SystemUserId)
                               .FindEntryAsync(cancellationToken);

            if (entry == null)
            {
                Logger.Information("{Username} does not exist, creating a new record", username);

                BusinessUnit rootBusinessUnit = await GetRootBusinessUnit(client, cancellationToken);

                // populate the SystemUser with required attributes
                entry = new SystemUser
                {
                    Firstname              = user.FirstName,
                    Lastname               = user.LastName,
                    DomainName             = IDIR.Logon(username),
                    InternalEMailAddress   = user.Email,
                    BusinessUnit           = rootBusinessUnit,
                    IsDisabled             = false,
                    SharePointEmailAddress = user.UserPrincipalName
                };

                await client
                .For <SystemUser>()
                .Set(entry)
                .InsertEntryAsync(cancellationToken);
            }
            else
            {
                Logger.Information("{@SystemUser} exists ensuring the user is enabled", entry);
                await UpdateSystemUserDisableFlag(client, entry.SystemUserId, user, false, cancellationToken);
            }

            return(string.Empty);
        }
Exemplo n.º 6
0
        public virtual async Task TestTimeZonesInCustomActionsWithoutClientsDemand()
        {
            IValueChecker valueChecker = A.Fake <IValueChecker>();

            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment(new TestEnvironmentArgs
            {
                AdditionalDependencies = (manager, services) =>
                {
                    manager.RegisterInstance(valueChecker);
                }
            }))
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                DateTimeOffset date = new DateTimeOffset(2016, 1, 1, 10, 30, 0, TimeSpan.Zero);

                await client.TestModels()
                .TimeZoneTests(simpleDate: date,
                               datesArray: new[] { date, date },
                               simpleDto: new TestModel {
                    StringProperty = " ", DateProperty = date, Id = 1, Version = 1
                },
                               entitiesArray: new[]
                {
                    new TestModel
                    {
                        StringProperty = " ", DateProperty = date, Id = 2, Version = 2
                    },
                    new TestModel
                    {
                        StringProperty = " ", DateProperty = date, Id = 3, Version = 3
                    }
                }).ExecuteAsync();

                A.CallTo(() => valueChecker.CheckValue(A <DateTimeOffset> .That.Matches(dt => dt.Year == 2016)))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue(A <List <DateTimeOffset> > .That.Matches(dates => dates.SequenceEqual(new List <DateTimeOffset> {
                    date, date
                }))))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue(A <TestModel> .That.Matches(tm => tm.DateProperty == date)))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue(A <List <TestModel> > .That.Matches(tms => tms.First().DateProperty == date && tms.Last().DateProperty == date)))
                .MustHaveHappenedOnceExactly();
            }
        }
        public virtual async Task WebApiExceptionHandlerFilterAttributeMustReturnKnownErrorReasonPhraseAndNotFoundStatusCodeAndCorrelationIdInResponseWhenResourceNotFoundExceptionThrownsInWebApi()
        {
            IEmailService emailService = A.Fake <IEmailService>();

            A.CallTo(() => emailService.SendEmail(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored))
            .Throws(new ResourceNotFoundException("Test"));

            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment(new TestEnvironmentArgs
            {
                AdditionalDependencies = (manager, services) =>
                {
                    manager.RegisterInstance(emailService);
                }
            }))
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token, afterResponse: message =>
                {
                    if (message.StatusCode == HttpStatusCode.NotFound)
                    {
                        Assert.AreEqual(BitMetadataBuilder.KnownError, message.ReasonPhrase);

                        ILogger logger = TestDependencyManager.CurrentTestDependencyManager.Objects
                                         .OfType <ILogger>().Last();

                        Guid correlationId = (Guid)logger.LogData.Single(logData => logData.Key == "X-CorrelationId").Value;

                        Assert.AreEqual(correlationId.ToString(), message.Headers.Single(h => h.Key == "X-CorrelationId").Value.Single());
                    }
                });

                try
                {
                    await client.Controller <TestModelsController, TestModel>()
                    .Action(nameof(TestModelsController.SendEmail))
                    .Set(new TestModelsController.EmailParameters {
                        to = "Someone", title = "Email title", message = "Email message"
                    })
                    .ExecuteAsync();

                    Assert.Fail();
                }
                catch (WebRequestException ex)
                {
                    Assert.IsTrue(ex.Response.Contains("Test"));

                    Assert.AreEqual(HttpStatusCode.NotFound, ex.Code);
                }
            }
        }
        public virtual async Task WebApiExceptionHandlerFilterAttributeMustReturnKnownErrorReasonPhraseAndNotFoundStatusCodeAndXCorrelationIdInResponseWhenResourceNotFoundExceptionThrownsInWebApi()
        {
            IEmailService emailService = A.Fake <IEmailService>();

            A.CallTo(() => emailService.SendEmail(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored))
            .Throws(new ResourceNotFoundException("Test"));

            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment(new TestEnvironmentArgs
            {
                AdditionalDependencies = (manager, services) =>
                {
                    manager.RegisterInstance(emailService);
                }
            }))
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.BuildTestODataClient(token: token, odataClientSettings: new ODataClientSettings
                {
                    AfterResponse = message =>
                    {
                        if (message.StatusCode == HttpStatusCode.NotFound)
                        {
                            Assert.AreEqual(BitMetadataBuilder.KnownError, message.ReasonPhrase);
                            Assert.IsTrue(message.Headers.Any(h => h.Key == "Reason-Phrase" && h.Value.Any(v => v == BitMetadataBuilder.KnownError)));

                            ILogger logger = testEnvironment.GetObjects <ILogger>().Last();

                            string xCorrelationId = (string)logger.LogData.Single(logData => logData.Key == "X-Correlation-ID").Value;

                            Assert.AreEqual(xCorrelationId, message.Headers.Single(h => h.Key == "X-Correlation-ID").Value.Single());
                        }
                    }
                });

                try
                {
                    await client.TestModels()
                    .SendEmail(to: "Someone", title: "Email title", message: "Email message")
                    .ExecuteAsync();

                    Assert.Fail();
                }
                catch (WebRequestException ex)
                {
                    Assert.IsTrue(ex.Response.Contains("Test"));

                    Assert.AreEqual(HttpStatusCode.NotFound, ex.Code);
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Registers new user. If userName gets provided, it uses that for registration. Otherwise, it creates random user name.
        /// </summary>
        /// <returns>UserName. Useful when you've not provided fixed user name, so you can retrive generated user name's value.</returns>
        public static async Task <string> RegisterNewUser(this ToDoLineTestEnv testEnv, string userName = null, string password = "******")
        {
            userName = userName ?? Guid.NewGuid().ToString("N");

            IODataClient client = testEnv.Server.BuildODataClient(odataRouteName: "ToDoLine");

            await client.UserRegistration()
            .Register(new UserRegistrationDto {
                UserName = userName, Password = password
            })
            .ExecuteAsync();

            return(userName);
        }
Exemplo n.º 10
0
        protected TestBase(string serviceUri, ODataPayloadFormat payloadFormat)
        {
            //services.odata.org only works with Tls 1.2
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

            if (serviceUri.Contains("%28readwrite%29") || serviceUri == TripPinV4ReadWriteUri)
            {
                serviceUri = GetReadWriteUri(serviceUri).GetAwaiter().GetResult();
            }

            _serviceUri    = new Uri(serviceUri);
            _payloadFormat = payloadFormat;
            _client        = CreateClientWithDefaultSettings();
        }
Exemplo n.º 11
0
        public virtual async Task EnumTest_CSClient()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment(new TestEnvironmentArgs {
            }))
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                DtoWithEnum dtoWithEnum = await client.DtoWithEnum()
                                          .GetDtoWithEnumsByGender(TestGender.Man)
                                          .ExecuteAsSingleAsync();

                Assert.AreEqual(TestGender.Man, dtoWithEnum.Gender);

                Assert.AreEqual(true, await client.DtoWithEnum()
                                .PostDtoWithEnum(dtoWithEnum)
                                .ExecuteAsScalarAsync <bool>());

                ODataBatch batchClient = testEnvironment.Server.BuildODataBatchClient(token: token);

                batchClient += bc => bc.DtoWithEnum()
                               .GetDtoWithEnumsByGender2(TestGender2.Man)
                               .ExecuteAsEnumerableAsync();

                batchClient += bc => bc.DtoWithEnum()
                               .GetDtoWithEnumsByGender(TestGender.Man)
                               .ExecuteAsEnumerableAsync();

                await batchClient.ExecuteAsync();

                /*Assert.AreEqual(true, await client.DtoWithEnum()
                 *  .TestEnumsArray(new[] { TestGender2.Man, TestGender2.Woman })
                 *  .ExecuteAsScalarAsync<bool>());*/

                DtoWithEnumController firstCallController = TestDependencyManager.CurrentTestDependencyManager.Objects
                                                            .OfType <DtoWithEnumController>()
                                                            .First();

                DtoWithEnumController secondCallController = TestDependencyManager.CurrentTestDependencyManager.Objects
                                                             .OfType <DtoWithEnumController>()
                                                             .ElementAt(2);

                A.CallTo(() => firstCallController.GetDtoWithEnumsByGender(TestGender.Man))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => secondCallController.GetDtoWithEnumsByGender2(TestGender2.Man))
                .MustHaveHappenedOnceExactly();
            }
        }
Exemplo n.º 12
0
        public async Task LoginAndSubmitNewEvlRequestAndFindExpertForItTest()
        {
            using (SanaapTestEnvironment testEnv = new SanaapTestEnvironment())
            {
                TokenResponse token = await testEnv.Server.Login("1270340050", "09033610498", "SanaapResOwner", "secret");

                HttpClient httpClient = testEnv.Server.BuildHttpClient(token);

                MultipartFormDataContent content = new MultipartFormDataContent
                {
                    //new StringContent(JsonConvert.SerializeObject(new EvlRequestDto
                    //{
                    //    AccidentDate = DateTimeOffset.UtcNow,
                    //    CompanyId = 1,
                    //    AccidentReason = "Test",
                    //    InsuranceNumber = "123-456",
                    //    InsuranceTypeEnum = InsuranceType.Sales,
                    //    Latitude = 12,
                    //    Longitude = 12,
                    //    VehicleKindId = 1,
                    //    VehicleNumber = "ایران - ب 44 678"
                    //}), Encoding.UTF8, "application/json"),

                    { new StreamContent(File.OpenRead(@"C:\Users\SOFT\Desktop\Mohammad.png")), Guid.Parse("9bbd650e-3415-494d-b382-623a0840ab5a").ToString(), Guid.Parse("9bbd650e-3415-494d-b382-623a0840ab5a").ToString() }
                };

                HttpRequestMessage submitEvlRequest = new HttpRequestMessage(HttpMethod.Post, "api/evl-requests/submit-evl-request")
                {
                    Content = content
                };

                HttpResponseMessage submitEvlRequestExpertResponse = await httpClient.SendAsync(submitEvlRequest);

                submitEvlRequestExpertResponse.EnsureSuccessStatusCode();

                EvlRequestDto evlRequest = JsonConvert.DeserializeObject <EvlRequestDto>(await submitEvlRequestExpertResponse.Content.ReadAsStringAsync());

                IODataClient odataClient = testEnv.Server.BuildODataClient(odataRouteName: "Sanaap", token: token);

                EvlRequestExpertDto evlRequestExpert = await odataClient.Controller <EvlRequestExpertsController, EvlRequestExpertDto>()
                                                       .Function(nameof(EvlRequestExpertsController.FindEvlRequestExpert))
                                                       .Set(new { evlRequestId = evlRequest.Id })
                                                       .FindEntryAsync();

                evlRequestExpert = await odataClient.Controller <EvlRequestExpertsController, EvlRequestExpertDto>()
                                   .Function(nameof(EvlRequestExpertsController.FindEvlRequestExpert))
                                   .Set(new { evlRequestId = evlRequest.Id })
                                   .FindEntryAsync();
            }
        }
        public async Task LogExceptionWhenEmailSendFailedAndTryForTheSecondTime()
        {
            IEmailService emailService = A.Fake <IEmailService>();

            TaskCompletionSource <bool> emailSent = new TaskCompletionSource <bool>();

            int tryCount = 0;

            A.CallTo(() => emailService.SendEmail(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored))
            .Invokes(() =>
            {
                tryCount++;

                if (tryCount == 2)
                {
                    emailSent.SetResult(true);
                    return;
                }

                throw new InvalidOperationException();
            });

            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment(new TestEnvironmentArgs
            {
                AdditionalDependencies = (manager, services) =>
                {
                    manager.RegisterInstance(emailService);
                }
            }))
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                string jobId = (await client.TestModels()
                                .SendEmailUsingBackgroundJobService(to: "Someone", title: "Email title", message: "Email message")
                                .ExecuteAsScalarAsync <Guid>()).ToString();

                Assert.AreEqual(true, await emailSent.Task);

                ILogger logger = TestDependencyManager.CurrentTestDependencyManager
                                 .Objects.OfType <ILogger>()
                                 .Last();

                A.CallTo(() => logger.LogException(A <Exception> .That.Matches(e => e is InvalidOperationException), A <string> .That.Matches(errMsg => errMsg.Contains(jobId))))
                .MustHaveHappenedOnceExactly();

                Assert.AreEqual(2, tryCount);
            }
        }
Exemplo n.º 14
0
        public virtual async Task ValidateODataSqlBuilderResults()
        {
            IValueChecker valueChecker = A.Fake <IValueChecker>();

            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment(new TestEnvironmentArgs
            {
                AdditionalDependencies = (manager, services) =>
                {
                    manager.RegisterInstance(valueChecker);
                }
            }))
            {
                Token token = await testEnvironment.Server.LoginWithCredentials("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.BuildTestODataClient(token: token);

                await client.TestModels()
                .TestSqlBuilder()
                .Where(t => (t.Id == 1 && t.StringProperty.ToLower().Contains("Test")) || t.Id == 3)
                .OrderBy(t => t.Id)
                .ThenByDescending(t => t.StringProperty)
                .Top(10)
                .Skip(7)
                .ExecuteAsEnumerableAsync();

                A.CallTo(() => valueChecker.CheckValue((long?)10))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue((long?)7))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue("(([TestModel].[Id] = @Param1 AND [TestModel].[StringProperty] LIKE @Param2) OR [TestModel].[Id] = @Param3)"))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue("[TestModel].[Id],[TestModel].[StringProperty] DESC"))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue(A <object[]> .That.Matches(parameters => (long)parameters[0] == 1 && (string)parameters[1] == "%Test%" && (long)parameters[2] == 3)))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue("select  * from Test.TestModels as [TestModel] where (([TestModel].[Id] = @Param1 AND [TestModel].[StringProperty] LIKE @Param2) OR [TestModel].[Id] = @Param3) order by [TestModel].[Id],[TestModel].[StringProperty] DESC offset 7 rows fetch next 10 rows only"))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue("select count_big(1) from Test.TestModels as [TestModel] where (([TestModel].[Id] = @Param1 AND [TestModel].[StringProperty] LIKE @Param2) OR [TestModel].[Id] = @Param3)"))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue(false))
                .MustHaveHappenedOnceExactly();
            }
        }
Exemplo n.º 15
0
        public virtual async Task TestTimeZonesInUrlWithoutClientDemand()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                IEnumerable <TestModel> testModels = await client.TestModels()
                                                     .Where(tm => tm.DateProperty == new DateTimeOffset(2016, 1, 1, 10, 30, 0, TimeSpan.Zero))
                                                     .FindEntriesAsync();

                Assert.AreEqual(1, testModels.Count());
            }
        }
        public override async Task <bool> UserHasAccessAsync(string username)
        {
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Username cannot be null or empty", nameof(username));
            }

            IODataClient client = GetODataClient();

            string logon = IDIR.Logon(username);

            var entry = await GetSystemUserByLogon(client, logon);

            return(entry?.IsDisabled != null && !entry.IsDisabled.Value);
        }
        private Task <IDictionary <string, object> > UpdateSystemUserDisableFlag(IODataClient client, Guid systemUserId, bool isDisabled)
        {
            _logger.LogDebug("Updating  SystemUser with {SystemUserId} with isDisabled flag set to {UsDisabled} in Dynamics", systemUserId, isDisabled);

            // using the untyped version because the typed version was giving an error:
            //
            // Microsoft.OData.ODataException: The property 'isdisabled' does not exist on type 'Microsoft.Dynamics.CRM.systemuser'.
            // Make sure to only use property names that are defined by the type or mark the type as open type.
            //
            return(client
                   .For("systemuser")
                   .Key(systemUserId)
                   .Set(new { isdisabled = isDisabled })
                   .UpdateEntryAsync());
        }
 public BreathingSpaceBrowseGateway(IODataClient client,
                                    DynamicsGatewayOptions options)
 {
     _client              = client;
     _options             = options;
     _taskBrowseFunctions = new Dictionary <BreathingSpaceBrowseTask, Func <Guid, bool, Task <BreathingSpaceBrowseResponse> > >
     {
         { BreathingSpaceBrowseTask.DebtsToBeReviewed, BrowseDebtsToBeReviewedAsync },
         { BreathingSpaceBrowseTask.ClientsToBeReviewed, BrowseClientsToBeReviewedAsync },
         { BreathingSpaceBrowseTask.NewDebtsProposed, BrowseNewDebtsProposedAsync },
         { BreathingSpaceBrowseTask.DebtsToBeTransferred, BrowseDebtsToBeTransferredAsync },
         { BreathingSpaceBrowseTask.ClientsToBeTransferred, BrowseClientsToBeTransferred },
         { BreathingSpaceBrowseTask.ClientsTransferredToMoneyAdviser, BrowseClientsTransferredToMoneyAdviser }
     };
 }
Exemplo n.º 19
0
 public CommonDynamicsGateway(
     IODataClient client,
     DynamicsGatewayOptions options,
     ILogger <CommonDynamicsGateway> logger,
     IMapperService mapperService,
     AuditContext auditContext,
     IAuditService auditService)
 {
     _logger        = logger;
     _client        = client;
     _options       = options;
     _mapperService = mapperService;
     _auditContext  = auditContext;
     _auditService  = auditService;
 }
        public async Task SendEmailUsingBackgroundJobWorkerAndWebApi()
        {
            IEmailService emailService = A.Fake <IEmailService>();

            TaskCompletionSource <bool> emailSent = new TaskCompletionSource <bool>();

            A.CallTo(() => emailService.SendEmail(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored))
            .Invokes(() =>
            {
                emailSent.SetResult(true);
            });

            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment(new TestEnvironmentArgs
            {
                AdditionalDependencies = (manager, services) =>
                {
                    manager.RegisterInstance(emailService);
                }
            }))
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                string jobId = (await client.Controller <TestModelsController, TestModel>()
                                .Action(nameof(TestModelsController.SendEmailUsingBackgroundJobService))
                                .Set(new TestModelsController.EmailParameters {
                    to = "Someone", title = "Email title", message = "Email message"
                })
                                .ExecuteAsScalarAsync <Guid>()).ToString();

                IODataClient bitODataClient = testEnvironment.Server.BuildODataClient(token: token, odataRouteName: "Bit");

                JobInfoDto jobInfo = await bitODataClient.Controller <JobsInfoController, JobInfoDto>()
                                     .Key(jobId)
                                     .FindEntryAsync();

                Assert.AreEqual(true, await emailSent.Task);

                await Task.Delay(TimeSpan.FromSeconds(1));

                jobInfo = await bitODataClient.Controller <JobsInfoController, JobInfoDto>()
                          .Key(jobId)
                          .FindEntryAsync();

                Assert.AreEqual("Succeeded", jobInfo.State);
            }
        }
        public override async Task <string> AddUserAsync(string username)
        {
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Username cannot be null or empty", nameof(username));
            }

            IODataClient client = GetODataClient();
            string       logon  = IDIR.Logon(username);

            SystemUser entry = await GetSystemUserByLogon(client, logon);

            if (entry == null)
            {
                _logger.LogInformation("{Username} does not exist, creating a new record", username);

                User user = await _userSearchService.SearchAsync(username);

                BusinessUnit rootBusinessUnit = await GetRootBusinessUnit(client);

                // populate the SystemUser with required attributes
                entry = new SystemUser
                {
                    Firstname            = user.FirstName,
                    Lastname             = user.LastName,
                    DomainName           = IDIR.Logon(username),
                    InternalEMailAddress = user.Email,
                    BusinessUnit         = rootBusinessUnit,
                    IsDisabled           = false
                };

                entry = await client
                        .For <SystemUser>()
                        .Set(entry)
                        .InsertEntryAsync();
            }
            else if (entry.IsDisabled != null && entry.IsDisabled.Value)
            {
                _logger.LogInformation("{@SystemUser} exists but is disabled, enabling user", entry);
                await UpdateSystemUserDisableFlag(client, entry.SystemUserId, false);
            }
            else
            {
                _logger.LogInformation("{@SystemUser} exists and is already enabled user", entry);
            }

            return(string.Empty);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Registers new user. If userName gets provided, it uses that for registration. Otherwise, it creates random user name.
        /// </summary>
        /// <returns>UserName. Useful when you've not provided fixed user name, so you can retrive generated user name's value.</returns>
        public static async Task <string> RegisterNewUser(this ToDoLineTestEnv testEnv, string userName = null)
        {
            userName = userName ?? Guid.NewGuid().ToString("N");

            IODataClient client = testEnv.Server.BuildODataClient(odataRouteName: "ToDoLine");

            await client.Controller <UserRegistrationController, UserRegistrationDto>()
            .Action(nameof(UserRegistrationController.Register))
            .Set(new UserRegistrationController.RegisterArgs {
                userRegistration = new UserRegistrationDto {
                    UserName = userName, Password = "******"
                }
            })
            .ExecuteAsync();

            return(userName);
        }
Exemplo n.º 23
0
        public virtual async Task InsertAndUpdateTogether()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                ODataBatch batchClient = testEnvironment.Server.BuildODataBatchClient(token: token);

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                TestModel modelBeforeInsert = new TestModel
                {
                    StringProperty = "Test",
                    Version        = 1
                };

                batchClient += bc => bc.Controller <TestModelsController, TestModel>()
                               .Set(modelBeforeInsert)
                               .CreateEntryAsync();

                long modelBeforeUpdateId = await client.Controller <TestModelsController, TestModel>()
                                           .Top(1)
                                           .Select(t => t.Id)
                                           .FindScalarAsync <long>();

                batchClient += bc => bc.Controller <TestModelsController, TestModel>()
                               .Key(modelBeforeUpdateId)
                               .Set(new { StringProperty = "Test2" })
                               .UpdateEntryAsync();

                await batchClient.ExecuteAsync();

                IRepository <TestModel> testModelsRepository =
                    TestDependencyManager.CurrentTestDependencyManager.Objects
                    .OfType <IRepository <TestModel> >()
                    .Last();

                A.CallTo(() => testModelsRepository.UpdateAsync(
                             A <TestModel> .That.Matches(testModel => testModel.StringProperty == "Test2"),
                             A <CancellationToken> .Ignored))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => testModelsRepository.AddAsync(A <TestModel> .That.Matches(testModel => testModel.StringProperty == "Test"), A <CancellationToken> .Ignored))
                .MustHaveHappenedOnceExactly();
            }
        }
Exemplo n.º 24
0
        public virtual async Task TestTimeZonesInUrlWithClientDemand()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token, beforeRequest: message =>
                {
                    message.Headers.Add("Desired-Time-Zone", "Iran Standard Time");
                    message.Headers.Add("Current-Time-Zone", "Afghanistan Standard Time");
                });

                IEnumerable <TestModel> testModels = await client.Controller <TestModelsController, TestModel>()
                                                     .Where(tm => tm.DateProperty == new DateTimeOffset(2016, 1, 1, 9, 30, 0, TimeSpan.Zero))
                                                     .FindEntriesAsync();

                Assert.AreEqual(1, testModels.Count());
            }
        }
Exemplo n.º 25
0
        public async Task TestPartialUpdate()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                long modelBeforeUpdateId = await client.Controller <TestModelsController, TestModel>()
                                           .Top(1)
                                           .Select(t => t.Id)
                                           .FindScalarAsync <long>();

                TestModel modelAfterUpdate = await client.Controller <TestModelsController, TestModel>()
                                             .Key(modelBeforeUpdateId)
                                             .Set(new { StringProperty = "Test2" })
                                             .UpdateEntryAsync();

                Assert.AreEqual("Test2", modelAfterUpdate.StringProperty);

                TestModelsController testModelsController = TestDependencyManager.CurrentTestDependencyManager.Objects
                                                            .OfType <TestModelsController>()
                                                            .Last();

                A.CallTo(() => testModelsController.PartialUpdate(modelBeforeUpdateId,
                                                                  A <Delta <TestModel> > .That.Matches(
                                                                      testModelDelta =>
                                                                      testModelDelta.GetChangedPropertyNames().Single() == nameof(TestModel.StringProperty)),
                                                                  A <CancellationToken> .Ignored))
                .MustHaveHappenedOnceExactly();

                IRepository <TestModel> testModelsRepository =
                    TestDependencyManager.CurrentTestDependencyManager.Objects
                    .OfType <IRepository <TestModel> >()
                    .Last();

                A.CallTo(() => testModelsRepository.UpdateAsync(
                             A <TestModel> .That.Matches(testModel => testModel.StringProperty == "Test2"),
                             A <CancellationToken> .Ignored))
                .MustHaveHappenedOnceExactly();
            }
        }
        private async Task <SystemUser> GetSystemUserByLogon(IODataClient client, string logon)
        {
            _logger.LogDebug("Getting SystemUser with {DomainName} from Dynamics", logon);

            var systemUser = await client
                             .For <SystemUser>()
                             .Filter(_ => _.DomainName == logon)
                             .FindEntryAsync();

            if (systemUser != null)
            {
                _logger.LogDebug("Found SystemUser {@SystemUser}", new { systemUser.DomainName, systemUser.IsDisabled, systemUser.SystemUserId });
            }
            else
            {
                _logger.LogDebug("SystemUser with {DomainName} not found", logon);
            }

            return(systemUser);
        }
Exemplo n.º 27
0
        public virtual async Task SimpleODataInCSharpClientTest()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                Token token = await testEnvironment.Server.LoginWithCredentials("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.BuildTestODataClient(token: token);

                Assert.AreEqual(3, await client.Simple().Sum(1, 2).ExecuteAsScalarAsync <int>());
            }

            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                Token token = await testEnvironment.Server.LoginWithCredentials("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                HttpClient client = testEnvironment.Server.BuildHttpClient(token: token);

                Assert.AreEqual(3, await client.Simple().Sum(1, 2));
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Login with provided user name. If registerNewUserByRandomUserName gets provided 'true' then it calls <see cref="RegisterNewUser(ToDoLineTestEnv, string)"/> first.
        /// You've to either provide a valid userName or pass registerNewUserByRandomUserName 'true'. It generates a random userName and returns that to you in case no userName is provided for registration.
        /// </summary>
        public static async Task <(string userName, IODataClient loggedInClient)> LoginInToApp(this ToDoLineTestEnv testEnv, bool registerNewUserByRandomUserName, string userName = null)
        {
            if (registerNewUserByRandomUserName == true)
            {
                userName = await RegisterNewUser(testEnv, userName);
            }
            else
            {
                if (userName == null)
                {
                    throw new ArgumentNullException(nameof(userName));
                }
            }

            TokenResponse token = await testEnv.Server.Login(userName, password : "******", clientId : "ToDoLine", secret : "secret");

            IODataClient loggedInClient = testEnv.Server.BuildODataClient(odataRouteName: "ToDoLine", token: token);

            return(userName, loggedInClient);
        }
        public virtual async Task WebApiTraceWritterShouldLogCorrelationIdAndExceptionDetails()
        {
            IEmailService emailService = A.Fake <IEmailService>();

            A.CallTo(() => emailService.SendEmail(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored))
            .Throws(new AppException("Test"));

            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment(new TestEnvironmentArgs
            {
                AdditionalDependencies = manager =>
                {
                    manager.RegisterInstance(emailService);
                }
            }))
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                try
                {
                    await client.Controller <TestModelsController, TestModel>()
                    .Action(nameof(TestModelsController.SendEmail))
                    .Set(new TestModelsController.EmailParameters {
                        to = "Someone", title = "Email title", message = "Email message"
                    })
                    .ExecuteAsync();

                    Assert.Fail();
                }
                catch (WebRequestException)
                {
                    ILogger logger = TestDependencyManager.CurrentTestDependencyManager.Objects
                                     .OfType <ILogger>().Last();

                    Assert.IsTrue(logger.LogData.Single(ld => ld.Key == "X-CorrelationId").Value is Guid);
                    Assert.AreEqual(typeof(AppException).GetTypeInfo().FullName, logger.LogData.Single(ld => ld.Key == "WebExceptionType").Value);
                    Assert.IsTrue(((string)(logger.LogData.Single(ld => ld.Key == "WebException").Value)).Contains("Bit.Owin.Exceptions.AppException: Test"));
                }
            }
        }
        public virtual async Task CreateODataLinkAndCallItTest()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.BuildTestODataClient(token: token);

                string newUrl = await client.TestModels()
                                .CreateODataLinkSample()
                                .ExecuteAsScalarAsync <string>();

                int sumResult = (await(await testEnvironment.Server.BuildHttpClient(token)
                                       .GetAsync(newUrl))
                                 .EnsureSuccessStatusCode()
                                 .Content
                                 .ReadAsAsync <ODataResponse <int> >()).Value;

                Assert.AreEqual(3, sumResult);
            }
        }
        public override async Task <bool> UserHasAccessAsync(string username, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Username cannot be null or empty", nameof(username));
            }

            IODataClient client = GetODataClient();

            string logon = IDIR.Logon(username);

            Logger.Debug("Checking {Username} has access to project", username);

            SystemUser entry = await client
                               .For <SystemUser>()
                               .Filter(_ => _.DomainName == logon && _.IsDisabled == false)
                               .Select(_ => _.SystemUserId)
                               .FindEntryAsync(cancellationToken);

            return(entry != null);
        }
        public virtual async Task LogOperationArgsFilterAttributeShouldLogOperationArgs()
        {
            IEmailService emailService = A.Fake <IEmailService>();

            A.CallTo(() => emailService.SendEmail(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored))
            .Throws <InvalidOperationException>();

            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment(new TestEnvironmentArgs
            {
                AdditionalDependencies = manager =>
                {
                    manager.RegisterInstance(emailService);
                }
            }))
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                try
                {
                    await client.Controller <TestModelsController, TestModel>()
                    .Action(nameof(TestModelsController.SendEmail))
                    .Set(new TestModelsController.EmailParameters {
                        to = "Someone", title = "Email title", message = "Email message"
                    })
                    .ExecuteAsync();

                    Assert.Fail();
                }
                catch (WebRequestException)
                {
                    ILogStore logStore = TestDependencyManager.CurrentTestDependencyManager.Objects
                                         .OfType <ILogStore>().Last();

                    A.CallTo(() => logStore.SaveLogAsync(A <LogEntry> .That.Matches(log => ((TestModelsController.EmailParameters)((KeyValuePair <string, object>[])log.LogData.Single(ld => ld.Key == "OperationArgs").Value)[0].Value).to == "Someone")))
                    .MustHaveHappened(Repeated.Exactly.Once);
                }
            }
        }
        public virtual async Task LogOperationArgsFilterAttributeShouldLogOperationArgs()
        {
            IEmailService emailService = A.Fake <IEmailService>();

            A.CallTo(() => emailService.SendEmail(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored))
            .Throws <InvalidOperationException>();

            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment(new TestEnvironmentArgs
            {
                AdditionalDependencies = (manager, services) =>
                {
                    manager.RegisterInstance(emailService);
                }
            }))
            {
                Token token = await testEnvironment.Server.LoginWithCredentials("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.BuildTestODataClient(token: token);

                try
                {
                    await client.TestModels()
                    .SendEmail(to: "Someone", title: "Email title", message: "Email message")
                    .ExecuteAsync();

                    Assert.Fail();
                }
                catch (WebRequestException)
                {
                    ILogStore logStore = testEnvironment.GetObjects <ILogStore>().Last();

                    A.CallTo(() => logStore.SaveLogAsync(A <LogEntry> .That.Matches(log => ((TestModelsController.EmailParameters)((KeyValuePair <string, object>[])log.LogData.Single(ld => ld.Key == "OperationArgs").Value)[0].Value).to == "Someone")))
                    .MustHaveHappenedOnceExactly();
                    A.CallTo(() => logStore.SaveLogAsync(A <LogEntry> .That.Matches(log => ((string)log.LogData.Single(ld => ld.Key == "OperationName").Value) == "SendEmail")))
                    .MustHaveHappenedOnceExactly();
                    A.CallTo(() => logStore.SaveLogAsync(A <LogEntry> .That.Matches(log => ((string)log.LogData.Single(ld => ld.Key == "ControllerName").Value) == "TestModels")))
                    .MustHaveHappenedOnceExactly();
                }
            }
        }
Exemplo n.º 34
0
 public TestBase()
 {
     _client = CreateClientWithDefaultSettings();
 }
		public DataApiService(IODataClient client)
		{
			this.client = client;
		}
 protected WebApiTestsBase(ODataClientSettings settings)
 {
     _client = new ODataClient(settings);
 }
 private async Task RunClient(IODataClient client, int productID, ExecutionSummary result)
 {
     try
     {
         var product = await client.FindEntryAsync(string.Format("Products({0})", productID));
         if (productID != Convert.ToInt32(product["ProductID"]))
         {
             lock (result)
             {
                 result.NonEqualCount++;
             }
         }
     }
     catch (Exception)
     {
         lock (result)
         {
             result.ExceptionCount++;
         }
     }
     finally
     {
         lock (result)
         {
             result.ExecutionCount++;
         }
     }
 }
Exemplo n.º 38
0
 protected TestBase()
 {
     _client = CreateClient(this.MetadataFile);
 }
Exemplo n.º 39
-1
 /// <summary>
 /// Initializes a new instance of the <see cref="ODataBatch"/> class.
 /// </summary>
 /// <param name="client">The OData client which settings will be used to create a batch.</param>
 public ODataBatch(IODataClient client)
 {
     _client = new ODataClient((client as ODataClient).Session.Settings, _entryMap);
 }