Esempio n. 1
0
 public void TestInitialize()
 {
     _repository = new MockRepository();
     _controller = new OrdersController(_repository);
     MockUser.CurrentUser(_controller);
     MockHttpConfiguration.HttpConfiguration(_controller);
 }
            public async Task UpdatesTheBeginningOfWeekProperty()
            {
                var oldBeginningOfWeek = BeginningOfWeek.Tuesday;
                var newBeginningOfWeek = BeginningOfWeek.Sunday;
                var oldUser            = new MockUser {
                    BeginningOfWeek = oldBeginningOfWeek
                };
                var newUser = new MockUser {
                    BeginningOfWeek = newBeginningOfWeek
                };

                UserSubject.OnNext(oldUser);
                NavigationService
                .Navigate <SelectBeginningOfWeekViewModel, BeginningOfWeek, BeginningOfWeek>(Arg.Any <BeginningOfWeek>())
                .Returns(Task.FromResult(newBeginningOfWeek));
                DataSource
                .User
                .Update(Arg.Any <EditUserDTO>())
                .Returns(Observable.Return(newUser));

                await ViewModel.SelectBeginningOfWeek();

                await DataSource.User.Received().Update(
                    Arg.Is <EditUserDTO>(dto => dto.BeginningOfWeek == newBeginningOfWeek
                                         ));
            }
Esempio n. 3
0
            public async Task UpdatesTheBeginningOfWeekProperty()
            {
                var oldBeginningOfWeek = BeginningOfWeek.Tuesday;
                var newBeginningOfWeek = BeginningOfWeek.Sunday;
                var oldUser            = new MockUser {
                    BeginningOfWeek = oldBeginningOfWeek
                };
                var newUser = new MockUser {
                    BeginningOfWeek = newBeginningOfWeek
                };

                UserSubject.OnNext(oldUser);
                NavigationService
                .Navigate <SelectBeginningOfWeekViewModel, BeginningOfWeek, BeginningOfWeek>(Arg.Any <BeginningOfWeek>())
                .Returns(Task.FromResult(newBeginningOfWeek));
                InteractorFactory
                .UpdateUser(Arg.Any <EditUserDTO>())
                .Execute()
                .Returns(Observable.Return(newUser));

                ViewModel.SelectBeginningOfWeek.Execute();
                TestScheduler.Start();

                await InteractorFactory.UpdateUser(
                    Arg.Is <EditUserDTO>(dto => dto.BeginningOfWeek == newBeginningOfWeek
                                         )).Received().Execute();
            }
Esempio n. 4
0
        public void GetAUser()
        {
            SetUpUserService();
            MockUser user = (MockUser)us.GetUser(userName1);

            user.Should().NotBeNull();
        }
Esempio n. 5
0
            protected override IDatabaseUser CreateCleanWithPositiveIdFrom(IDatabaseUser entity)
            {
                var te = new MockUser(entity);

                te.Id = 1;
                return(User.Clean(te));
            }
Esempio n. 6
0
        internal MockUser AddUserToDB(string Name)
        {
            MockUser user = CreateUser(Name);

            us.AddUser(user);
            return(user);
        }
            public async Task ReturnsTheWorkspaceWithSmallestIdWhenUsersDefaultWorkspaceIsNotInTheDatabase()
            {
                const long workspaceId = 11;
                var        workspaces  = new[] { new MockWorkspace {
                                                     Id = workspaceId + 2
                                                 }, new MockWorkspace {
                                                     Id = workspaceId
                                                 }, new MockWorkspace {
                                                     Id = workspaceId + 1
                                                 } };
                var user = new MockUser {
                    DefaultWorkspaceId = workspaceId + 3
                };

                DataSource.User.Get().Returns(Observable.Return(user));
                InteractorFactory.GetWorkspaceById(workspaceId + 3)
                .Execute()
                .Returns(Observable.Throw <IThreadSafeWorkspace>(new InvalidOperationException()));
                DataSource.Workspaces.GetAll(Arg.Any <Func <IDatabaseWorkspace, bool> >())
                .Returns(Observable.Return(workspaces));

                var defaultWorkspace = await InteractorFactory.GetDefaultWorkspace().Execute();

                defaultWorkspace.Id.Should().Be(workspaceId);
            }
Esempio n. 8
0
        public bool PasswordIsValid(MockUser user, string password)
        {
            var hasher = new MockPasswordHasher();
            var hash   = hasher.CreateHash(password);

            return(hash.Equals(user.PasswordHash));
        }
