Exemplo n.º 1
0
        private void btnRegistrationOK_Click(object sender, EventArgs e)
        {
            // Zabezpieczenie przed pustym hasłem.
            if (string.IsNullOrWhiteSpace(tbPassword.Text) && string.IsNullOrWhiteSpace(tbPasswordAgain.Text))
            {
                MessageBox.Show("Password shouldn't be empty", "Registration Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Walidacja.
            if (tbPassword.Text == tbPasswordAgain.Text)
            {
                // Tworzenie nowego użytkownika.
                UserFactory usersFactory = new UserFactory();

                if (usersFactory.RegisterUser(tbLogin.Text, tbPassword.Text, cbIsStudent.Checked))
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                else
                {
                    MessageBox.Show("User with specified username exists in database - please try different username", "Registration Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Passwords didn't match", "Registration Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void UserEntityToUserDto()
        {
            UserFactory factory = new UserFactory();
            User user = factory.CreateUser("username", "password");

            UserDto dto = user.ProjectedAs<UserDto>();

            Assert.AreEqual(user.Id, dto.Id);
            Assert.AreEqual(user.UserMail, dto.UserMail);
            Assert.AreEqual(string.Empty, dto.EncryptedPassword);
        }
        public static void Init(TestContext context)
        {
            _loginService = new UserLoginAppService<UserDto, User>();

            IUserFactory<User> factory = new UserFactory();
            _registerService = new UserRegisterAppService<UserDto, User>();
            var dto = _registerService.RegisterUser(UserName, ContainerHelper.Resolve<IMd5Encryptor>().Encrypt(Password));
            _userId = dto.Id;

            _manageService = new UserManageAppService();
        }
Exemplo n.º 4
0
        public UserRepositoryFixture()
        {
            // Fixture setup
            var fixture = new Fixture()
                .Customize(new AutoMoqCustomization());

            mockUser = fixture.Freeze<User>();
            mockUsers = fixture.Freeze<IEnumerable<User>>();
            string mockProductString = JsonConvert.SerializeObject(mockUser);

            ICouchbaseClient db = MakeMockCbClient(mockProductString);
            IFactory<IUser> userFactory = new UserFactory();
            ILocale locale = fixture.Freeze<DefaultLocale>();

            //ICouchbaseClient db, IFactory<IUser> userFactory, ILocale locale
            userRepo = new UserRepository(db, userFactory, locale, "http://localhost:9200/unittests/_search");
        }
Exemplo n.º 5
0
 public static ILoggedUser GetLoggedUser(IOAuthCredentials credentials)
 {
     return(UserFactory.GetLoggedUser(credentials));
 }
Exemplo n.º 6
0
        public User Get(string username, string password)
        {
            var entity = _userRepository.Get(username, password);

            return(entity == null ? null : UserFactory.Create(entity));
        }
Exemplo n.º 7
0
        public User Get(int id)
        {
            var entity = _userRepository.Get(id);

            return(UserFactory.Create(entity));
        }
Exemplo n.º 8
0
 public BannerController(IBannerService bannerService, IBannerMappingService bannerMappingService, UserFactory userFactory)
 {
     this._bannerService        = bannerService;
     this._bannerMappingService = bannerMappingService;
     //this.userId = User.i
     this._userFactory = userFactory;
     this._userId      = _userFactory.GetUserId(User.Identity.Name);
 }
Exemplo n.º 9
0
 public Message(MessageFactory messageFactory, UserFactory userFactory)
 {
     _messageFactory = messageFactory;
     _userFactory    = userFactory;
 }
Exemplo n.º 10
0
 public static void insertNewUser(string name, string email, string password, string gender)
 {
     UserRepository.insert(UserFactory.createNewUser(name, email, password, gender));
 }
Exemplo n.º 11
0
 public static IEnumerable <IUser> GenerateUsersFromDTO(IEnumerable <IUserDTO> usersDTO)
 {
     return(UserFactory.GenerateUsersFromDTO(usersDTO));
 }
Exemplo n.º 12
0
        public void TestAssertUserFactoryCreate()
        {
            var _user = UserFactory.CreateFakeUser();

            Assert.IsInstanceOfType(_user, typeof(User));
        }
Exemplo n.º 13
0
 private void BindData()
 {
     // _userBOL = new UserFactory();
     grvUser.AutoGenerateColumns = false;
     grvUser.DataSource          = UserFactory.SelectAllUser();
 }
Exemplo n.º 14
0
        public override async Task<Resource> Create(Resource resource, string correlationIdentifier)
        {
            logger.Info("creating resource");

            if (null == resource)
            {
                throw new ArgumentNullException(FileProvider.ArgumentNameResource);
            }

            if (string.IsNullOrWhiteSpace(correlationIdentifier))
            {
                throw new ArgumentNullException(FileProvider.ArgumentNameCorrelationIdentifier);
            }

            if (string.IsNullOrWhiteSpace(resource.Identifier))
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidResource);
            }

            string informationStarting =
                string.Format(
                    CultureInfo.InvariantCulture,
                    AzureTestProvisioningResources.InformationCreating,
                    resource.Identifier);
            ProvisioningAgentMonitor.Instance.Inform(informationStarting, true, correlationIdentifier);

            ColumnsFactory columnsFactory;

            WindowsAzureActiveDirectoryGroup group = resource as WindowsAzureActiveDirectoryGroup;
            if (group != null)
            {
                columnsFactory = new GroupColumnsFactory(group);
            }
            else
            {
                Core2EnterpriseUser user = resource as Core2EnterpriseUser;
                if (user != null)
                {
                    columnsFactory = new UserColumnsFactory(user);
                }
                else
                {
                    string unsupportedSchema =
                        string.Join(
                            Environment.NewLine,
                            resource.Schemas);
                    throw new NotSupportedException(unsupportedSchema);
                }
            }

            IReadOnlyDictionary<string, string> columns = columnsFactory.CreateColumns();
            IRow row = await this.file.InsertRow(columns);

            ResourceFactory resourceFactory;
            if (group != null)
            {
                resourceFactory = new GroupFactory(row);
            }
            else
            {
                resourceFactory = new UserFactory(row);
            }

            Resource result = resourceFactory.CreateResource();

            if (group != null && group.Members != null && group.Members.Any())
            {
                foreach (Member member in group.Members)
                {
                    MemberColumnsFactory memberColumnsFactory = new MemberColumnsFactory(result, member);
                    IReadOnlyDictionary<string, string> memberColumns = memberColumnsFactory.CreateColumns();
                    await this.file.InsertRow(memberColumns);
                }
            }

            return result;
        }
Exemplo n.º 15
0
        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);
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Get a collection of users from a collection of user ids
 /// </summary>
 public static IEnumerable <IUser> GetUsersFromIds(IEnumerable <long> userIds)
 {
     return(UserFactory.GetUsersFromIds(userIds));
 }
 public HomeController(UserFactory user)
 {
     userFactory = user;
 }
Exemplo n.º 18
0
 public static IEnumerable <IUser> GetUsersFromScreenNames(IEnumerable <string> screenNames)
 {
     return(UserFactory.GetUsersFromScreenNames(screenNames));
 }
Exemplo n.º 19
0
 public ActionResult ProjectEdit()
 {
     ViewBag.customers = _customerFactory.GetAllContacts() ?? new List <Contact>();
     ViewBag.users     = UserFactory.GetAllUsers();
     return(View());
 }
Exemplo n.º 20
0
        public override async Task<Resource> Retrieve(IResourceRetrievalParameters parameters, string correlationIdentifier)
        {
            if (null == parameters)
            {
                throw new ArgumentNullException(FileProvider.ArgumentNameParameters);
            }

            if (string.IsNullOrWhiteSpace(correlationIdentifier))
            {
                throw new ArgumentNullException(FileProvider.ArgumentNameCorrelationIdentifier);
            }

            if (null == parameters.ResourceIdentifier)
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidParameters);
            }

            if (string.IsNullOrWhiteSpace(parameters.ResourceIdentifier.Identifier))
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidResourceIdentifier);
            }

            if (string.IsNullOrWhiteSpace(parameters.SchemaIdentifier))
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidParameters);
            }

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

            IReadOnlyCollection<string> columnNames = this.IdentifyRequestedColumns(parameters);
            
            IRow row = await this.file.ReadRow(parameters.ResourceIdentifier.Identifier);
            if (null == row || null == row.Columns)
            {
                return null;
            }

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

            IRow reducedRow = FileProvider.FilterColumns(row, columnNames);

            ResourceFactory resourceFactory;
            switch (rowSchema)
            {
                case SchemaIdentifiers.Core2EnterpriseUser:
                    resourceFactory = new UserFactory(reducedRow);
                    break;
                case SchemaIdentifiers.WindowsAzureActiveDirectoryGroup:
                    resourceFactory = new GroupFactory(reducedRow);
                    break;
                default:
                    throw new NotSupportedException(parameters.SchemaIdentifier);
            }

            Resource result = resourceFactory.CreateResource();
            return result;
        }
