public override Task <Resource> CreateAsync(Resource resource, string correlationIdentifier)
        {
            if (resource.Identifier != null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            Core2EnterpriseUser user = resource as Core2EnterpriseUser;

            if (string.IsNullOrWhiteSpace(user.UserName))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            // call service
            TargetUser target;

            try
            {
                target = _storageService.CreateUser((TargetUser)user);
            }
            catch (Exception err)
            {
                switch (err.Message)
                {
                case "Conflict":
                    throw new HttpResponseException(HttpStatusCode.Conflict);

                default:
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }
            }

            return(Task.FromResult((Core2EnterpriseUser)target as Resource));
        }
        private static ResourceFactory SelectResourceFactoryFor(Resource resource, IRow row)
        {
            WindowsAzureActiveDirectoryGroup group = resource as WindowsAzureActiveDirectoryGroup;

            if (group != null)
            {
                ResourceFactory result = new GroupFactory(row);
                return(result);
            }

            Core2EnterpriseUser user = resource as Core2EnterpriseUser;

            if (user != null)
            {
                ResourceFactory result = new UserFactory(row);
                return(result);
            }

            DynamicUser dynamicUser = resource as DynamicUser;

            if (dynamicUser != null)
            {
                ResourceFactory result = new DynamicUserFactory(row);
                return(result);
            }

            string unsupportedSchema =
                string.Join(
                    Environment.NewLine,
                    resource.Schemas);

            throw new NotSupportedException(unsupportedSchema);
        }
        private static ColumnsFactory SelectColumnsFactoryFor(Resource resource)
        {
            WindowsAzureActiveDirectoryGroup group = resource as WindowsAzureActiveDirectoryGroup;

            if (group != null)
            {
                ColumnsFactory result = new GroupColumnsFactory(group);
                return(result);
            }

            Core2EnterpriseUser user = resource as Core2EnterpriseUser;

            if (user != null)
            {
                ColumnsFactory result = new UserColumnsFactory(user);
                return(result);
            }

            string unsupportedSchema =
                string.Join(
                    Environment.NewLine,
                    resource.Schemas);

            throw new NotSupportedException(unsupportedSchema);
        }
示例#4
0
        public override async Task <Resource> RetrieveAsync(IResourceRetrievalParameters parameters, string correlationIdentifier)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

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

            if (string.IsNullOrEmpty(parameters?.ResourceIdentifier?.Identifier))
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            Resource result     = null;
            string   identifier = parameters.ResourceIdentifier.Identifier;

            Core2EnterpriseUser user = await this.context.Users.Where(u => u.Identifier == identifier)
                                       .Include(u => u.Addresses)
                                       .Include(u => u.ElectronicMailAddresses)
                                       .Include(u => u.InstantMessagings)
                                       .Include(u => u.PhoneNumbers)
                                       .AsNoTracking().FirstOrDefaultAsync();

            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            result = user as Resource;
            return(await Task.FromResult(result));
        }