Esempio n. 9
0
            public async Task UpdatesTheBeginningOfWeekProperty()
            {
                var oldBeginningOfWeek = BeginningOfWeek.Tuesday;
                var newBeginningOfWeek = BeginningOfWeek.Sunday;
                var oldUser            = new MockUser {
                    BeginningOfWeek = oldBeginningOfWeek
                };
                var newUser = new MockUser {
                    BeginningOfWeek = newBeginningOfWeek
                };

                UserSubject.OnNext(oldUser);
                View.Select(
                    Arg.Any <string>(),
                    Arg.Any <IEnumerable <SelectOption <BeginningOfWeek> > >(),
                    Arg.Any <int>())
                .Returns(Observable.Return(newBeginningOfWeek));
                InteractorFactory
                .UpdateUser(Arg.Any <EditUserDTO>())
                .Execute()
                .Returns(Observable.Return(newUser));

                ViewModel.SelectBeginningOfWeek.Execute();
                TestScheduler.Start();

                await InteractorFactory.UpdateUser(
                    Arg.Is <EditUserDTO>(dto => dto.BeginningOfWeek == newBeginningOfWeek
                                         )).Received().Execute();
            }
Esempio n. 10
0
        public void CreateUser(MockUser userToCreate)
        {
            if (userToCreate == null)
            {
                throw new ArgumentNullException("userToCreate");
            }

            //userToCreate.Validate();

            /*
             * Typical usage of DbContextScope for a read-write business transaction.
             * It's as simple as it looks.
             */
            using (var dbContextScope = _dbContextScopeFactory.Create())
            {
                //-- Build domain model
                var user = new User()
                {
                    Id               = userToCreate.Id,
                    Name             = userToCreate.Name,
                    Email            = userToCreate.Email,
                    WelcomeEmailSent = false,
                    CreatedOn        = DateTime.UtcNow
                };

                //-- Persist
                var addedUser = UserRepository.Add(user);
                int saveCount = dbContextScope.SaveChanges();

                //return addedUser;
            }
        }
Esempio n. 11
0
        public async Task <string> GenerateJwtTokenAsync(MockUser user)
        {
            //ключ щифрования токена
            var key      = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.Value.Secret));
            var algoritm = SecurityAlgorithms.HmacSha256;
            // подпись токена
            var credentials = new SigningCredentials(key, algoritm);

            // нужен пакет Identity.Model.Jwt
            //клаймы юзера в токене (тело токена)
            var claims = new[]
            {
                //кастомный клайм для хранения айди
                new Claim("ID", user.Id.ToString()),
                new Claim(ClaimTypes.Role, user.UserRole),
                //new Claim("Role",user.UserRole),
                new Claim(JwtRegisteredClaimNames.Email, user.Login),
                new Claim(JwtRegisteredClaimNames.Nbf, DateTime.Now.ToString()),
                new Claim(JwtRegisteredClaimNames.Exp, DateTime.Now.AddHours(options.Value.ExpireTime).ToString()),
            };

            //создаем токен
            var securityToken = new JwtSecurityToken(
                issuer: options.Value.Issuer,
                audience: options.Value.Audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddHours(options.Value.ExpireTime),
                signingCredentials: credentials
                );


            return(await Task.Run(() => new JwtSecurityTokenHandler().WriteToken(securityToken)));
        }
Esempio n. 12
0
 static ISqlCompiler GetSqlCompiler()
 {
     var compOpts = GetCompilerOptions();
     var user = new MockUser();
     var cohortOpts = Options.Create(new CohortOptions());
     return new SqlServerCompiler(user, compOpts, cohortOpts);
 }
Esempio n. 13
0
        protected override IAsyncResult BeginSubmitCore(EntityChangeSet changeSet, AsyncCallback callback, object userState)
        {
            Assert.AreEqual(0, changeSet.AddedEntities.Count,
                            "Change set should not contained added entities.");
            Assert.IsFalse(changeSet.IsEmpty,
                           "Change set should not be empty.");
            Assert.AreEqual(1, changeSet.ModifiedEntities.Count,
                            "Change set should contain a single modified entity.");
            Assert.AreEqual(0, changeSet.RemovedEntities.Count,
                            "Change set should not contained removed entities.");

            ChangeSetEntry[] submitOperations = changeSet.GetChangeSetEntries().ToArray();
            Assert.AreEqual(1, submitOperations.Length,
                            "A single submit operation is expected.");

            MockUser userToSubmit = (MockUser)submitOperations[0].Entity;
            MockUser userToReturn = new MockUser()
            {
                Name = userToSubmit.Name, Type = UserType.Saved
            };

            List <ChangeSetEntry> submitOperationsToReturn = new List <ChangeSetEntry>();

            submitOperationsToReturn.Add(new ChangeSetEntry(userToReturn, submitOperations[0].Id, submitOperations[0].Operation));

            this.Result = new AdcSubmitAsyncResult(changeSet, submitOperationsToReturn, userToReturn, callback, userState);
            return(this.Result);
        }
Esempio n. 14
0
        private static MockUser CreateUser(string userName)
        {
            MockUser user = new MockUser();

            user.Name     = userName;
            user.Platform = GamePlatform.PS4 | GamePlatform.PC;
            return(user);
        }