Exemplo n.º 21
0
        public virtual async Task <IActionResult> Login([FromForm] string username, [FromForm] string password)
        {
            //Empty password or username
            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                Response.StatusCode = 400;
                return(new ObjectResult(new ErrorMessage()
                {
                    Title = "Error",
                    Text = "Invalid username/password supplied!"
                }));
            }

            //Get user
            try
            {
                var user = UserFactory.fromModel(_userService.FindOnebyUsernameAndPassword(username, password));

                var claims = new[] {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Email, user.Email),
                    new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                    new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),

                    new Claim(JwtRegisteredClaimNames.Email, user.Email),
                };

                // Create the JWT security token and encode it.
                var jwt = new JwtSecurityToken(
                    issuer: _jwtOptions.Issuer,
                    audience: _jwtOptions.Audience,
                    claims: claims,
                    notBefore: _jwtOptions.NotBefore,
                    expires: _jwtOptions.Expiration,
                    signingCredentials: _jwtOptions.SigningCredentials);

                //encode JWT token
                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                // Serialize and return the response
                var response = new
                {
                    access_token = encodedJwt,
                    expires_in   = (int)_jwtOptions.ValidFor.TotalSeconds
                };

                var json = JsonConvert.SerializeObject(response, _serializerSettings);
                return(new OkObjectResult(json));
            }
            catch (ModelNotFoundException)
            {
                _logger.LogInformation($"Invalid username ({username}) or password ({password})");
                Response.StatusCode = 401;
                return(new ObjectResult(new ErrorMessage()
                {
                    Title = "Error",
                    Text = $"Invalid username or password!"
                }
                                        ));
            }
            catch (Exception ex)
            {
                Response.StatusCode = 500;
                return(new ObjectResult(new ErrorMessage()
                {
                    Title = "Error",
                    Text = ex.Message
                }));
            }
        }
