Пример #1
0
        public void Create_WithUsernameAndPassword_CreatesUser()
        {
            var givenEmail    = "email";
            var givenPassword = "******";
            var result        = _subject.Create(givenEmail, givenPassword);

            Assert.NotNull(result);
            Assert.NotNull(result.EmailAddress);
            Assert.NotNull(result.Password);
        }
Пример #2
0
        private void Subscribe_Btn(object sender, RoutedEventArgs e)
        {
            if (AreUserFieldsOk())
            {
                string   login        = Login_TxtBox.Text;
                string   password     = Password_Box.Password;
                DateTime birthday     = (DateTime)Birthday_DatePicker.SelectedDate;
                short    streetNumber = Convert.ToInt16(StreetNumber_TxtBox.Text);
                string   streetName   = StreetName_TxtBox.Text;
                string   cityName     = CityName_TxtBox.Text;
                string   postalCode   = PostalCode_TxtBox.Text;
                Region   region       = (Region)Region_cmbBox.SelectedItem;

                City    city              = CityFactory.Get(cityName, postalCode, region);
                Address address           = AddressFactory.Get(streetNumber, streetName, city);
                string  encryptedPassword = Password.Encrypt(password.ToString());

                if (!User.IsInDb(login, encryptedPassword))
                {
                    User user = UserFactory.Create(login, encryptedPassword, birthday, address);
                    DialogBox.Ok("Success", "User has been correctly recorded");
                    ResetInscription();
                }
                else
                {
                    DialogBox.Ok("Error", "Check fields");
                }
            }
            else
            {
                DialogBox.Ok("Error", "Check fields");
            }
        }
Пример #3
0
        public GetTransitStateWithEntryOrExitDataHandlerTests()
        {
            mapper = A.Fake <IMapper>();
            transportRouteRepository = A.Fake <ITransportRouteRepository>();

            var context = new TestIwsContext();

            context.Users.Add(UserFactory.Create(TestIwsContext.UserId, AnyString, AnyString, AnyString, AnyString));
            context.EntryOrExitPoints.AddRange(new List <EntryOrExitPoint>(EntryExitPoints)
            {
                new TestableEntryOrExitPoint()
                {
                    Country = new TestableCountry()
                    {
                        Id = countryId
                    }
                },
                new TestableEntryOrExitPoint()
                {
                    Country = new TestableCountry()
                    {
                        Id = countryId
                    }
                }
            });

            A.CallTo(() => mapper.Map <EntryOrExitPointData>(A <EntryOrExitPoint> .Ignored))
            .Returns(new EntryOrExitPointData()
            {
                CountryId = countryId, Name = AnyString
            });

            handler = new GetTransitStateWithEntryOrExitDataHandler(context, mapper, transportRouteRepository);
        }
Пример #4
0
        public InternalUserCollection()
        {
            Users = new[]
            {
                InternalUserFactory.Create(AdminPendingId,
                                           UserFactory.Create(AdminPendingUserId, AnyString, AnyString, AnyString,
                                                              AnyString)),
                InternalUserFactory.Create(AdminApprovedId, UserFactory.Create(AdminApprovedUserId, AnyString, AnyString, AnyString,
                                                                               AnyString)),
                InternalUserFactory.Create(AdminRejectedId, UserFactory.Create(AdminRejectedUserId, AnyString, AnyString, AnyString,
                                                                               AnyString)),
                InternalUserFactory.Create(ThisUserAdminPendingId, UserFactory.Create(ThisUserAdminPendingUserId, AnyString, AnyString, AnyString,
                                                                                      AnyString)),
                InternalUserFactory.Create(ThisUserAdminApprovedId, UserFactory.Create(ThisUserAdminApprovedUserId, AnyString, AnyString, AnyString,
                                                                                       AnyString))
            };

            foreach (var user in Users)
            {
                SetEmailConfirmed(user.User, true);
            }

            SetInternalUserStatus(Users[AdminPendingIndex], InternalUserStatus.Pending);
            SetInternalUserStatus(Users[AdminApprovedIndex], InternalUserStatus.Approved);
            SetInternalUserStatus(Users[AdminRejectedIndex], InternalUserStatus.Rejected);
            SetInternalUserStatus(Users[ThisUserAdminPendingIndex], InternalUserStatus.Pending);
            SetInternalUserStatus(Users[ThisUserAdminApprovedIndex], InternalUserStatus.Approved);
        }
