private static void RemoveRuleGroup(ManagementService managementService, string ruleGroupName)
        {
            Guard.NotNullOrEmpty(() => ruleGroupName, ruleGroupName);

            var rgToRemove = managementService.RuleGroups.Where(
                rg => rg.Name.Equals(ruleGroupName)).Single();

            managementService.DeleteObject(rgToRemove);
        }
        private static void LinkRuleGroupToRelyingParty(ManagementService client, RuleGroup ruleGroup, RelyingParty relyingParty)
        {
            Guard.NotNull(() => ruleGroup, ruleGroup);
            Guard.NotNull(() => relyingParty, relyingParty);

            var relyingPartyRuleGroup = new RelyingPartyRuleGroup
                {
                    RuleGroupId = ruleGroup.Id,
                    RelyingParty = relyingParty
                };

            client.AddRelatedObject(relyingParty, "RelyingPartyRuleGroups", relyingPartyRuleGroup);
            client.SaveChanges(SaveChangesOptions.Batch);
        }
        private void RemoveRelatedKeys(RelyingParty rpToRemove, ManagementService client, Action<LogInfo> logAction)
        {
            var pendingChanges = false;

            foreach (var key in rpToRemove.RelyingPartyKeys)
            {
                RelyingPartyKey keyLocal = key;
                var keyToRemove = client.RelyingPartyKeys.Where(
                    k => k.DisplayName.Equals(keyLocal.DisplayName)).Single();

                this.LogMessage(logAction, string.Format("Removing Key '{0}'", keyLocal.DisplayName));
                client.DeleteObject(keyToRemove);

                pendingChanges = true;
            }

            if (pendingChanges)
            {
                client.SaveChanges(SaveChangesOptions.Batch);
                this.LogSavingChangesMessage(logAction);
            }
        }
        private void LinkExistingRuleGroups(ManagementService client, Action<LogInfo> logAction)
        {
            foreach (var linkedRuleGroup in this.relyingPartySpec.LinkedRuleGroups())
            {
                var @group = linkedRuleGroup;
                DataServiceCollection<RuleGroup> ruleGroups = new DataServiceCollection<RuleGroup>(client.RuleGroups);

                while (ruleGroups.Continuation != null)
                {
                    ruleGroups.Load(client.Execute<RuleGroup>(ruleGroups.Continuation));
                }

                foreach (var ruleGroup in ruleGroups.Where(rg => System.Text.RegularExpressions.Regex.IsMatch(rg.Name, group)))
                {
                    var relyingParty = client.RelyingParties.Where(rp => rp.Name.Equals(this.relyingPartySpec.Name())).Single();

                    var relyingPartyRuleGroup = new RelyingPartyRuleGroup
                    {
                        RuleGroupId = ruleGroup.Id,
                        RelyingParty = relyingParty
                    };

                    this.LogMessage(logAction, string.Format("Linking Relying Party '{0}' to Rule Group '{1}'", this.relyingPartySpec.Name(), ruleGroup.Name));
                    client.AddRelatedObject(relyingParty, "RelyingPartyRuleGroups", relyingPartyRuleGroup);
                }
            }

            if (this.relyingPartySpec.LinkedRuleGroups().Any())
            {
                client.SaveChanges(SaveChangesOptions.Batch);
                this.LogSavingChangesMessage(logAction);
            }
        }
        private static void CreateRelyingParty(ManagementService client, string relyingPartyName, string ruleGroupName, string realmAddress, string replyAddress, TokenType tokenType, int tokenLifetime, bool asymmetricTokenEncryptionRequired, out RelyingParty relyingParty)
        {
            // Create Relying Party
            relyingParty = new RelyingParty
                               {
                                   Name = relyingPartyName,
                                   DisplayName = relyingPartyName,
                                   Description = relyingPartyName,
                                   TokenType = tokenType.ToString(),
                                   TokenLifetime = tokenLifetime,
                                   AsymmetricTokenEncryptionRequired = asymmetricTokenEncryptionRequired
                               };

            client.AddObject("RelyingParties", relyingParty);
            client.SaveChanges();

            if (!string.IsNullOrWhiteSpace(ruleGroupName))
            {
                RuleGroup ruleGroup = client.RuleGroups.Where(rg => rg.Name.Equals(ruleGroupName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (ruleGroup == null)
                {
                    ruleGroup = new RuleGroup
                                    {
                                        Name = ruleGroupName
                                    };

                    client.AddToRuleGroups(ruleGroup);
                    client.SaveChanges();
                }

                var relyingPartyRuleGroup = new RelyingPartyRuleGroup
                                                {
                                                    RuleGroupId = ruleGroup.Id,
                                                    RelyingParty = relyingParty
                                                };

                client.AddRelatedObject(relyingParty, "RelyingPartyRuleGroups", relyingPartyRuleGroup);
            }

            // Create the Realm for Relying Party
            var realm = new RelyingPartyAddress
                            {
                                Address = realmAddress,
                                EndpointType = RelyingPartyAddressEndpointType.Realm.ToString(),
                                RelyingParty = relyingParty
                            };

            client.AddRelatedObject(relyingParty, "RelyingPartyAddresses", realm);

            if (!string.IsNullOrEmpty(replyAddress))
            {
                var reply = new RelyingPartyAddress
                                {
                                    Address = replyAddress,
                                    EndpointType = RelyingPartyAddressEndpointType.Reply.ToString(),
                                    RelyingParty = relyingParty
                                };

                client.AddRelatedObject(relyingParty, "RelyingPartyAddresses", reply);
            }

            client.SaveChanges(SaveChangesOptions.Batch);
        }
        private static void AddSigningKeyToRelyingParty(ManagementService client, string relyingPartyName, byte[] symmetricKey, DateTime defaultStartDate, DateTime defaultEndDate, RelyingParty relyingParty)
        {
            var relyingPartyKey = new RelyingPartyKey
                                      {
                                          DisplayName = "Signing Key for " + relyingPartyName,
                                          Type = KeyType.Symmetric.ToString(),
                                          Usage = KeyUsage.Signing.ToString(),
                                          Value = symmetricKey,
                                          RelyingParty = relyingParty,
                                          StartDate = defaultStartDate,
                                          EndDate = defaultEndDate,
                                          IsPrimary = true
                                      };

            client.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);

            client.SaveChanges();
        }
        private static void AddSigningKeyToRelyingParty(ManagementService client, string relyingPartyName, byte[] signingCert, string signingCertPassword, DateTime defaultStartDate, DateTime defaultEndDate, RelyingParty relyingParty)
        {
            var relyingPartyKey = new RelyingPartyKey
                                      {
                                          DisplayName = "Signing Certificate for " + relyingPartyName,
                                          Type = KeyType.X509Certificate.ToString(),
                                          Usage = KeyUsage.Signing.ToString(),
                                          Value = signingCert,
                                          Password = string.IsNullOrEmpty(signingCertPassword) ? null : new UTF8Encoding().GetBytes(signingCertPassword),
                                          RelyingParty = relyingParty,
                                          StartDate = defaultStartDate,
                                          EndDate = defaultEndDate,
                                          IsPrimary = true
                                      };

            client.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);

            client.SaveChanges();
        }
        private static void AddIdentityProviderToRelyingParty(ManagementService client, string[] allowedIdentityProviders, RelyingParty relyingParty)
        {
            // if no allowed identity providers were set, allow all
            if (allowedIdentityProviders == null)
            {
                allowedIdentityProviders = client.IdentityProviders.ToList().Select(idp => idp.DisplayName).ToArray();
            }

            foreach (var allowedIdp in allowedIdentityProviders)
            {
                var idp = client.IdentityProviders
                    .Where(i => i.DisplayName.Equals(allowedIdp, StringComparison.OrdinalIgnoreCase))
                    .FirstOrDefault();

                if (idp != null)
                {
                    var rpidp = new RelyingPartyIdentityProvider
                                    {
                                        IdentityProviderId = idp.Id,
                                        RelyingPartyId = relyingParty.Id
                                    };

                    client.AddToRelyingPartyIdentityProviders(rpidp);
                    client.SaveChanges();
                }
            }
        }
        private static void AddEncryptionKeyToRelyingParty(ManagementService client, string relyingPartyName, byte[] encryptionCert, DateTime defaultStartDate, DateTime defaultEndDate, RelyingParty relyingParty)
        {
            var relyingPartyKey = new RelyingPartyKey
                                      {
                                          DisplayName = "Encryption Certificate for " + relyingPartyName,
                                          Type = KeyType.X509Certificate.ToString(),
                                          Usage = KeyUsage.Encrypting.ToString(),
                                          Value = encryptionCert,
                                          RelyingParty = relyingParty,
                                          StartDate = defaultStartDate,
                                          EndDate = defaultEndDate
                                      };

            client.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);

            client.SaveChanges();
        }
        public ManagementService CreateManagementServiceClient()
        {
            var managementServiceEndpoint = string.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/{2}", this.serviceNamespace, Constants.AcsHostName, Constants.ManagementServiceHead);

                var managementService = new ManagementService(new Uri(managementServiceEndpoint))
                                            {
                                                IgnoreMissingProperties = true
                                            };
                managementService.SendingRequest += this.AttachTokenWithWritePermissions;

            return managementService;
        }