Exemplo n.º 22
0
 public UserService()
 {
     this._repo    = new UserRepository(new ApplicationDbContext());
     this._factory = new UserFactory();
 }
Exemplo n.º 23
0
        public void RegisterUser(RegisterUserRequest req)
        {
            var user = UserFactory.Create(req.LoginId, req.Name, req.MailAddress, req.Password);

            testData.Add(user);
        }
Exemplo n.º 24
0
 public UserController()
 {
     userfactory = new UserFactory();
 }
Exemplo n.º 25
0
 public HomeController()
 {
     userFactory = new UserFactory();
 }
 //use dependency injection on the HomeController constructor to get a UserFactory object
 public UserController(UserFactory user)
 {
     userFactory = user;
 }
Exemplo n.º 27
0
 public UsersController(UserFactory user, MessageFactory message, CommentFactory comment)
 {
     userFactory    = user;
     messageFactory = message;
     commentFactory = comment;
 }
Exemplo n.º 28
0
        public void Update(User model)
        {
            var entity = UserFactory.Create(model);

            _userRepository.Update(entity);
        }
Exemplo n.º 29
0
        }                                                                                                                                        // Delete

        public static void Insert(string userName, string userPassword, string gender, DateTime dob, string email, string address, string phoneNumber, string image, int userRole)
        {
            User u = UserFactory.Create(userName, userPassword, gender, dob, email, address, phoneNumber, image, userRole); UserRepository.Insert(u);
        }                                                                                                                                                                         // Register
Exemplo n.º 30
0
 public static ILoggedUser GetLoggedUser()
 {
     return(UserFactory.GetLoggedUser());
 }
Exemplo n.º 31
0
 public HomeController(DbConnector db, UserFactory userFactory)
 {
     _db          = db;
     _userFactory = userFactory;
 }
Exemplo n.º 32
0
 public static IUser GetUserFromId(long userId)
 {
     return(UserFactory.GetUserFromId(userId));
 }