Пример #5
0
        public AMFUserLogin Register(String firstName, String lastName, String userName, string password, string passwordHint, String USAHockeyNum, String DOB, String Address1, String Address2, String City, String State, String ZipCode, String Phone1, String Phone2, String Emergency1, String Emergency2, String YearsExp, PlayerLevel playerLevel, String Internet, String Referral, String Tournament, String Other)
        {
            AMFUserLogin retVal = null;

            AMFUserLogin userLogin = UserFactory.Create(userName, password, firstName, lastName, passwordHint);

            userLogin.USAHockeyNum = USAHockeyNum;
            userLogin.DOB          = DOB;
            userLogin.Address1     = Address1;
            userLogin.Address2     = Address2;
            userLogin.City         = City;
            userLogin.State        = State;
            userLogin.ZipCode      = ZipCode;
            userLogin.Phone1       = Phone1;
            userLogin.Phone2       = Phone2;
            userLogin.Emergency1   = Emergency1;
            userLogin.Emergency2   = Emergency2;
            userLogin.YearsExp     = YearsExp;
            userLogin.Level        = playerLevel;
            userLogin.Internet     = Internet;
            userLogin.Referral     = Referral;
            userLogin.Tournament   = Tournament;
            userLogin.Other        = Other;
            retVal = this.UserRepository.Save(userLogin);

            return(retVal);
        }
Пример #6
0
        public async Task <IActionResult> Register([FromBody] RegistrationInformation registrationInformation)
        {
            if (string.IsNullOrWhiteSpace(registrationInformation.Username))
            {
                return(BadRequest("Username must not be empty"));
            }
            if (string.IsNullOrEmpty(registrationInformation.Password))
            {
                return(BadRequest("Password must not be empty"));
            }
            if (string.IsNullOrWhiteSpace(registrationInformation.Email))
            {
                return(BadRequest("Email must not be empty"));
            }
            var existingUser = await authenticationModule.FindUserAsync(registrationInformation.Username);

            if (existingUser != null)
            {
                return(Conflict($"User '{registrationInformation.Username}' already exists"));
            }

            var newUser = UserFactory.Create(registrationInformation);

            if (!await authenticationModule.CreateUserAsync(newUser))
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
            apiEventLogger.Log(LogLevel.Info, $"New user '{newUser.UserName}' added");
            return(Ok());
        }
Пример #7
0
        private void LearnLogic_CopyToFinished(object sender, EventArgs e)
        {
            LearnLogic.CopyToFinished -= new EventHandler(LearnLogic_CopyToFinished);
            HideStatusMessage();

            if (cleanUpOdx)
            {
                ConnectionStringStruct css = new ConnectionStringStruct(DatabaseType.Xml, Path.GetDirectoryName(odxFile), odxFile, true);
                IUser xmlUser = UserFactory.Create((GetLoginInformation) delegate(UserStruct u, ConnectionStringStruct c) { return(u); },
                                                   css, DataAccessError, null);
                xmlUser.List().Delete(css);
            }
            else
            {
                FileInfo fi = new FileInfo(odxFile);
                if (File.Exists(odxFile + ".bak"))
                {
                    try
                    {
                        File.Delete(odxFile + ".bak");
                    }
                    catch { }
                }
                try
                {
                    fi.MoveTo(odxFile + ".bak");
                }
                catch { }
            }
            OnConvertedFinish(new ConvertingEventArgs(edbFile));
        }
Пример #8
0
 /// <summary>
 /// 转换为用户实体
 /// </summary>
 /// <param name="dto">用户数据传输对象</param>
 public static User ToEntity3(this UserDto dto)
 {
     if (dto == null)
     {
         return(new User());
     }
     return(UserFactory.Create(
                userId: dto.Id.ToGuid(),
                eId: dto.EId,
                organizationsId: dto.OrganizationsId,
                merchantId: dto.MerchantId,
                accountId: dto.AccountId,
                registerTime: dto.RegisterTime,
                isLocked: dto.IsLocked,
                lockBeginTime: dto.LockBeginTime,
                lockDuration: dto.LockDuration,
                lockMessage: dto.LockMessage,
                lastLoginTime: dto.LastLoginTime,
                lastLoginIp: dto.LastLoginIp,
                currentLoginTime: dto.CurrentLoginTime,
                currentLoginIp: dto.CurrentLoginIp,
                creationTime: dto.CreationTime,
                creatorId: dto.CreatorId,
                lastModificationTime: dto.LastModificationTime,
                lastModifierId: dto.LastModifierId,
                isDeleted: dto.IsDeleted,
                version: dto.Version
                ));
 }