Esempio n. 15
0
        private void setupUserWithDefaultWorkspace(long?defaultWorkspaceId)
        {
            var user = new MockUser {
                DefaultWorkspaceId = defaultWorkspaceId
            };

            dataSource.User.Get().Returns(Observable.Return(user));
        }
        public async Task Given_AValidDateRangeEffectiveContractObjectId_When_DeleteIsInvoked_Then_DalUpdateMethodShouldBeInvokedWithUpdatedAuditInformation()
        {
            MockUser.SetupGet(m => m.Id).Returns(StaticTestValues.LastUpdatedByUserId2.Value);
            MockDateRangeEffectiveObjectsDal.Setup(m => m.Read(StaticTestValues.ValidId1)).ReturnsAsync(new DateRangeEffectiveDtoObject());

            await(await DateRangeEffectiveContractObjectsController.Delete(StaticTestValues.ValidId1)).ExecuteAsync(CancellationToken.None);

            MockDateRangeEffectiveObjectsDal.Verify(m => m.Update(It.Is <DateRangeEffectiveDtoObject>(c => c.LastUpdatedByUserId == StaticTestValues.LastUpdatedByUserId2 && c.LastUpdatedOn > DateTimeOffset.UtcNow.AddSeconds(-1) && c.LastUpdatedOn <DateTimeOffset.UtcNow.AddSeconds(1) && c.EffectiveEndDate> DateTimeOffset.UtcNow.AddSeconds(-1) && c.EffectiveEndDate < DateTimeOffset.UtcNow.AddSeconds(1))));
        }
Esempio n. 17
0
        public void TestSelectByNameorEmail()
        {
            MockUser tester = new MockUser();

            tester.createMockUser();
            User result = tester.getUserByNameOrEmail("ali", "*****@*****.**");

            Assert.IsNotNull(result, "Seharusnya not null");
        }
Esempio n. 18
0
        public void TestSelectByID()
        {
            MockUser tester = new MockUser();

            tester.createMockUser();
            List <User> result = tester.getUserByID(5);

            Assert.IsNotNull(result, "Seharusnya not null");
        }
Esempio n. 19
0
        static ISqlCompiler GetSqlCompiler()
        {
            var compOpts   = GetCompilerOptions();
            var user       = new MockUser();
            var cohortOpts = Options.Create(new CohortOptions {
                FieldCohortPersonId = "person_id", SetCohort = "app.Cohort"
            });

            return(new SqlServerCompiler(user, compOpts, cohortOpts));
        }
Esempio n. 20
0
        public void Test_ValidateNull()
        {
            MockUser mockUser = null;
            Action   validate = () => ValidationHelper.ValidateNull(_logger.Here(), mockUser);

            validate.Should().ThrowExactly <ArgumentNullException>();

            validate = () => ValidationHelper.ValidateNull(_logger.Here(), "test");
            validate.Should().NotThrow();
        }
Esempio n. 21
0
        public void TestSelectByEmail()
        {
            MockUser tester = new MockUser();

            tester.createMockUser();
            List <User> result = tester.getUserByEmail("asd");

            Assert.IsFalse(result.Any(), "harusnya false");
            //Assert.IsNotNull(result, "Seharusnya not null");
        }
        public async Task Given_AValidDateRangeEffectiveContractObject_When_PostIsInvoked_Then_DalCreateMethodShouldBeInvokedWithUpdatedAuditInformation()
        {
            MockUser.SetupGet(m => m.Id).Returns(StaticTestValues.CreatedByUserId2);
            MockContractValidator.Setup(m => m.ValidateContract(It.IsAny <DateRangeEffectiveContractObject>())).ReturnsAsync(new string[0]);
            MockDateRangeEffectiveObjectsDal.Setup(m => m.Create(It.IsAny <DateRangeEffectiveDtoObject>())).ReturnsAsync(new DateRangeEffectiveDtoObject());

            await(await DateRangeEffectiveContractObjectsController.Post(new DateRangeEffectiveContractObject())).ExecuteAsync(CancellationToken.None);

            MockDateRangeEffectiveObjectsDal.Verify(m => m.Create(It.Is <DateRangeEffectiveDtoObject>(c => c.LastUpdatedByUserId == null && c.LastUpdatedOn == null && c.CreatedByUserId == StaticTestValues.CreatedByUserId2 && c.CreatedOn > DateTimeOffset.UtcNow.AddSeconds(-1) && c.CreatedOn < DateTimeOffset.UtcNow.AddSeconds(1))));
        }
Esempio n. 23
0
        public void TestSelectMaxID()
        {
            MockUser tester = new MockUser();

            tester.createMockUser();
            int result   = tester.getMaxId();
            int expected = 3;

            Assert.AreEqual(result, expected, "Seharusnya 3");
        }