Exemplo n.º 33
0
        /// <summary>
        /// Unpacks the specified source path.
        /// </summary>
        /// <param name="sourcePath">The source path.</param>
        /// <param name="ignoreInvalidHeaders">if set to <c>true</c> [ignore invalid headers].</param>
        /// <returns></returns>
        /// <remarks>Documented by Dev03, 2007-09-11</remarks>
        public IDictionary Unpack(string sourcePath, bool ignoreInvalidHeaders)
        {
            string dictionaryPath = String.Empty;

            //ZipConstants.DefaultCodePage = Encoding.Unicode.CodePage;   //this may possibly mean that we are not Zip compatible anymore

            using (FileStream sourceStream = File.OpenRead(sourcePath))
            {
                string temporaryPath;

                if (!ignoreInvalidHeaders)
                {
                    // Checking Zip File Header
                    if (!IsValidArchive(sourcePath))
                    {
                        throw new NoValidArchiveException();
                    }
                }

                long zipFileSize = 0;

                ZipFile zipFile = null;
                try
                {
                    zipFile     = new ZipFile(sourcePath);
                    zipFileSize = zipFile.Count;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (zipFile != null)
                    {
                        zipFile.Close();
                    }
                }

                if (m_temporaryFolder.Length == 0)
                {
                    temporaryPath = Path.GetTempPath();
                    temporaryPath = Path.Combine(temporaryPath, Path.GetRandomFileName());
                }
                else
                {
                    temporaryPath = m_temporaryFolder;
                }

                if (!Directory.Exists(temporaryPath))
                {
                    Directory.CreateDirectory(temporaryPath);
                }

                System.IO.Directory.SetCurrentDirectory(temporaryPath);

                // Extract files
                ZipInputStream zipStream = new ZipInputStream(sourceStream);
                ZipEntry       zipEntry;

                int    nBytes = 2048;
                byte[] data   = new byte[nBytes];

                int counter = 1;
                if (!ReportProgressUpdate(0))
                {
                    return(null);
                }
                while ((zipEntry = zipStream.GetNextEntry()) != null)
                {
                    if (!Directory.Exists(Path.GetDirectoryName(Path.Combine(temporaryPath, zipEntry.Name))))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(temporaryPath, zipEntry.Name)));
                    }

                    if (Path.GetExtension(zipEntry.Name).ToLower() == Resources.DICTIONARY_ODX_EXTENSION)
                    {
                        dictionaryPath = Path.Combine(temporaryPath, zipEntry.Name);
                    }

                    // write file
                    try
                    {
                        string   filePath = Path.Combine(temporaryPath, zipEntry.Name);
                        FileMode fileMode = (File.Exists(filePath)) ? FileMode.Truncate : FileMode.OpenOrCreate;
                        using (FileStream writer = new FileStream(filePath, fileMode, FileAccess.ReadWrite, FileShare.Read))
                        {
                            while ((nBytes = zipStream.Read(data, 0, data.Length)) > 0)
                            {
                                writer.Write(data, 0, nBytes);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("DAL.Pack.Unpack() - " + zipEntry.Name + " - " + ex.Message);
                        if (zipEntry.Name.Contains(DAL.Helper.OdxExtension))
                        {
                            throw ex;
                        }
                    }

                    int progress = (int)Math.Floor(100.0 * (counter++) / zipFileSize);
                    if (!ReportProgressUpdate(progress))
                    {
                        return(null);
                    }
                }
                if (!ReportProgressUpdate(100))
                {
                    return(null);
                }
                zipStream.Close();
                sourceStream.Close();
            }

            if (dictionaryPath.Length == 0)
            {
                throw new NoValidArchiveException();
            }

            return(UserFactory.Create(m_loginCallback, new ConnectionStringStruct(DatabaseType.Xml, dictionaryPath, true),
                                      (DataAccessErrorDelegate) delegate { return; }, this).Open());
        }
Exemplo n.º 34
0
 public static IUser GetUserFromScreenName(string userName)
 {
     return(UserFactory.GetUserFromScreenName(userName));
 }