Пример #9
0
        public SetMovementPartialRejectedHandlerTests()
        {
            var context = new TestIwsContext();

            context.Users.Add(UserFactory.Create(TestIwsContext.UserId, AnyString, AnyString, AnyString, AnyString));

            notificationId = Guid.NewGuid();
            movementId     = Guid.NewGuid();
            rejectDate     = SystemTime.UtcNow;
            wasteDate      = SystemTime.UtcNow;

            partialRejectionMovement = A.Fake <IPartialRejectionMovement>();
            movementRepository       = A.Fake <IMovementRepository>();
            var notificationRepository = A.Fake <INotificationApplicationRepository>();
            var userContext            = A.Fake <IUserContext>();

            A.CallTo(() => notificationRepository.GetById(notificationId))
            .Returns(new TestableNotificationApplication()
            {
                NotificationNumber = NotificatioNumber
            });

            A.CallTo(() => userContext.UserId).Returns(TestIwsContext.UserId);

            handler = new RecordPartialRejectionInternalHandler(partialRejectionMovement, context);
        }
Пример #10
0
        public UpdateTransitStateEntryOrExitHandlerTests()
        {
            transportRouteRepository = A.Fake <ITransportRouteRepository>();

            var context = new TestIwsContext();

            context.Users.Add(UserFactory.Create(TestIwsContext.UserId, AnyString, AnyString, AnyString, AnyString));
            context.EntryOrExitPoints.AddRange(new List <EntryOrExitPoint>(EntryExitPoints)
            {
                new TestableEntryOrExitPoint()
                {
                    Id      = entryPointId,
                    Country = new TestableCountry()
                    {
                        Id = countryId
                    }
                },
                new TestableEntryOrExitPoint()
                {
                    Id      = exitPointId,
                    Country = new TestableCountry()
                    {
                        Id = countryId
                    }
                }
            });

            handler = new UpdateTransitStateEntryOrExitHandler(context, transportRouteRepository);
        }
Пример #11
0
        public SetMultipleMovementFileIdHandlerTests()
        {
            var context = new TestIwsContext();

            context.Users.Add(UserFactory.Create(TestIwsContext.UserId, AnyString, AnyString, AnyString, AnyString));

            notificationId = Guid.NewGuid();
            fileId         = Guid.NewGuid();
            var userId = TestIwsContext.UserId;

            movementRepository      = A.Fake <IMovementRepository>();
            notificationRepository  = A.Fake <INotificationApplicationRepository>();
            fileRepository          = A.Fake <IFileRepository>();
            movementAuditRepository = A.Fake <IMovementAuditRepository>();
            var userContext = A.Fake <IUserContext>();

            A.CallTo(() => notificationRepository.GetById(notificationId))
            .Returns(new TestableNotificationApplication()
            {
                NotificationNumber = NotificatioNumber
            });

            A.CallTo(() => fileRepository.Store(A <File> .Ignored)).Returns(fileId);

            A.CallTo(() => userContext.UserId).Returns(userId);

            handler = new SetMultipleMovementFileIdHandler(context, movementRepository, notificationRepository,
                                                           fileRepository, movementAuditRepository, userContext);
        }
Пример #12
0
        public SharedUserRepositoryTests()
        {
            ownerUser = UserFactory.Create(Guid.NewGuid(), "Owner", "User", "12345",
                                           "*****@*****.**");
            sharedUser = UserFactory.Create(Guid.NewGuid(), "Shared", "User", "12345",
                                            "*****@*****.**");

            var userContext = A.Fake <IUserContext>();

            A.CallTo(() => userContext.UserId).Returns(Guid.Parse(ownerUser.Id));

            context       = new IwsContext(userContext, A.Fake <IEventDispatcher>());
            authorization = A.Fake <INotificationApplicationAuthorization>();
            repository    = new SharedUserRepository(context, authorization);

            preRunNotifications = context.NotificationApplications.Select(na => na.Id).ToArray();

            notification = NotificationApplicationFactory.Create(Guid.Parse(ownerUser.Id), NotificationType.Recovery,
                                                                 UKCompetentAuthority.England, 20191);

            context.Users.Add(ownerUser);
            context.Users.Add(sharedUser);
            context.NotificationApplications.Add(notification);
            context.SaveChanges();
        }