示例#5
0
        public override Task <Resource> CreateAsync(Resource resource, string correlationIdentifier)
        {
            if (resource.Identifier != null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            Core2EnterpriseUser user = resource as Core2EnterpriseUser;

            if (string.IsNullOrWhiteSpace(user.UserName))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            IEnumerable <Core2EnterpriseUser> exisitingUsers = this.storage.Users.Values;

            if
            (
                exisitingUsers.Any(
                    (Core2EnterpriseUser exisitingUser) =>
                    string.Equals(exisitingUser.UserName, user.UserName, StringComparison.Ordinal))
            )
            {
                throw new HttpResponseException(HttpStatusCode.Conflict);
            }

            string resourceIdentifier = Guid.NewGuid().ToString();

            resource.Identifier = resourceIdentifier;
            this.storage.Users.Add(resourceIdentifier, user);

            return(Task.FromResult(resource));
        }
示例#6
0
        public override async Task <Resource> CreateAsync(Resource resource, string correlationIdentifier)
        {
            if (resource.Identifier != null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            Core2EnterpriseUser user = resource as Core2EnterpriseUser;

            if (string.IsNullOrWhiteSpace(user.UserName))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            if (await this.context.Users.AnyAsync(u => u.UserName == user.UserName))
            {
                throw new HttpResponseException(HttpStatusCode.Conflict);
            }

            string resourceIdentifier = Guid.NewGuid().ToString();

            user.Identifier = resourceIdentifier;
            await this.context.Users.AddAsync(user);

            await this.context.SaveChangesAsync();

            return(await Task.FromResult(user as Resource));
        }
        private static IReadOnlyDictionary <string, string> PatchUser(PatchRequest2 patch, IRow row)
        {
            ResourceFactory <Core2EnterpriseUser> userFactory = new UserFactory(row);
            Core2EnterpriseUser user = userFactory.Create();

            user.Apply(patch);
            ColumnsFactory <Core2EnterpriseUser> userColumnsFactory = new UserColumnsFactory(user);
            IReadOnlyDictionary <string, string> result             = userColumnsFactory.CreateColumns();

            return(result);
        }
示例#8
0
        // override missing
        public override async Task <Resource> ReplaceAsync(Resource resource, string correlationIdentifier)
        {
            if (resource.Identifier == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            Core2EnterpriseUser update = resource as Core2EnterpriseUser;

            if (string.IsNullOrWhiteSpace(update.UserName))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            if (await this.context.Users.AnyAsync(u => u.UserName == update.UserName && u.Identifier != update.Identifier))
            {
                throw new HttpResponseException(HttpStatusCode.Conflict);
            }

            Core2EnterpriseUser user = await this.context.Users.Where(u => u.Identifier == update.Identifier)
                                       .Include(u => u.Addresses)
                                       .Include(u => u.ElectronicMailAddresses)
                                       .Include(u => u.InstantMessagings)
                                       .Include(u => u.PhoneNumbers)
                                       .FirstOrDefaultAsync();

            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            // cascade updates to related tables
            // Addresses
            cascadeUpdates(update.Addresses, user.Addresses);
            // ElectronicMailAddresses
            cascadeUpdates(update.ElectronicMailAddresses, user.ElectronicMailAddresses);
            // InstantMessagings
            cascadeUpdates(update.InstantMessagings, user.InstantMessagings);
            // PhoneNumbers
            cascadeUpdates(update.PhoneNumbers, user.PhoneNumbers);

            // update object
            this.context.Entry(user).CurrentValues.SetValues(update);

            await this.context.SaveChangesAsync();

            return(await Task.FromResult(user as Resource));
        }
示例#9
0
        public override async Task UpdateAsync(IPatch patch, string correlationIdentifier)
        {
            if (null == patch)
            {
                throw new ArgumentNullException(nameof(patch));
            }

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

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

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

            PatchRequest2 patchRequest = patch.PatchRequest as PatchRequest2;

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

            Core2EnterpriseUser user = await this.context.Users.Where(u => u.Identifier == patch.ResourceIdentifier.Identifier)
                                       .Include(u => u.Addresses)
                                       .Include(u => u.ElectronicMailAddresses)
                                       .Include(u => u.InstantMessagings)
                                       .Include(u => u.PhoneNumbers)
                                       .FirstOrDefaultAsync();

            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            user.Apply(patchRequest);
            this.context.Users.Update(user);
            await this.context.SaveChangesAsync();
        }
示例#10
0
        public override async Task DeleteAsync(IResourceIdentifier resourceIdentifier, string correlationIdentifier)
        {
            if (string.IsNullOrWhiteSpace(resourceIdentifier?.Identifier))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            string identifier = resourceIdentifier.Identifier;

            Core2EnterpriseUser user = await this.context.Users.Where(u => u.Identifier == identifier).FirstOrDefaultAsync();

            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            this.context.Users.Remove(user);
            await this.context.SaveChangesAsync();
        }
        public override async Task <Resource> ReplaceAsync(Resource resource, string correlationIdentifier)
        {
            if (resource.Identifier == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            Core2EnterpriseUser user = resource as Core2EnterpriseUser;

            if (string.IsNullOrWhiteSpace(user.UserName))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            IEnumerable <Core2EnterpriseUser> existingUsers = _context.Users
                                                              .Select(u => (Core2EnterpriseUser)u).ToList();

            if
            (
                existingUsers.Any(
                    (Core2EnterpriseUser existingUser) =>
                    string.Equals(existingUser.UserName, user.UserName, StringComparison.Ordinal) &&
                    !string.Equals(existingUser.Identifier, user.Identifier, StringComparison.OrdinalIgnoreCase))
            )
            {
                throw new HttpResponseException(HttpStatusCode.Conflict);
            }

            if (int.TryParse(user.Identifier, out int id) && _context.Users.Find(id) is MvcMovie.Models.User existingModelUser)
            {
                existingModelUser.DisplayName = user.DisplayName;
                existingModelUser.Active      = user.Active;
                existingModelUser.UserName    = user.UserName;

                _context.Update(existingModelUser);
                await _context.SaveChangesAsync();

                return(user);
            }

            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        public override async Task UpdateAsync(IPatch patch, string correlationIdentifier)
        {
            if (null == patch)
            {
                throw new ArgumentNullException(nameof(patch));
            }

            if (null == patch.ResourceIdentifier)
            {
                throw new ArgumentException("Invalid Patch");
            }

            if (string.IsNullOrWhiteSpace(patch.ResourceIdentifier.Identifier))
            {
                throw new ArgumentException("Invalid Patch");
            }

            if (null == patch.PatchRequest)
            {
                throw new ArgumentException("Invalid Patch");
            }

            PatchRequest2 patchRequest =
                patch.PatchRequest as PatchRequest2;

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

            if (int.TryParse(patch.ResourceIdentifier.Identifier, out int id) && _context.Users.Find(id) is MvcMovie.Models.User modelUser)
            {
                Core2EnterpriseUser scimUser = (Core2EnterpriseUser)modelUser;
                scimUser.Apply(patchRequest);
                await ReplaceAsync(scimUser, correlationIdentifier);
            }
            else
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }
        public async Task TestQuery()
        {
            Func <ProviderBase, Task> testFunction =
                new Func <ProviderBase, Task>(
                    async(ProviderBase provider) =>
            {
                string correlationIdentifierCreate = Guid.NewGuid().ToString();

                Core2EnterpriseUser inputResource = SampleComposer.Instance.ComposeUserResource() as Core2EnterpriseUser;
                Resource outputResource           = await provider.CreateAsync(inputResource, correlationIdentifierCreate);
                Assert.IsNotNull(outputResource);
                Assert.IsFalse(string.IsNullOrWhiteSpace(outputResource.Identifier));

                IReadOnlyCollection <string> requestedAttributes = new string[0];
                IReadOnlyCollection <string> excludedAttributes  = new string[0];

                IReadOnlyCollection <IFilter> filters = null;
                string filterExpression =
                    string.Format(
                        CultureInfo.InvariantCulture,
                        ProviderTestTemplate <TProvider> .FilterByExternalIdentifierExpressionTemplate,
                        inputResource.ExternalIdentifier);
                Assert.IsTrue(Filter.TryParse(filterExpression, out filters));
                IQueryParameters queryParameters =
                    new QueryParameters(
                        SchemaIdentifiers.Core2EnterpriseUser,
                        ProtocolConstants.PathUsers,
                        filters,
                        requestedAttributes,
                        excludedAttributes);

                string correlationIdentifierQuery = Guid.NewGuid().ToString();

                IReadOnlyCollection <Resource> resources = await provider.QueryAsync(queryParameters, correlationIdentifierQuery);
                Assert.IsNotNull(resources);
                Resource resource = resources.Single();
                Assert.IsTrue(string.Equals(outputResource.Identifier, resource.Identifier, StringComparison.OrdinalIgnoreCase));
            });

            await this.RunTest(testFunction);
        }
示例#14
0
        public override Task <Resource> ReplaceAsync(Resource resource, string correlationIdentifier)
        {
            if (resource.Identifier == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            Core2EnterpriseUser user = resource as Core2EnterpriseUser;

            if (string.IsNullOrWhiteSpace(user.UserName))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            IEnumerable <Core2EnterpriseUser> exisitingUsers = this.storage.Users.Values;

            if
            (
                exisitingUsers.Any(
                    (Core2EnterpriseUser exisitingUser) =>
                    string.Equals(exisitingUser.UserName, user.UserName, StringComparison.Ordinal) &&
                    !string.Equals(exisitingUser.Identifier, user.Identifier, StringComparison.OrdinalIgnoreCase))
            )
            {
                throw new HttpResponseException(HttpStatusCode.Conflict);
            }

            if (!this.storage.Users.TryGetValue(user.Identifier, out Core2EnterpriseUser _))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            this.storage.Users[user.Identifier] = user;
            Resource result = user as Resource;

            return(Task.FromResult(result));
        }
        public override Task <Resource> CreateAsync(Resource resource, string correlationIdentifier)
        {
            if (resource.Identifier != null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            Core2EnterpriseUser user = resource as Core2EnterpriseUser;

            if (string.IsNullOrWhiteSpace(user.UserName))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            IEnumerable <Core2EnterpriseUser> exisitingUsers =
                _context.Users.Select(u => (Core2EnterpriseUser)u).ToList();

            if
            (
                exisitingUsers.Any(
                    (Core2EnterpriseUser exisitingUser) =>
                    string.Equals(exisitingUser.UserName, user.UserName, StringComparison.Ordinal))
            )
            {
                throw new HttpResponseException(HttpStatusCode.Conflict);
            }

            var modelUser = (MvcMovie.Models.User)user;

            _context.Users.Add(modelUser);
            _context.SaveChanges();

            resource.Identifier = modelUser.Id.ToString();

            return(Task.FromResult(resource));
        }
        public void TestLifecycleGroup()
        {
            Uri addressBase = new Uri(WebServiceUnitTest.AddressBase);

            IMonitor monitor = new ConsoleMonitor();

            IAmazonWebServicesIdentityAnchoringBehavior anchoringBehavior =
                new AnchoringByIdentifierBehavior();
            AmazonWebServicesProviderBase provider = new AmazonWebServicesProvider(WebServiceUnitTest.CredentialsProfileName, anchoringBehavior);
            Service webService = null;
            try
            {
                webService = new WebService(monitor, provider);
                webService.Start(addressBase);

                string identifierGroup;
                string identifierGroupExternal;
                string identifierMemberOne;
                string identifierMemberTwo;
                
                Uri resource;

                WebClient client = null;
                try
                {
                    IDictionary<string, object> json;
                    string characters;
                    byte[] bytes;
                    byte[] response;
                    string responseCharacters;
                    IReadOnlyDictionary<string, object> responseJson;
                    Core2EnterpriseUser user;
                    Member member;
                    IReadOnlyCollection<Member> members;

                    client = new WebClient();
                    
                    identifierMemberOne = Guid.NewGuid().ToString();
                    string identifierMemberOneExternal = Guid.NewGuid().ToString();
                    user =
                        new Core2EnterpriseUser()
                        {
                            Identifier = identifierMemberOne,
                            ExternalIdentifier = identifierMemberOneExternal
                        };

                    json = user.ToJson();
                    characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                    bytes = Encoding.UTF8.GetBytes(characters);
                    resource = new Uri(addressBase, WebServiceUnitTest.AddressRelativeUsers);
                    client.Headers.Clear();
                    client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                    response = client.UploadData(resource.AbsoluteUri, WebRequestMethods.Http.Post, bytes);
                    responseCharacters = Encoding.UTF8.GetString(response);
                    responseJson =
                        WebServiceUnitTest.Serializer.Value.Deserialize<Dictionary<string, object>>(responseCharacters);
                    user = new Core2EnterpriseUserJsonDeserializingFactory().Create(responseJson);
                    identifierMemberOne = user.Identifier;

                    try
                    {
                        member = 
                            new Member()
                            {
                                Value = identifierMemberOne
                            };
                        members =
                            new Member[]
                                {
                                    member
                                };

                        identifierGroup = Guid.NewGuid().ToString();
                        identifierGroupExternal = Guid.NewGuid().ToString();

                        WindowsAzureActiveDirectoryGroup group =
                            new WindowsAzureActiveDirectoryGroup()
                            {
                                Identifier = identifierGroup,
                                ExternalIdentifier = identifierGroupExternal,
                                Members = members
                            };

                        json = group.ToJson();
                        characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                        bytes = Encoding.UTF8.GetBytes(characters);
                        resource = new Uri(addressBase, WebServiceUnitTest.AddressRelativeGroups);
                        client.Headers.Clear();
                        client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                        response = client.UploadData(resource.AbsoluteUri, WebRequestMethods.Http.Post, bytes);
                        responseCharacters = Encoding.UTF8.GetString(response);
                        responseJson =
                            WebServiceUnitTest.Serializer.Value.Deserialize<Dictionary<string, object>>(responseCharacters);
                        group = new WindowsAzureActiveDirectoryGroupJsonDeserializingFactory().Create(responseJson);
                        Assert.IsNotNull(group);
                        Assert.IsNotNull(
                            group
                            .Schemas
                            .SingleOrDefault(
                                (string item) =>
                                    string.Equals(
                                        SchemaIdentifiers.WindowsAzureActiveDirectoryGroup,
                                        item,
                                        StringComparison.Ordinal)));
                        Assert.IsFalse(string.IsNullOrWhiteSpace(group.Identifier));

                        string identifierGroupAmazon = group.Identifier;

                        try
                        {
                            Assert.IsNotNull(group.Metadata);
                            Assert.IsFalse(string.IsNullOrWhiteSpace(group.Metadata.ResourceType));
                            Assert.IsFalse(string.Equals(identifierGroup, identifierGroupAmazon, StringComparison.OrdinalIgnoreCase));

                            string resourcePath = 
                                string.Format(
                                    CultureInfo.InvariantCulture, 
                                    WebServiceUnitTest.AddressRelativeGroupTemplate, 
                                    identifierGroupAmazon);
                            resource = new Uri(addressBase, resourcePath);

                            response = client.DownloadData(resource);
                            responseCharacters = Encoding.UTF8.GetString(response);
                            responseJson =
                                WebServiceUnitTest.Serializer.Value.Deserialize<Dictionary<string, object>>(responseCharacters);
                            group = new WindowsAzureActiveDirectoryGroupJsonDeserializingFactory().Create(responseJson);
                            Assert.IsNotNull(group);
                            Assert.IsNotNull(
                                group
                                .Schemas
                                .SingleOrDefault(
                                    (string item) =>
                                        string.Equals(
                                            SchemaIdentifiers.Core2Group,
                                            item,
                                            StringComparison.Ordinal)));
                            Assert.IsFalse(string.IsNullOrWhiteSpace(group.Identifier));
                            Assert.IsTrue(string.Equals(group.Identifier, identifierGroupAmazon, StringComparison.OrdinalIgnoreCase));

                            Assert.IsFalse(string.IsNullOrWhiteSpace(group.ExternalIdentifier));
                            Assert.IsTrue(string.Equals(group.ExternalIdentifier, identifierGroupExternal, StringComparison.OrdinalIgnoreCase));

                            identifierMemberTwo = Guid.NewGuid().ToString();
                            string identifierMemberTwoExternal = Guid.NewGuid().ToString();
                            user =
                                new Core2EnterpriseUser()
                                {
                                    Identifier = identifierMemberTwo,
                                    ExternalIdentifier = identifierMemberTwoExternal
                                };

                            json = user.ToJson();
                            characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                            bytes = Encoding.UTF8.GetBytes(characters);
                            resource = new Uri(addressBase, WebServiceUnitTest.AddressRelativeUsers);
                            client.Headers.Clear();
                            client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                            response = client.UploadData(resource.AbsoluteUri, WebRequestMethods.Http.Post, bytes);
                            responseCharacters = Encoding.UTF8.GetString(response);
                            responseJson =
                                WebServiceUnitTest.Serializer.Value.Deserialize<Dictionary<string, object>>(responseCharacters);
                            user = new Core2EnterpriseUserJsonDeserializingFactory().Create(responseJson);
                            identifierMemberTwo = user.Identifier;

                            try
                            {
                                IResourceIdentifier resourceIdentifier =
                                    new ResourceIdentifier()
                                    {
                                        Identifier = identifierGroupAmazon,
                                        SchemaIdentifier = SchemaIdentifiers.WindowsAzureActiveDirectoryGroup
                                    };

                                IPath path = Microsoft.SystemForCrossDomainIdentityManagement.Path.Create(AttributeNames.Members);

                                OperationValue operationValue;
                                PatchOperation operation;
                                IReadOnlyCollection<PatchOperation> operations;
                                PatchRequest2 patch;
                                                                
                                operationValue =
                                    new OperationValue()
                                    {
                                        Value = identifierMemberTwo
                                    };
                                operation =
                                    new PatchOperation()
                                    {
                                        Name = OperationName.Add,
                                        Path = path
                                    };
                                operations =
                                    new PatchOperation[] 
                                        { 
                                            operation 
                                        };
                                operation.AddValue(operationValue);                                
                                
                                patch = new PatchRequest2();
                                patch.AddOperation(operation);
                                json = patch.ToJson();
                                characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                                bytes = Encoding.UTF8.GetBytes(characters);
                                resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeGroup, identifierGroupAmazon);
                                resource = new Uri(addressBase, resourcePath);
                                client.Headers.Clear();
                                client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                                response = client.UploadData(resource.AbsoluteUri, WebServiceUnitTest.MethodPatch, bytes);

                                operationValue =
                                   new OperationValue()
                                   {
                                       Value = identifierMemberTwo
                                   };
                                operation =
                                    new PatchOperation()
                                    {
                                        Name = OperationName.Remove,
                                        Path = path
                                    };
                                operations =
                                    new PatchOperation[] 
                                        { 
                                            operation 
                                        };
                                operation.AddValue(operationValue);

                                patch = new PatchRequest2();
                                patch.AddOperation(operation);
                                json = patch.ToJson();
                                characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                                bytes = Encoding.UTF8.GetBytes(characters);
                                resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeGroup, identifierGroupAmazon);
                                resource = new Uri(addressBase, resourcePath);
                                client.Headers.Clear();
                                client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                                response = client.UploadData(resource.AbsoluteUri, WebServiceUnitTest.MethodPatch, bytes);

                                operationValue =
                                   new OperationValue()
                                   {
                                       Value = identifierMemberOne
                                   };
                                operation =
                                    new PatchOperation()
                                    {
                                        Name = OperationName.Remove,
                                        Path = path
                                    };
                                operations =
                                    new PatchOperation[] 
                                        { 
                                            operation 
                                        };
                                operation.AddValue(operationValue);

                                patch = new PatchRequest2();
                                patch.AddOperation(operation);
                                json = patch.ToJson();
                                characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                                bytes = Encoding.UTF8.GetBytes(characters);
                                resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeGroup, identifierGroupAmazon);
                                resource = new Uri(addressBase, resourcePath);
                                client.Headers.Clear();
                                client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                                response = client.UploadData(resource.AbsoluteUri, WebServiceUnitTest.MethodPatch, bytes);
                            }
                            finally
                            {
                                resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeUser, identifierMemberTwo);
                                resource = new Uri(addressBase, resourcePath);
                                bytes = new byte[0];
                                client.UploadData(resource, WebServiceUnitTest.MethodDelete, bytes);
                            }
                        }
                        finally
                        {
                            string resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeGroup, identifierGroupAmazon);
                            resource = new Uri(addressBase, resourcePath);
                            bytes = new byte[0];
                            client.UploadData(resource, WebServiceUnitTest.MethodDelete, bytes);
                        }
                    }
                    finally
                    {
                        string resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeUser, identifierMemberOne);
                        resource = new Uri(addressBase, resourcePath);
                        bytes = new byte[0];
                        client.UploadData(resource, WebServiceUnitTest.MethodDelete, bytes);
                    }
                }
                finally
                {
                    if (client != null)
                    {
                        client.Dispose();
                        client = null;
                    }
                }
            }
            finally
            {
                if (webService != null)
                {
                    webService.Dispose();
                    webService = null;
                }
            }
        }
        public override Task UpdateAsync(IPatch patch, string correlationIdentifier)
        {
            if (null == patch)
            {
                throw new ArgumentNullException(nameof(patch));
            }

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

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

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

            PatchRequest2 patchRequest = patch.PatchRequest as PatchRequest2;

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

            // call service
            TargetUser target;

            try
            {
                // get user
                target = _storageService.RetrieveUser(new Guid(patch.ResourceIdentifier.Identifier));

                // patch user
                Core2EnterpriseUser patched = (Core2EnterpriseUser)target;
                patched.Apply(patchRequest);

                // update user
                _storageService.UpdateUser((TargetUser)patched);
            }
            catch (Exception err)
            {
                switch (err.Message)
                {
                case "Conflict":
                    throw new HttpResponseException(HttpStatusCode.Conflict);

                case "NotFound":
                    throw new HttpResponseException(HttpStatusCode.NotFound);

                default:
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }
            }

            return(Task.CompletedTask);
        }
        public override async Task<Resource> Retrieve(
            IResourceRetrievalParameters parameters, 
            string correlationIdentifier)
        {
            if (null == parameters)
            {
                throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameParameters);
            }

            if (string.IsNullOrWhiteSpace(correlationIdentifier))
            {
                throw new ArgumentNullException(AmazonWebServicesProvider.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,
                    AmazonProvisioningAgentResources.InformationRetrieving,
                    parameters.SchemaIdentifier,
                    parameters.ResourceIdentifier.Identifier);
            ProvisioningAgentMonitor.Instance.Inform(informationStarting, true, correlationIdentifier);

            AmazonWebServicesProvider.Validate(parameters);

             IAmazonIdentityManagementService proxy = null;
             try
             {
                 proxy = AWSClientFactory.CreateAmazonIdentityManagementServiceClient(this.credentials);

                 switch (parameters.SchemaIdentifier)
                 {
                     case SchemaIdentifiers.Core2EnterpriseUser:
                         Amazon.IdentityManagement.Model.User user = 
                             await this.RetrieveUser(parameters.ResourceIdentifier.Identifier, proxy);
                         Core2EnterpriseUser resourceUser =
                             new Core2EnterpriseUser()
                                 {
                                     Identifier = user.UserId,
                                     ExternalIdentifier = user.UserName
                                 };
                         return resourceUser;

                     case SchemaIdentifiers.WindowsAzureActiveDirectoryGroup:
                         Group group = 
                             await this.RetrieveGroup(parameters.ResourceIdentifier.Identifier, proxy);
                         WindowsAzureActiveDirectoryGroup resourceGroup =
                             new WindowsAzureActiveDirectoryGroup()
                                 {
                                     Identifier = group.GroupId,
                                     ExternalIdentifier = group.GroupName
                                 };
                         return resourceGroup;

                     default:
                         throw new NotSupportedException(parameters.SchemaIdentifier);
                 }
             }
             finally
             {
                 if (proxy != null)
                 {
                     proxy.Dispose();
                     proxy = null;
                 }
             }
        }
        public override async Task<Resource[]> Query(
            IQueryParameters parameters, 
            string correlationIdentifier)
        {
            if (null == parameters)
            {
                throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameParameters);
            }

            if (string.IsNullOrWhiteSpace(correlationIdentifier))
            {
                throw new ArgumentNullException(AmazonWebServicesProvider.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;
            }

            AmazonWebServicesProvider.Validate(parameters);

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

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

            if (!string.Equals(queryFilter.AttributePath, AttributeNames.ExternalIdentifier, StringComparison.Ordinal))
            {
                throw new NotSupportedException(queryFilter.AttributePath);
            }

            IAmazonIdentityManagementService proxy = null;
            try
            {
                proxy = AWSClientFactory.CreateAmazonIdentityManagementServiceClient(this.credentials);            

                switch (parameters.SchemaIdentifier)
                {
                    case SchemaIdentifiers.Core2EnterpriseUser:
                        GetUserRequest getRequestUser =
                            new GetUserRequest()
                                {
                                    UserName = queryFilter.ComparisonValue
                                };
                        GetUserResult responseUser = await proxy.GetUserAsync(getRequestUser);
                        if (null == responseUser.User)
                        {
                            return new Resource[0];
                        }

                        Core2EnterpriseUser resourceUser =
                            new Core2EnterpriseUser()
                            {
                                Identifier = responseUser.User.UserId,
                                ExternalIdentifier = responseUser.User.UserName
                            };
                        Resource[] resourceUsers =
                            new Resource[]
                            {
                                resourceUser
                            };
                        return resourceUsers;

                    case SchemaIdentifiers.WindowsAzureActiveDirectoryGroup:
                        GetGroupRequest getRequestGroup =
                            new GetGroupRequest()
                                {
                                    GroupName = queryFilter.ComparisonValue
                                };
                        GetGroupResult responseGroup = await proxy.GetGroupAsync(getRequestGroup);
                        if (null == responseGroup.Group)
                        {
                            return new Resource[0];
                        }

                        WindowsAzureActiveDirectoryGroup resourceGroup =
                            new WindowsAzureActiveDirectoryGroup()
                            {
                                Identifier = responseGroup.Group.GroupId,
                                ExternalIdentifier = responseGroup.Group.GroupName
                            };
                        Resource[] resourceGroups =
                            new Resource[]
                            {
                                resourceGroup
                            };
                        return resourceGroups;

                    default:
                        throw new NotSupportedException(parameters.SchemaIdentifier);
                }
            }
            finally
            {
                if (proxy != null)
                {
                    proxy.Dispose();
                    proxy = null;
                }
            }
        }
        public Resource ComposeUserResource()
        {
            int            countValues = 4;
            IList <string> values      = new List <string>(countValues);

            for (int valueIndex = 0; valueIndex < countValues; valueIndex++)
            {
                string value = Guid.NewGuid().ToString(SampleComposer.FormatUniqueIdentifierCompressed);
                values.Add(value);
            }

            ElectronicMailAddress electronicMailAddress = new ElectronicMailAddress();

            electronicMailAddress.ItemType = ElectronicMailAddress.Work;
            electronicMailAddress.Primary  = false;
            electronicMailAddress.Value    =
                string.Format(
                    CultureInfo.InvariantCulture,
                    SampleComposer.ElectronicMailAddressTemplate,
                    values[1]);

            int countProxyAddresses = 2;
            IList <ElectronicMailAddress> proxyAddresses = new List <ElectronicMailAddress>(countProxyAddresses);

            for (int proxyAddressIndex = 0; proxyAddressIndex < countProxyAddresses; proxyAddressIndex++)
            {
                ElectronicMailAddress proxyAddress = new ElectronicMailAddress();
                proxyAddress.ItemType = ElectronicMailAddress.Other;
                proxyAddress.Primary  = false;
                proxyAddress.Value    =
                    string.Format(
                        CultureInfo.InvariantCulture,
                        SampleComposer.ElectronicMailAddressTemplate,
                        values[2 + proxyAddressIndex]);
                proxyAddresses.Add(proxyAddress);
            }

            Core2EnterpriseUser result = new Core2EnterpriseUser();

            result.Identifier         = Guid.NewGuid().ToString();
            result.ExternalIdentifier = values[0];
            result.Active             = true;
            result.DisplayName        = values[0];

            result.Name            = new Name();
            result.Name.FamilyName = values[0];
            result.Name.GivenName  = values[0];

            Address workAddress = new Address();

            workAddress.ItemType      = Address.Work;
            workAddress.StreetAddress = values[0];
            workAddress.PostalCode    = values[0];

            Address officeLocation = new Address();

            officeLocation.ItemType  = Address.Other;
            officeLocation.Primary   = false;
            officeLocation.Formatted = values[0];

            PhoneNumber phoneNumberWork = new PhoneNumber();

            phoneNumberWork.ItemType = PhoneNumber.Work;
            phoneNumberWork.Value    = SampleComposer.FictitiousPhoneNumber.ToString(CultureInfo.InvariantCulture);

            PhoneNumber phoneNumberMobile = new PhoneNumber();

            phoneNumberMobile.ItemType = PhoneNumber.Mobile;
            phoneNumberMobile.Value    = (SampleComposer.FictitiousPhoneNumber + 1).ToString(CultureInfo.InvariantCulture);

            PhoneNumber phoneNumberFacsimile = new PhoneNumber();

            phoneNumberFacsimile.ItemType = PhoneNumber.Fax;
            phoneNumberFacsimile.Value    = (SampleComposer.FictitiousPhoneNumber + 2).ToString(CultureInfo.InvariantCulture);

            PhoneNumber phoneNumberPager = new PhoneNumber();

            phoneNumberPager.ItemType = PhoneNumber.Pager;
            phoneNumberPager.Value    = (SampleComposer.FictitiousPhoneNumber + 3).ToString(CultureInfo.InvariantCulture);

            result.UserName =
                string.Format(
                    CultureInfo.InvariantCulture,
                    SampleComposer.ElectronicMailAddressTemplate,
                    values[0]);

            result.Addresses =
                new Address[]
            {
                workAddress,
                officeLocation
            };

            result.ElectronicMailAddresses =
                new ElectronicMailAddress[]
            {
                electronicMailAddress,
            }
            .Union(proxyAddresses)
            .ToArray();

            result.PhoneNumbers =
                new PhoneNumber[]
            {
                phoneNumberWork,
                phoneNumberFacsimile,
                phoneNumberMobile,
                phoneNumberPager
            };

            return(result);
        }
        public void TestLifecycleUser()
        {
            Uri addressBase = new Uri(WebServiceUnitTest.AddressBase);

            IMonitor monitor = new ConsoleMonitor();
            
            IAmazonWebServicesIdentityAnchoringBehavior anchoringBehavior = 
                new AnchoringByIdentifierBehavior();
            AmazonWebServicesProviderBase provider = new AmazonWebServicesProvider(WebServiceUnitTest.CredentialsProfileName, anchoringBehavior);
            Service webService = null;
            try
            {
                webService = new WebService(monitor, provider);
                webService.Start(addressBase);

                string identifier = Guid.NewGuid().ToString();
                string identifierExternal = Guid.NewGuid().ToString();
                Core2EnterpriseUser user =
                    new Core2EnterpriseUser()
                    {
                        Identifier = identifier,
                        ExternalIdentifier = identifierExternal
                    };
                IDictionary<string, object> json = user.ToJson();
                string characters = WebServiceUnitTest.Serializer.Value.Serialize(json);
                byte[] bytes = Encoding.UTF8.GetBytes(characters);

                Uri resource = new Uri(addressBase, WebServiceUnitTest.AddressRelativeUsers);

                WebClient client = null;
                try
                {
                    client = new WebClient();
                    client.Headers.Add(HttpRequestHeader.ContentType, WebServiceUnitTest.ContentTypeJson);
                    byte[] response = client.UploadData(resource.AbsoluteUri, WebRequestMethods.Http.Post, bytes);
                    string responseCharacters = Encoding.UTF8.GetString(response);
                    IReadOnlyDictionary<string, object> responseJson =
                        WebServiceUnitTest.Serializer.Value.Deserialize<Dictionary<string, object>>(responseCharacters);
                    user = new Core2EnterpriseUserJsonDeserializingFactory().Create(responseJson);
                    Assert.IsNotNull(user);
                    Assert.IsNotNull(
                        user
                        .Schemas
                        .SingleOrDefault(
                            (string item) =>
                                string.Equals(
                                    SchemaIdentifiers.Core2EnterpriseUser,
                                    item,
                                    StringComparison.Ordinal)));
                    Assert.IsFalse(string.IsNullOrWhiteSpace(user.Identifier));

                    string identifierAmazon = user.Identifier;
                    string resourcePath = string.Concat(WebServiceUnitTest.AddressRelativeUser, identifierAmazon);
                    resource = new Uri(addressBase, resourcePath);

                    try
                    {
                        Assert.IsNotNull(user.Metadata);
                        Assert.IsFalse(string.IsNullOrWhiteSpace(user.Metadata.ResourceType));
                        Assert.IsFalse(string.Equals(identifier, identifierAmazon, StringComparison.OrdinalIgnoreCase));

                        response = client.DownloadData(resource);
                        responseCharacters = Encoding.UTF8.GetString(response);
                        responseJson =
                            WebServiceUnitTest.Serializer.Value.Deserialize<Dictionary<string, object>>(responseCharacters);
                        user = new Core2EnterpriseUserJsonDeserializingFactory().Create(responseJson);
                        Assert.IsNotNull(user);
                        Assert.IsNotNull(
                            user
                            .Schemas
                            .SingleOrDefault(
                                (string item) =>
                                    string.Equals(
                                        SchemaIdentifiers.Core2EnterpriseUser,
                                        item,
                                        StringComparison.Ordinal)));
                        Assert.IsFalse(string.IsNullOrWhiteSpace(user.Identifier));
                        Assert.IsTrue(string.Equals(user.Identifier, identifierAmazon, StringComparison.OrdinalIgnoreCase));

                        Assert.IsFalse(string.IsNullOrWhiteSpace(user.ExternalIdentifier));
                        Assert.IsTrue(string.Equals(user.ExternalIdentifier, identifierExternal, StringComparison.OrdinalIgnoreCase));
                    }
                    finally
                    {
                        bytes = new byte[0];
                        client.UploadData(resource, WebServiceUnitTest.MethodDelete, bytes);
                    }
                }
                finally
                {
                    if (client != null)
                    {
                        client.Dispose();
                        client = null;
                    }
                }
            }
            finally
            {
                if (webService != null)
                {
                    webService.Dispose();
                    webService = null;
                }
            }
        }