Esempio n. 24
0
        protected override IAsyncResult BeginQueryCore(EntityQuery query, AsyncCallback callback, object userState)
        {
            MockUser user = null;

            if (query.QueryName == "Login")
            {
                Assert.IsNotNull(query.Parameters,
                                 "Parameters should not be null.");
                Assert.IsTrue(query.Parameters.ContainsKey("UserName"),
                              "Parameters should contain UserName.");
                Assert.IsTrue(query.Parameters.ContainsKey("Password"),
                              "Parameters should contain Password.");
                Assert.IsTrue(query.Parameters.ContainsKey("IsPersistent"),
                              "Parameters should contain IsPersistent.");

                if (AuthenticationDomainClient.ValidUserName == (string)query.Parameters["UserName"])
                {
                    user = new MockUser()
                    {
                        Type = UserType.LoggedIn, Name = "LoggedIn"
                    };
                }
            }
            else if (query.QueryName == "Logout")
            {
                Assert.IsTrue((query.Parameters == null) || (query.Parameters.Count == 0),
                              "Logout operation is not expecting any parameters.");

                user = new MockUser()
                {
                    Type = UserType.LoggedOut
                };
            }
            else if (query.QueryName == "GetUser")
            {
                Assert.AreEqual("GetUser", query.QueryName,
                                "Operation should be GetUser.");
                Assert.IsTrue((query.Parameters == null) || (query.Parameters.Count == 0),
                              "GetUser operation is not expecting any parameters.");
                Assert.IsNull(query.Query,
                              "GetUser operation is not expecting a query.");

                user = new MockUser()
                {
                    Type = UserType.Loaded
                };
            }
            else
            {
                Assert.Fail("Only Login, Logout, and GetUser methods are supported for queries.");
            }

            this.Result = new AdcAsyncResult(user, callback, userState);
            return(this.Result);
        }
Esempio n. 25
0
        public async Task ProcessCommand_RandomCommands(string commands)
        {
            var mainUser  = new MockUser();
            var userLobby = new UserLobbyCommandProcessor();

            await userLobby.ProcessCommand(mainUser, new List <IUser> {
                mainUser
            }, commands);

            mainUser.VerifySendMessageCalledWith("INVAILD COMMAND\n");
        }
Esempio n. 26
0
        public async Task ProcessCommand_Help()
        {
            var mainUser  = new MockUser();
            var userLobby = new UserLobbyCommandProcessor();

            await userLobby.ProcessCommand(mainUser, new List <IUser> {
                mainUser
            }, "!:help");

            mainUser.VerifySendMessageCalledWith(GetHelp());
        }
Esempio n. 27
0
        public void TestSelectAllItem()
        {
            MockUser tester = new MockUser();

            tester.createMockUser();
            List <User> result   = tester.getAllUserTest();
            int         expected = 3;
            int         a        = result.Count;

            Assert.AreEqual(expected, a, "Seharusnya 3");
        }
Esempio n. 28
0
        public void GetAgencyFromUserID_ValidUser4()
        {
            SetMockDbTableConfiguration <Agencies>(MockAgencies.GetAgenciesDBList(), mockAgency);
            SetMockDbTableConfiguration <AgencieUsers>(MockUser.GetListAgencyUserDBModel(), mockUser);
            mockContext.Setup(m => m.Agencies).Returns(mockAgency.Object);
            mockContext.Setup(m => m.AgencyUsers).Returns(mockUser.Object);

            logic = new AgenciesLogic(mockContext.Object);

            Assert.IsTrue(logic.GetAgencyByUserId(4).Result);
        }
Esempio n. 29
0
        public void TestSelectByName()
        {
            MockUser tester = new MockUser();

            tester.createMockUser();
            List <User> result   = tester.getUserByName("ali");
            String      expected = "ali";
            User        testing  = result.FirstOrDefault();

            Assert.AreEqual(expected, testing.Name, "Seharusnya ali");
        }
Esempio n. 30
0
        public void ValidateUser_InvalidUser3()
        {
            SetMockDbTableConfiguration <Agencies>(MockAgencies.GetAgenciesDBList(), mockAgency);
            SetMockDbTableConfiguration <AgencieUsers>(MockUser.GetListAgencyUserDBModel(), mockUser);
            mockContext.Setup(m => m.Agencies).Returns(mockAgency.Object);
            mockContext.Setup(m => m.AgencyUsers).Returns(mockUser.Object);

            logic = new AgencyUserLogic(mockContext.Object);

            Assert.IsFalse(logic.ValidateUser(MockUser.InvalidUsers()[2]).Result);
        }