Exemplo n.º 35
0
        public override async Task<Resource[]> Query(IQueryParameters parameters, string correlationIdentifier)
        {
            if (null == parameters)
            {
                throw new ArgumentNullException(FileProvider.ArgumentNameParameters);
            }

            if (string.IsNullOrWhiteSpace(correlationIdentifier))
            {
                throw new ArgumentNullException(FileProvider.ArgumentNameCorrelationIdentifier);
            }

            if (null == parameters.AlternateFilters)
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidParameters);
            }

            if (string.IsNullOrWhiteSpace(parameters.SchemaIdentifier))
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidParameters);
            }

            string informationAlternateFilterCount = parameters.AlternateFilters.Count.ToString(CultureInfo.InvariantCulture);
            ProvisioningAgentMonitor.Instance.Inform(informationAlternateFilterCount, true, correlationIdentifier);
            if (parameters.AlternateFilters.Count != 1)
            {
                string exceptionMessage =
                    string.Format(
                        CultureInfo.InvariantCulture,
                        ProvisioningAgentResources.ExceptionFilterCountTemplate,
                        1,
                        parameters.AlternateFilters.Count);
                throw new NotSupportedException(exceptionMessage);
            }

            Resource[] results;
            IFilter queryFilter = parameters.AlternateFilters.Single();
            if (queryFilter.AdditionalFilter != null)
            {
                results = await this.QueryReference(parameters, correlationIdentifier);
                return results;
            }

            IReadOnlyCollection<string> requestedColumns = this.IdentifyRequestedColumns(parameters);

            if (string.IsNullOrWhiteSpace(queryFilter.AttributePath))
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidParameters);
            }

            if (string.IsNullOrWhiteSpace(queryFilter.ComparisonValue))
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidParameters);
            }

            Dictionary<string, string> columns =
                new Dictionary<string, string>()
                    {
                        {
                            AttributeNames.Schemas,
                            parameters.SchemaIdentifier
                        },
                        {
                            queryFilter.AttributePath,
                            queryFilter.ComparisonValue
                        }
                    };
            IReadOnlyCollection<IRow> rows = await this.file.Query(columns);
            if (null == rows)
            {
                return new Resource[0];
            }

            IList<Resource> resources = new List<Resource>(rows.Count);
            foreach (IRow row in rows)
            {
                string rowSchema = null;
                if
                (
                        !row.Columns.TryGetValue(AttributeNames.Schemas, out rowSchema)
                    ||  !string.Equals(rowSchema, parameters.SchemaIdentifier, StringComparison.Ordinal)
                )
                {
                    continue;
                }

                IRow reducedRow = FileProvider.FilterColumns(row, requestedColumns);

                ResourceFactory resourceFactory;
                switch (rowSchema)
                {
                    case SchemaIdentifiers.Core2EnterpriseUser:
                        resourceFactory = new UserFactory(reducedRow);
                        break;
                    case SchemaIdentifiers.WindowsAzureActiveDirectoryGroup:
                        resourceFactory = new GroupFactory(reducedRow);
                        break;
                    default:
                        throw new NotSupportedException(parameters.SchemaIdentifier);
                }

                Resource resource = resourceFactory.CreateResource();
                resources.Add(resource);
            }

            results = resources.ToArray();
            return results;
        }
Exemplo n.º 36
0
 public static IUser GenerateUserFromDTO(IUserDTO userDTO)
 {
     return(UserFactory.GenerateUserFromDTO(userDTO));
 }
Exemplo n.º 37
0
 public UserMapper()
 {
     factory       = new UserFactory();
     teamConverter = new TeamMapper();
 }
Exemplo n.º 38
0
 public ViewModel(UserFactory userFactory)
 {
     _userFactory = userFactory;
 }