Пример #13
0
        public UserViewModel(PizzaStoreDBContext dbo)
        {
            var UF = new UserFactory();

            User = UF.Create();
            _db  = dbo;
        }
Пример #14
0
        public void LoginUserProfileTest()
        {
            TestInfrastructure.DebugLineStart(TestContext);
            if (TestInfrastructure.IsActive(TestContext))
            {
                using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, string.Empty))
                {
                    IList <UserStruct> users;
                    if (writeLM.IsDB)
                    {
                        users = UserFactory.GetUserList(writeLM.Parent.CurrentUser.ConnectionString);
                    }

                    if (writeLM.Parent.CurrentUser.ConnectionString.Typ != DatabaseType.MsSqlCe)
                    {
                        IUser user = (IUser)UserFactory.Create((GetLoginInformation)GetUserAdmin, writeLM.Parent.CurrentUser.ConnectionString,
                                                               (DataAccessErrorDelegate) delegate { return; }, TestContext);

                        //before: 7ff135854376850e9711bd75ce942e07
                        Assert.AreEqual <string>(TestInfrastructure.SupportsNullableValues(TestContext) ? "21232f297a57a5a743894a0e4a801fc3" : string.Empty,
                                                 user.Password, "Password isnt't encrypted properly");
                        Assert.AreEqual <string>(TestInfrastructure.SupportsNullableValues(TestContext) ?
                                                 GetUserAdmin(new UserStruct(), new ConnectionStringStruct()).Value.UserName : string.Empty,
                                                 user.UserName, "UserName isn't saved properly");
                    }
                    else
                    {
                        Assert.AreEqual <string>(WindowsIdentity.GetCurrent().Name.ToLower(), writeLM.Parent.CurrentUser.UserName.ToLower());
                    }
                }
            }
            TestInfrastructure.DebugLineEnd(TestContext);
        }
Пример #15
0
        public SaveMovementCompletedReceiptHandlerTests()
        {
            var context = new TestIwsContext();

            context.Users.Add(UserFactory.Create(TestIwsContext.UserId, AnyString, AnyString, AnyString, AnyString));

            notificationId = Guid.NewGuid();
            movementId     = Guid.NewGuid();
            fileId         = Guid.NewGuid();

            var userContext = A.Fake <IUserContext>();

            movementRepository      = A.Fake <IMovementRepository>();
            fileRepository          = A.Fake <IFileRepository>();
            notificationRepository  = A.Fake <INotificationApplicationRepository>();
            movementAuditRepository = A.Fake <IMovementAuditRepository>();

            A.CallTo(() => notificationRepository.GetById(notificationId))
            .Returns(new TestableNotificationApplication()
            {
                NotificationNumber = NotificationNumber
            });

            A.CallTo(() => fileRepository.Store(A <File> .Ignored)).Returns(fileId);

            var nameGenerator      = new CertificateOfRecoveryNameGenerator(notificationRepository);
            var certificateFactory = new CertificateFactory();

            handler = new SaveMovementCompletedReceiptHandler(context, fileRepository, movementRepository,
                                                              certificateFactory, nameGenerator, userContext, notificationRepository, movementAuditRepository);
        }
Пример #16
0
        public async Task <IDataResult <Int64> > AddAsync(AddUserModel addUserModel)
        {
            if (addUserModel is null)
            {
                throw new ArgumentNullException(nameof(addUserModel));
            }

            var validation = new AddUserModelValidator().Validate(addUserModel);

            if (validation.IsError)
            {
                return(DataResult <Int64> .Error(validation.Message));
            }

            addUserModel.SignIn = _signInService.CreateSignIn(addUserModel.SignIn);

            var userEntity = UserFactory.Create(addUserModel);

            userEntity.Add();

            await _userRepository.AddAsync(userEntity).ConfigureAwait(false);

            await _unitOfWork.SaveChangesAsync().ConfigureAwait(false);

            return(DataResult <Int64> .Success(userEntity.Id));
        }