Esempio n. 31
0
 public static MockUser GetTestUserDefinition (string login, string group, bool admin, Int64 index)
 {
     var user = new MockUser
     {
         Login = login,
         Name = login,
         Desc = "TestUser",
         Password = "******",
         IsEnabled = true,
         IsSystemAdmin = admin,
         Group = group
     };
     var v = index.ToString ();
     user.Parameters.Add (v, v);
     user.List.Add (new KeyValueObj { Key = v, Value = v});
     return user;
 }
        protected override IAsyncResult BeginQueryCore(EntityQuery query, AsyncCallback callback, object userState)
        {
            MockUser user = null;

            if (query.QueryName == "Login")
            {
                Assert.IsNotNull(query.Parameters,
                    "Parameters should not be null.");
                Assert.IsTrue(query.Parameters.ContainsKey("UserName"),
                    "Parameters should contain UserName.");
                Assert.IsTrue(query.Parameters.ContainsKey("Password"),
                    "Parameters should contain Password.");
                Assert.IsTrue(query.Parameters.ContainsKey("IsPersistent"),
                    "Parameters should contain IsPersistent.");

                if (AuthenticationDomainClient.ValidUserName == (string)query.Parameters["UserName"])
                {
                    user = new MockUser() { Type = UserType.LoggedIn, Name = "LoggedIn" };
                }
            }
            else if (query.QueryName == "Logout")
            {
                Assert.IsTrue((query.Parameters == null) || (query.Parameters.Count == 0),
                    "Logout operation is not expecting any parameters.");

                user = new MockUser() { Type = UserType.LoggedOut };
            }
            else if (query.QueryName == "GetUser")
            {
                Assert.AreEqual("GetUser", query.QueryName,
                    "Operation should be GetUser.");
                Assert.IsTrue((query.Parameters == null) || (query.Parameters.Count == 0),
                    "GetUser operation is not expecting any parameters.");
                Assert.IsNull(query.Query,
                    "GetUser operation is not expecting a query.");

                user = new MockUser() { Type = UserType.Loaded };
            }
            else
            {
                Assert.Fail("Only Login, Logout, and GetUser methods are supported for queries.");
            }

            this.Result = new AdcAsyncResult(user, callback, userState);
            return this.Result;
        }
        protected override IAsyncResult BeginSubmitCore(EntityChangeSet changeSet, AsyncCallback callback, object userState)
        {
            Assert.AreEqual(0, changeSet.AddedEntities.Count,
                "Change set should not contained added entities.");
            Assert.IsFalse(changeSet.IsEmpty,
                "Change set should not be empty.");
            Assert.AreEqual(1, changeSet.ModifiedEntities.Count,
                "Change set should contain a single modified entity.");
            Assert.AreEqual(0, changeSet.RemovedEntities.Count,
                "Change set should not contained removed entities.");

            ChangeSetEntry[] submitOperations = changeSet.GetChangeSetEntries().ToArray();
            Assert.AreEqual(1, submitOperations.Length,
                "A single submit operation is expected.");

            MockUser userToSubmit = (MockUser)submitOperations[0].Entity;
            MockUser userToReturn = new MockUser() { Name = userToSubmit.Name, Type = UserType.Saved };

            List<ChangeSetEntry> submitOperationsToReturn = new List<ChangeSetEntry>();
            submitOperationsToReturn.Add(new ChangeSetEntry(userToReturn, submitOperations[0].Id, submitOperations[0].Operation));

            this.Result = new AdcSubmitAsyncResult(changeSet, submitOperationsToReturn, userToReturn, callback, userState);
            return this.Result;
        }
 public AdcAsyncResult(MockUser user, AsyncCallback asyncCallback, object asyncState)
     : base(asyncCallback, asyncState)
 {
     this._user = user;
 }
        public void Authorization_Custom_Authorization_On_Invoke()
        {
            // Specifically, the City data is marked so that no one can delete a Zip code
            // from WA unless their user name is WAGuy
            MockUser notWaGuy = new MockUser("notWAGuy");
            notWaGuy.IsAuthenticated = true;

            DomainServiceDescription serviceDescription = DomainServiceDescription.GetDescription(typeof(CityDomainService));
            DomainOperationEntry invokeOperation = serviceDescription.GetInvokeOperation("GetStateIfUser");
            Assert.IsNotNull(invokeOperation, "Could not locate GetStateIfUser Invoke operation");
            DomainOperationEntry getCitiesQuery = serviceDescription.GetQueryMethod("GetCities");

            City city = null;

            // Execute a query to get a City from WA
            using (CityDomainService cities = new CityDomainService())
            {
                // Now prepare for a query to find a Zip in WA
                DomainServiceContext ctxt = new DomainServiceContext(new MockDataService(notWaGuy), DomainOperationType.Query);
                cities.Initialize(ctxt);

                int count = -1;
                IEnumerable<ValidationResult> validationErrors = null;
                IEnumerable result = cities.Query(new QueryDescription(getCitiesQuery), out validationErrors, out count);

                city = result.OfType<City>().FirstOrDefault(z => z.StateName == "WA");
                Assert.IsNotNull(city, "Could not find a city in WA");
            }

            // Perform an invoke against a method that has a custom auth attribute requiring WaGuy
            // where the user is something else -- should be denied
            using (CityDomainService cities = new CityDomainService())
            {
                // Prepare an invoke to call a method that has a custom auth attribute
                DomainServiceContext ctxt = new DomainServiceContext(new MockDataService(notWaGuy), DomainOperationType.Invoke);
                cities.Initialize(ctxt);

                // verify that even top level exceptions go through
                // the OnError handler
                IEnumerable<ValidationResult> validationErrors;
                UnauthorizedAccessException expectedException = null;
                try
                {
                    // cause a domain service not initialized exception
                    cities.Invoke(new InvokeDescription(invokeOperation, new object[] { city }), out validationErrors);
                }
                catch (UnauthorizedAccessException e)
                {
                    expectedException = e;
                }

                Assert.IsNotNull(expectedException, "Expected Invoke to be denied");
                Assert.AreEqual("Access to operation 'GetStateIfUser' was denied.", expectedException.Message);
            }

            // Perform an invoke against a method that has a custom auth attribute requiring WaGuy
            // where the user is correct -- should be allowed
            using (CityDomainService cities = new CityDomainService())
            {
                MockUser waGuy = new MockUser("WAGuy");
                waGuy.IsAuthenticated = true;

                // Prepare an invoke to call a method that has a custom auth attribute
                DomainServiceContext ctxt = new DomainServiceContext(new MockDataService(waGuy), DomainOperationType.Invoke);
                cities.Initialize(ctxt);

                // verify that even top level exceptions go through
                // the OnError handler
                IEnumerable<ValidationResult> validationErrors;
                UnauthorizedAccessException expectedException = null;
                try
                {
                    // cause a domain service not initialized exception
                    cities.Invoke(new InvokeDescription(invokeOperation, new object[] { city }), out validationErrors);
                }
                catch (UnauthorizedAccessException e)
                {
                    expectedException = e;
                }

                Assert.IsNull(expectedException, "Expected Invoke to be allowed");
            }
        }
 public AdcSubmitAsyncResult(EntityChangeSet changeSet, IEnumerable<ChangeSetEntry> submitOperations, MockUser user, AsyncCallback asyncCallback, object asyncState)
     : base(user, asyncCallback, asyncState)
 {
     this._changeSet = changeSet;
     this._submitOperations = submitOperations;
 }
        public void Authorization_Custom_Authorization_On_Query()
        {
            int count;
            CityDomainService cities = new CityDomainService();
            DomainServiceDescription serviceDescription = DomainServiceDescription.GetDescription(typeof(CityDomainService));
            DomainOperationEntry getZipsIfUser = serviceDescription.GetQueryMethod("GetZipsIfUser");

            // The attribute permits only a user named mathew to access the query
            MockUser user = new MockUser("NotZipGuy");
            MockDataService dataService = new MockDataService(user);
            cities.Initialize(new DomainServiceContext(dataService, DomainOperationType.Query));

            // not authenticated should be denied cleanly because there is no user name
            Exception expectedException = null;
            System.Collections.IEnumerable result;
            IEnumerable<ValidationResult> validationErrors = null;
            try
            {
                user.IsAuthenticated = false;
                result = cities.Query(new QueryDescription(getZipsIfUser), out validationErrors, out count);
            }
            catch (UnauthorizedAccessException e)
            {
                expectedException = e;
            }
            Assert.IsNotNull(expectedException);
            Assert.AreEqual("Only one user is authorized for this query, and it isn't you.", expectedException.Message, "Expected this custom authorization deny message for non-authenticated user.");
            Assert.IsNull(validationErrors);

            // Authenticated, but still not the right user name -- should be denied
            cities = new CityDomainService();
            expectedException = null;
            user = new MockUser("NotZipGuy", new string[] { "clerk" });
            user.IsAuthenticated = true;
            dataService = new MockDataService(user);
            cities.Initialize(new DomainServiceContext(dataService, DomainOperationType.Query));
            try
            {
                result = cities.Query(new QueryDescription(getZipsIfUser), out validationErrors, out count);
            }
            catch (UnauthorizedAccessException e)
            {
                expectedException = e;
            }
            Assert.IsNotNull(expectedException);
            Assert.AreEqual("Only one user is authorized for this query, and it isn't you.", expectedException.Message, "Expected this custom authorization deny message for authenticated user with wrong name.");
            Assert.IsNull(validationErrors);

            // authenticated and in with the right name -- should be allowed
            cities = new CityDomainService();
            expectedException = null;
            user = new MockUser("ZipGuy");
            user.IsAuthenticated = true;
            dataService = new MockDataService(user);
            cities.Initialize(new DomainServiceContext(dataService, DomainOperationType.Query));
            result = cities.Query(new QueryDescription(getZipsIfUser), out validationErrors, out count);
            Assert.IsNotNull(result);
            Assert.IsNull(validationErrors);
            Assert.IsTrue(result.OfType<Zip>().Any(), "Expected non-zero number of zip codes returned");
        }
        public void Authorization_MockUser()
        {
            int count;
            CityDomainService cities = new CityDomainService();
            DomainServiceDescription serviceDescription = DomainServiceDescription.GetDescription(typeof(CityDomainService));
            DomainOperationEntry getZipsIfAuthenticated = serviceDescription.GetQueryMethod("GetZipsIfAuthenticated");
            DomainOperationEntry getZipsIfInRole = serviceDescription.GetQueryMethod("GetZipsIfInRole");

            // Validate a null principal is denied
            MockUser user = null;
            MockDataService dataService = new MockDataService(user);
            cities.Initialize(new DomainServiceContext(dataService, DomainOperationType.Query));
            Exception expectedException = null;
            System.Collections.IEnumerable result;
            IEnumerable<ValidationResult> validationErrors = null;
            try
            {
                result = cities.Query(new QueryDescription(getZipsIfAuthenticated), out validationErrors, out count);
            }
            catch (UnauthorizedAccessException e)
            {
                expectedException = e;
            }
            Assert.IsNotNull(expectedException);
            Assert.IsNull(validationErrors);
            Assert.AreEqual("Access to operation 'GetZipsIfAuthenticated' was denied.", expectedException.Message, "Expected standard deny message for null principal");

            // Validate a non-authenticated user is denied
            user = new MockUser("mathew");
            dataService = new MockDataService(user);
            cities = new CityDomainService();
            cities.Initialize(new DomainServiceContext(dataService, DomainOperationType.Query));

            expectedException = null;
            validationErrors = null;
            try
            {
                user.IsAuthenticated = false;
                result = cities.Query(new QueryDescription(getZipsIfAuthenticated), out validationErrors, out count);
            }
            catch (UnauthorizedAccessException e)
            {
                expectedException = e;
            }
            Assert.IsNotNull(expectedException);
            Assert.IsNull(validationErrors);

            // we're authenticated, so this should succeed
            expectedException = null;
            user.IsAuthenticated = true;
            result = cities.Query(new QueryDescription(getZipsIfAuthenticated), out validationErrors, out count);
            Assert.IsNotNull(result);
            Assert.IsNull(validationErrors);

            // authenticated, but not in role, so we should fail
            cities = new CityDomainService();
            expectedException = null;
            user = new MockUser("mathew", new string[] { "clerk" });
            user.IsAuthenticated = true;
            dataService = new MockDataService(user);
            cities.Initialize(new DomainServiceContext(dataService, DomainOperationType.Query));
            try
            {
                result = cities.Query(new QueryDescription(getZipsIfInRole), out validationErrors, out count);
            }
            catch (UnauthorizedAccessException e)
            {
                expectedException = e;
            }
            Assert.IsNotNull(expectedException);
            Assert.IsNull(validationErrors);

            // authenticated and in role, so we should succeed
            cities = new CityDomainService();
            expectedException = null;
            user = new MockUser("mathew", new string[] { "manager" });
            user.IsAuthenticated = true;
            dataService = new MockDataService(user);
            cities.Initialize(new DomainServiceContext(dataService, DomainOperationType.Query));
            result = cities.Query(new QueryDescription(getZipsIfInRole), out validationErrors, out count);
            Assert.IsNotNull(result);
            Assert.IsNull(validationErrors);
        }
        public void Authorization_Custom_Authorization_On_CUD()
        {
            // Specifically, the City data is marked so that no one can delete a Zip code
            // from WA unless their user name is WAGuy
            MockUser notWaGuy = new MockUser("notWAGuy");
            notWaGuy.IsAuthenticated = true;

            DomainServiceDescription serviceDescription = DomainServiceDescription.GetDescription(typeof(CityDomainService));
            Zip zip = null;

            // First execute a query to get some zips
            DomainOperationEntry getZipsQuery = serviceDescription.GetQueryMethod("GetZips");
            DomainServiceContext ctxt = new DomainServiceContext(new MockDataService(notWaGuy), DomainOperationType.Query);

            using (CityDomainService cities = new CityDomainService())
            {
                // Now prepare for a query to find a Zip in WA
                ctxt = new DomainServiceContext(new MockDataService(notWaGuy), DomainOperationType.Query);
                cities.Initialize(ctxt);

                int count = -1;
                IEnumerable<ValidationResult> validationErrors = null;
                IEnumerable result = cities.Query(new QueryDescription(getZipsQuery), out validationErrors, out count);

                zip = result.OfType<Zip>().FirstOrDefault(z => z.StateName == "WA");
                Assert.IsNotNull(zip, "Could not find a zip code in WA");
            }

            // Prepare a submit to delete this zip from a user who is not authorized
            using (CityDomainService cities = new CityDomainService())
            {
                // Now prepare for a query to find a Zip in WA
                ctxt = new DomainServiceContext(new MockDataService(notWaGuy), DomainOperationType.Submit);
                cities.Initialize(ctxt);

                // Prepare an attempt to delete this with a user whose name is not WAGuy
                // This should fail due to a custom auth attribute
                List<ChangeSetEntry> entries = new List<ChangeSetEntry>();

                ChangeSetEntry entry = new ChangeSetEntry(1, zip, zip, DomainOperation.Delete);
                entries.Add(entry);
                UnauthorizedAccessException exception = null;
                try
                {
                    ChangeSetProcessor.Process(cities, entries);
                }
                catch (UnauthorizedAccessException ex)
                {
                    exception = ex;
                }
                Assert.IsNotNull(exception, "Expected failure attempting to delete a zip from WA with inappropriate user name");
                Assert.AreEqual("Only one user can delete zip codes from that state, and it isn't you.", exception.Message);
            }

            // Now do that again but with a user who is WAGuy -- it should succeed
            using (CityDomainService cities = new CityDomainService())
            {
                MockUser waGuy = new MockUser("WAGuy");
                waGuy.IsAuthenticated = true;

                // Now try a submit where the user *is* Mathew to validate we succeed
                ctxt = new DomainServiceContext(new MockDataService(waGuy), DomainOperationType.Submit);
                cities.Initialize(ctxt);
                List<ChangeSetEntry> entries = new List<ChangeSetEntry>();

                ChangeSetEntry entry = new ChangeSetEntry(1, zip, zip, DomainOperation.Delete);
                entries.Add(entry);
                Exception exception = null;
                try
                {
                    ChangeSetProcessor.Process(cities, entries);
                }
                catch (UnauthorizedAccessException ex)
                {
                    exception = ex;
                }
                Assert.IsNull(exception, "Expected success attempting to delete a zip from WA with inappropriate user name");
            }
        }
        public void Authorization_Custom_Authorization_On_Custom_Update()
        {
            // Specifically, the City data is marked so that no one can delete a Zip code
            // from WA unless their user name is WAGuy
            MockUser notWaGuy = new MockUser("notWAGuy");
            notWaGuy.IsAuthenticated = true;

            DomainServiceDescription serviceDescription = DomainServiceDescription.GetDescription(typeof(CityDomainService));
            City city = null;

            // Execute a query to get a City from WA
            using (CityDomainService cities = new CityDomainService())
            {
                DomainOperationEntry getCitiesQuery = serviceDescription.GetQueryMethod("GetCities");

                // Now prepare for a query to find a Zip in WA
                DomainServiceContext ctxt = new DomainServiceContext(new MockDataService(notWaGuy), DomainOperationType.Query);
                cities.Initialize(ctxt);

                int count = -1;
                IEnumerable<ValidationResult> validationErrors = null;
                IEnumerable result = cities.Query(new QueryDescription(getCitiesQuery), out validationErrors, out count);

                city = result.OfType<City>().FirstOrDefault(z => z.StateName == "WA");
                Assert.IsNotNull(city, "Could not find a city in WA");
            }


            using (CityDomainService cities = new CityDomainService())
            {
                // Now prepare for a submit to invoke AssignCityZoneIfAuthorized as a named update method
                DomainServiceContext ctxt = new DomainServiceContext(new MockDataService(notWaGuy), DomainOperationType.Submit);
                cities.Initialize(ctxt);

                // Prepare an attempt to delete this with a user whose name is not WAGuy
                // This should fail due to a custom auth attribute
                List<ChangeSetEntry> entries = new List<ChangeSetEntry>();

                ChangeSetEntry entry = new ChangeSetEntry();
                entry.DomainOperationEntry = serviceDescription.GetCustomMethod(typeof(City), "AssignCityZoneIfAuthorized");
                entry.EntityActions = new EntityActionCollection { { "AssignCityZoneIfAuthorized", new object[] { "SomeZone" } } };
                entry.Operation = DomainOperation.Update;
                entry.Entity = city;
                entries.Add(entry);

                UnauthorizedAccessException exception = null;
                try
                {
                    ChangeSetProcessor.Process(cities, entries);
                }
                catch (UnauthorizedAccessException ex)
                {
                    exception = ex;
                }
                Assert.IsNotNull(exception, "Expected failure attempting to perform custom method on WA with inappropriate user name");
                Assert.AreEqual("Only one user is authorized to execute operation 'AssignCityZoneIfAuthorized', and it isn't you.", exception.Message);
            }

            // Now do that again but with a user who is WAGuy -- it should succeed
            using (CityDomainService cities = new CityDomainService())
            {
                MockUser waGuy = new MockUser("WAGuy");
                waGuy.IsAuthenticated = true;

                // Now prepare for a submit to invoke AssignCityZoneIfAuthorized as a named update method
                DomainServiceContext ctxt = new DomainServiceContext(new MockDataService(waGuy), DomainOperationType.Submit);
                cities.Initialize(ctxt);

                // Prepare an attempt to delete this with a user whose name is not WAGuy
                // This should fail due to a custom auth attribute

                // Prepare a submit to call the AssignCityZoneIfAuthorized with an unauthorized user
                List<ChangeSetEntry> entries = new List<ChangeSetEntry>();

                ChangeSetEntry entry = new ChangeSetEntry();
                entry.DomainOperationEntry = serviceDescription.GetCustomMethod(typeof(City), "AssignCityZoneIfAuthorized");
                entry.EntityActions = new EntityActionCollection { { "AssignCityZoneIfAuthorized", new object[] { "SomeZone" } } };
                entry.Operation = DomainOperation.Update;
                entry.Entity = city;
                entries.Add(entry);

                Exception exception = null;
                try
                {
                    ChangeSetProcessor.Process(cities, entries);
                }
                catch (UnauthorizedAccessException ex)
                {
                    exception = ex;
                }
                Assert.IsNull(exception, "Expected success attempting to delete a zip from WA with inappropriate user name");
            }
        }