Exemplo n.º 39
0
        private async Task<Resource[]> QueryReference(IQueryParameters parameters, string correlationIdentifier)
        {
            if (null == parameters)
            {
                throw new ArgumentNullException(FileProvider.ArgumentNameParameters);
            }

            if (string.IsNullOrWhiteSpace(correlationIdentifier))
            {
                throw new ArgumentNullException(FileProvider.ArgumentNameCorrelationIdentifier);
            }

            if (null == parameters.RequestedAttributePaths || !parameters.RequestedAttributePaths.Any())
            {
                throw new NotSupportedException(ProvisioningAgentResources.ExceptionUnsupportedQuery);
            }

            string selectedAttribute = parameters.RequestedAttributePaths.SingleOrDefault();
            if (string.IsNullOrWhiteSpace(selectedAttribute))
            {
                throw new NotSupportedException(ProvisioningAgentResources.ExceptionUnsupportedQuery);
            }
            ProvisioningAgentMonitor.Instance.Inform(selectedAttribute, true, correlationIdentifier);

            if
            (
                !string.Equals(
                    selectedAttribute,
                    Microsoft.SystemForCrossDomainIdentityManagement.AttributeNames.Identifier,
                    StringComparison.OrdinalIgnoreCase)
            )
            {
                throw new NotSupportedException(ProvisioningAgentResources.ExceptionUnsupportedQuery);
            }

            if (null == parameters.AlternateFilters)
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidParameters);
            }

            if (string.IsNullOrWhiteSpace(parameters.SchemaIdentifier))
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidParameters);
            }

            string informationAlternateFilterCount = parameters.AlternateFilters.Count.ToString(CultureInfo.InvariantCulture);
            ProvisioningAgentMonitor.Instance.Inform(informationAlternateFilterCount, true, correlationIdentifier);
            if (parameters.AlternateFilters.Count != 1)
            {
                string exceptionMessage =
                    string.Format(
                        CultureInfo.InvariantCulture,
                        ProvisioningAgentResources.ExceptionFilterCountTemplate,
                        1,
                        parameters.AlternateFilters.Count);
                throw new NotSupportedException(exceptionMessage);
            }

            IReadOnlyCollection<string> requestedColumns = this.IdentifyRequestedColumns(parameters);

            IFilter filterPrimary = parameters.AlternateFilters.Single();
            if (null == filterPrimary.AdditionalFilter)
            {
                throw new ArgumentException(ProvisioningAgentResources.ExceptionInvalidParameters);
            }

            IFilter filterAdditional = filterPrimary.AdditionalFilter;

            if (filterAdditional.AdditionalFilter != null)
            {
                throw new NotSupportedException(ProvisioningAgentResources.ExceptionUnsupportedQuery);
            }

            IReadOnlyCollection<IFilter> filters =
                new IFilter[]
                    {
                        filterPrimary,
                        filterAdditional
                    };

            IFilter filterIdentifier =
                filters
                .SingleOrDefault(
                    (IFilter item) =>
                        string.Equals(
                            AttributeNames.Identifier,
                            item.AttributePath,
                            StringComparison.OrdinalIgnoreCase));
            if (null == filterIdentifier)
            {
                throw new NotSupportedException(ProvisioningAgentResources.ExceptionUnsupportedQuery);
            }

            IRow row;
            IFilter filterReference =
                filters
                .SingleOrDefault(
                    (IFilter item) =>
                            string.Equals(
                                AttributeNames.Members,
                                item.AttributePath,
                                StringComparison.OrdinalIgnoreCase));
            if (filterReference != null)
            {
                Dictionary<string, string> columns =
                new Dictionary<string, string>()
                    {
                        {
                            AttributeNames.Schemas,
                            parameters.SchemaIdentifier
                        },
                        {
                            AttributeNames.Identifier,
                            filterIdentifier.ComparisonValue
                        },
                        {
                            filterReference.AttributePath,
                            filterReference.ComparisonValue
                        }
                    };

                IReadOnlyCollection<IRow> rows = await this.file.Query(columns);
                if (null == rows || !rows.Any())
                {
                    return new Resource[0];
                }

                row = await this.file.ReadRow(filterIdentifier.ComparisonValue);
            }
            else
            {
                filterReference =
                    filters
                    .SingleOrDefault(
                        (IFilter item) =>
                                string.Equals(
                                    AttributeNames.Manager,
                                    item.AttributePath,
                                    StringComparison.OrdinalIgnoreCase));
                if (null == filterReference)
                {
                    throw new NotSupportedException(ProvisioningAgentResources.ExceptionUnsupportedQuery);
                }

                row = await this.file.ReadRow(filterIdentifier.ComparisonValue);
                if
                (
                        null == row.Columns
                    || !row
                        .Columns
                        .Any(
                            (KeyValuePair<string, string> columnItem) =>
                                    string.Equals(columnItem.Key, filterReference.AttributePath, StringComparison.Ordinal)
                                && string.Equals(columnItem.Value, filterReference.ComparisonValue, StringComparison.Ordinal))
                )
                {
                    return new Resource[0];
                }
            }

            string rowSchema = null;
            if
            (
                    !row.Columns.TryGetValue(AttributeNames.Schemas, out rowSchema)
                || !string.Equals(rowSchema, parameters.SchemaIdentifier, StringComparison.Ordinal)
            )
            {
                return new Resource[0];
            }

            IRow reducedRow = FileProvider.FilterColumns(row, requestedColumns);

            ResourceFactory resourceFactory;
            switch (rowSchema)
            {
                case SchemaIdentifiers.Core2EnterpriseUser:
                    resourceFactory = new UserFactory(reducedRow);
                    break;
                case SchemaIdentifiers.WindowsAzureActiveDirectoryGroup:
                    resourceFactory = new GroupFactory(reducedRow);
                    break;
                default:
                    throw new NotSupportedException(parameters.SchemaIdentifier);
            }

            Resource resource = resourceFactory.CreateResource();
            Resource[] results =
                new Resource[]
                {
                    resource
                };
            return results;
        }