Пример #17
0
        public int CreateUser(string userName, string displayName, string password, string email, int role, string createdBy)
        {
            var hashPassword = _encryptor.Encode(password);
            var user         = UserFactory.Create(userName, displayName, hashPassword, email, role, createdBy);

            return(CreateUser(user));
        }
Пример #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CollectorForm"/> class.
        /// </summary>
        /// <remarks>Documented by Dev05, 2007-09-27</remarks>
        public CollectorForm()
        {
            InitializeComponent();
            cardEdit.HelpNamespace = this.HelpFile;

            OpenFileDialog openDlg = new OpenFileDialog();

            openDlg.Filter = "Dictionary|*.odx";
            if (openDlg.ShowDialog() == DialogResult.OK)
            {
                if (dictionary != null)
                {
                    dictionary.Dispose();
                }
                MLifter.DAL.Interfaces.IUser user = UserFactory.Create((GetLoginInformation)MLifter.Controls.LoginForm.OpenLoginForm,
                                                                       new ConnectionStringStruct(DatabaseType.Xml, openDlg.FileName, true),
                                                                       (DataAccessErrorDelegate) delegate(object sender, Exception e) { MessageBox.Show(e.ToString()); }, this);
                dictionary = new Dictionary(user.Open(), null);
            }
            else
            {
                Close();
            }

            tableCards.NoItemsText = Properties.Resources.TABLECARDS_NOITEMSTEXT;
        }
Пример #19
0
        public SetMovementRejectedHandlerTests()
        {
            var context = new TestIwsContext();

            context.Users.Add(UserFactory.Create(TestIwsContext.UserId, AnyString, AnyString, AnyString, AnyString));

            notificationId = Guid.NewGuid();
            movementId     = Guid.NewGuid();
            rejectDate     = SystemTime.UtcNow;

            rejectMovement          = A.Fake <IRejectMovement>();
            movementRepository      = A.Fake <IMovementRepository>();
            fileRepository          = A.Fake <IFileRepository>();
            movementAuditRepository = A.Fake <IMovementAuditRepository>();
            var notificationRepository = A.Fake <INotificationApplicationRepository>();
            var nameGenerator          = new MovementFileNameGenerator(notificationRepository);
            var certificateFactory     = new CertificateFactory();
            var userContext            = A.Fake <IUserContext>();

            A.CallTo(() => notificationRepository.GetById(notificationId))
            .Returns(new TestableNotificationApplication()
            {
                NotificationNumber = NotificatioNumber
            });

            A.CallTo(() => fileRepository.Store(A <File> .Ignored)).Returns(Guid.NewGuid());

            A.CallTo(() => userContext.UserId).Returns(TestIwsContext.UserId);

            handler = new SetMovementRejectedHandler(rejectMovement, movementRepository, context, nameGenerator,
                                                     certificateFactory, fileRepository, movementAuditRepository, userContext);
        }
Пример #20
0
        public async Task <IActionResult> Register(RegisterUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var usr = UserFactory.Create(model.UserType);

                usr.UserName  = model.Email;
                usr.Email     = model.Email;
                usr.FirstName = model.FirstName;
                usr.LastName  = model.LastName;

                // Kopiowanie danych z modelu RegisterUserViewModel do... chcemy by tutaj był user, lecz nie chce byc


                // Zapisanie danych usera do bazy

                var result = await userManager.CreateAsync(usr, model.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index", "Home"));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            return(View(model));
        }
Пример #21
0
        private LearningModulesIndexEntry CreateNewOdxLearningModuleEntry(string path)
        {
            ConnectionStringStruct css = new ConnectionStringStruct(DatabaseType.Xml, path, true);
            IUser       user           = UserFactory.Create(getLogin, css, dataAccessError, path);
            IDictionary dic            = DAL.User.GetPreviewDictionary(path, user, false);

            return(CreateLerningModuleEntry(dic, user));
        }
Пример #22
0
        public async Task EditAsync(UserRegistrationEditModel model)
        {
            var item = await _repository.GetAsync(model.Id);

            UserFactory.Create(model, item, _userId);
            _repository.Edit(item);
            await _unitOfWork.SaveChangesAsync();
        }
Пример #23
0
        public void Add(User model)
        {
            var entity = UserFactory.Create(model);

            _userRepository.Add(entity);

            model.Id = entity.Id;
        }
Пример #24
0
 public static void MyClassInitialize(TestContext testContext)
 {
     DictionaryTest.MyClassCleanup();             //in case the LM is still open
     DictionaryTest.ExtractTestDictionary();
     user = UserFactory.Create((GetLoginInformation) delegate(UserStruct u, ConnectionStringStruct c) { return(u); },
                               new ConnectionStringStruct(DatabaseType.Xml, DictionaryTest.testDic, false), (DataAccessErrorDelegate) delegate { return; }, testContext);
     Assert.IsTrue(File.Exists(DictionaryTest.testDic), "Test Learning Module file cannot be found.");
 }
Пример #25
0
        public async Task <Unit> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            await _repository.SaveAsync(
                UserFactory.Create(request.Id, request.Email, request.FirstName, request.LastName, request.NickName)
                );

            return(Unit.Value);
        }
Пример #26
0
        public ActionResult Create(User user)
        {
            if (!CheckRole())
            {
                return(RedirectToAction("Index"));
            }
            if (!CheckRole(ERole.Create))
            {
                return(RedirectToAction("Index"));
            }

            user.UserId     = Guid.Empty;
            ViewBag.Roles   = _roleFactory.GetSelectListRole();
            ViewBag.Clients = _clientFactory.GetSelectListClient();
            ViewBag.Edit    = true;

            if (!ModelState.IsValid)
            {
                return(View(user));
            }

            if (!CheckLogin())
            {
                return(RedirectToAction("Login", "User"));
            }
            if (string.IsNullOrEmpty(user.Password))
            {
                user.Password = DSEConstant.DefaultPasswords;
            }

            user = _userFactory.Create(user);

            if (user.Updated)
            {
                return(RedirectToAction("Edit", "AdminUser", new { id = user.UserId }));
            }
            else
            {
                log.ErrorFormat("{0} at {1}  ", user.ErrorMessage, DateTime.Now);
                if (user.ErrorCode == 2)
                {
                    ModelState.AddModelError("CustomError", DSEConstant.User_Duplicate_UserName);
                }
                else
                if (user.ErrorCode == 3)
                {
                    ModelState.AddModelError("CustomError", DSEConstant.User_Duplicate_Email);
                }
                else
                {
                    ModelState.AddModelError("CustomError", DSEConstant.Error_Message_Default);
                }
            }

            ViewBag.Roles   = _roleFactory.GetSelectListRole();
            ViewBag.Clients = _clientFactory.GetSelectListClient();
            return(View(user));
        }
Пример #27
0
        public async Task UpdateOrganisation_BusinessType_Should_Not_Remove_Organisation()
        {
            //Create new user
            var newUser = UserFactory.Create(userId, "testFirst", "testLast", "9999", "*****@*****.**");

            //Create new org
            var country = context.Countries.Single(c => c.IsoAlpha2Code.Equals("gb"));
            var address = TestAddress(country);
            var org     = new Organisation("SFW Ltd", BusinessType.LimitedCompany);

            try
            {
                context.Users.Add(newUser);
                await context.SaveChangesAsync();

                context.Organisations.Add(org);
                await context.SaveChangesAsync();

                //Assign org to user
                newUser.LinkToOrganisation(org);
                await context.SaveChangesAsync();

                //Hold OrgID of newly created entity
                var oldOrgId = org.Id;

                //Update org with change in Business Type
                org = new Organisation("Name Changed", BusinessType.SoleTrader);
                context.Organisations.Add(org);
                await context.SaveChangesAsync();

                //Update user with newly created org2
                var user = await context.Users.SingleAsync(u => u.Id == newUser.Id);

                user.UpdateOrganisationOfUser(org);
                await context.SaveChangesAsync();

                Assert.True(user.Organisation.Id == org.Id);

                //Both Orgs should have different OrgIds
                Assert.False(oldOrgId == org.Id);

                //Check if old org exists
                var oldExists = context.Organisations.Any(x => x.Id == oldOrgId);
                Assert.True(oldExists);

                //Check if new org exists
                var newExists = context.Organisations.Any(x => x.Id == org.Id);
                Assert.True(newExists);
            }
            finally
            {
                context.DeleteOnCommit(org);

                context.Entry(newUser).State = EntityState.Deleted;
                context.SaveChanges();
            }
        }
Пример #28
0
        protected void FireConnectionAccepted(V4Event message)
        {
            User toUser   = UserFactory.Create(message.Initiator.User);
            User fromUser = UserFactory.Create(message.Payload.ConnectionAccepted.FromUser);

            var eventArgs = new ConnectionAcceptedEventArgs(fromUser, toUser);

            InvokeEventHandlers(_onConnectionAccepted, eventArgs);
        }
Пример #29
0
        /// <summary>
        /// Opens an existing extension file.
        /// </summary>
        /// <remarks>Documented by Dev02, 2009-07-09</remarks>
        public void Open(GetLoginInformation loginDelegate)
        {
            IUser user = UserFactory.Create(loginDelegate, new ConnectionStringStruct(DatabaseType.MsSqlCe, ExtensionPath, -1), delegate { return; }, this);
            ConnectionStringStruct css = user.ConnectionString;

            css.LmId = MLifter.DAL.User.GetIdOfLearningModule(ExtensionPath, user);
            user.ConnectionString = css;
            LearningModules       = user.List();
        }
        private Organisation GetOrganisation()
        {
            User         user = UserFactory.Create(userId, "firstName", "lastName", "9123456789", "*****@*****.**");
            Organisation org  = new Organisation(name, BusinessType.Other, otherDescription);

            EntityHelper.SetEntityId(org, organisationId);

            user.LinkToOrganisation(org);
            return(org);
        }
        public override async Task Update(IPatch patch, string correlationIdentifier)
        {
            if (null == patch)
            {
                throw new ArgumentNullException(FileProvider.ArgumentNamePatch);
            }

            if (null == patch.ResourceIdentifier)
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch);
            }

            if (string.IsNullOrWhiteSpace(patch.ResourceIdentifier.Identifier))
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch);
            }

            if (null == patch.PatchRequest)
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidPatch);
            }

            string informationStarting =
                string.Format(
                    CultureInfo.InvariantCulture,
                    AzureTestProvisioningResources.InformationPatching,
                    patch.ResourceIdentifier.SchemaIdentifier,
                    patch.ResourceIdentifier.Identifier);
            ProvisioningAgentMonitor.Instance.Inform(informationStarting, true, correlationIdentifier);

            PatchRequest2 patchRequest = patch.PatchRequest as PatchRequest2;
            if (null == patchRequest)
            {
                string unsupportedPatchTypeName = patch.GetType().FullName;
                throw new NotSupportedException(unsupportedPatchTypeName);
            }

            IRow row = await this.file.ReadRow(patch.ResourceIdentifier.Identifier);

            string rowSchema = null;
            if
            (
                    !row.Columns.TryGetValue(AttributeNames.Schemas, out rowSchema)
                ||  !string.Equals(rowSchema, patch.ResourceIdentifier.SchemaIdentifier, StringComparison.Ordinal)
            )
            {
                return;
            }

            IReadOnlyDictionary<string, string> columns;
            WindowsAzureActiveDirectoryGroup group = null;
            switch (rowSchema)
            {
                case SchemaIdentifiers.Core2EnterpriseUser:
                    ResourceFactory<Core2EnterpriseUser> userFactory = new UserFactory(row);
                    Core2EnterpriseUser user = userFactory.Create();
                    user.Apply(patchRequest);
                    ColumnsFactory<Core2EnterpriseUser> userColumnsFactory = new UserColumnsFactory(user);
                    columns = userColumnsFactory.CreateColumns();
                    break;

                case SchemaIdentifiers.WindowsAzureActiveDirectoryGroup:
                    ResourceFactory<WindowsAzureActiveDirectoryGroup> groupFactory = new GroupFactory(row);
                    group = groupFactory.Create();
                    group.Apply(patchRequest);
                    ColumnsFactory<WindowsAzureActiveDirectoryGroup> groupColumnsFactory = new GroupColumnsFactory(group);
                    columns = groupColumnsFactory.CreateColumns();
                    break;
                default:
                    throw new NotSupportedException(patch.ResourceIdentifier.SchemaIdentifier);
            }

            IRow rowReplacement = new Row(row.Key, columns);
            await this.file.ReplaceRow(rowReplacement);

            if (group != null)
            {
                await this.UpdateMembers(group, patch);
            }
        }