/// <summary>
        /// Rotate either the primary or secondary connection string key of the Azure Service Bus resource.
        /// </summary>
        /// <param name="keyType">The type of the key to rotate.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="keyType"/> is outside the bounds of the enumeration.</exception>
        public async Task <string> RotateConnectionStringKeyAsync(KeyType keyType)
        {
            Guard.For <ArgumentOutOfRangeException>(
                () => !Enum.IsDefined(typeof(KeyType), keyType),
                $"Requires the KeyType value to be either '{nameof(KeyType.PrimaryKey)}' or '{nameof(KeyType.SecondaryKey)}'");

            try
            {
                using IServiceBusManagementClient client = await _authentication.AuthenticateAsync();

                _logger.LogTrace(
                    "Start rotating {KeyType} connection string of Azure Service Bus {EntityType} '{EntityName}'...",
                    keyType, Namespace.Entity, Namespace.EntityName);

                AccessKeys keys = await RegenerateAzureServiceBusKeysAsync(Namespace.Entity, Namespace.EntityName, keyType, client);

                _logger.LogWarning(
                    "Rotated {KeyType} connection string of Azure Service Bus {EntityType} '{EntityName}'",
                    keyType, Namespace.Entity, Namespace.EntityName);

                return(keyType switch
                {
                    KeyType.PrimaryKey => keys.PrimaryConnectionString,
                    KeyType.SecondaryKey => keys.SecondaryConnectionString,
                    _ => throw new ArgumentOutOfRangeException(nameof(keyType), keyType, "Unknown key type")
                });
            }
示例#2
0
 /// <summary>
 /// Initializes a new instance of the AuthorizationRuleKeysAttributes class with a Azure.Management.Relay.Models.AuthorizationRuleKeys
 /// </summary>
 /// <param name="authorizationruleskeys"></param>
 public PSAuthorizationRuleKeysAttributes(AccessKeys authorizationruleskeys)
 {
     PrimaryConnectionString   = authorizationruleskeys.PrimaryConnectionString;
     SecondaryConnectionString = authorizationruleskeys.SecondaryConnectionString;
     PrimaryKey   = authorizationruleskeys.PrimaryKey;
     SecondaryKey = authorizationruleskeys.SecondaryKey;
     KeyName      = authorizationruleskeys.KeyName;
 }
示例#3
0
        public virtual IActionResult Invalidate([FromBody] AccessKeys accessKeys)
        {
            //TODO: Uncomment the next line to return response 204 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
            // return StatusCode(204);

            //TODO: Uncomment the next line to return response 400 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
            // return StatusCode(400, default(Error));


            throw new NotImplementedException();
        }
示例#4
0
        public async Task <string> GetConnectionStringAsync()
        {
            await EnsureAuthenticatedAsync();

            AccessKeys keys = await _client.Namespaces
                              .ListKeysAsync(_azureResourceIdentifier.ResourceGroupName,
                                             _azureResourceIdentifier.Name,
                                             "RootManageSharedAccessKey");

            return(keys.PrimaryConnectionString);
        }
示例#5
0
        /// <summary>
        /// Gets the connection string keys for the Azure Service Bus Topic tested in the integration test suite.
        /// </summary>
        public async Task <AccessKeys> GetConnectionStringKeysForTopicAsync()
        {
            using IServiceBusManagementClient client = await CreateServiceManagementClientAsync();

            AccessKeys accessKeys = await client.Topics.ListKeysAsync(
                _configuration.ServiceBusNamespace.ResourceGroup,
                _configuration.ServiceBusNamespace.Namespace,
                _configuration.ServiceBusNamespace.TopicName,
                _configuration.ServiceBusNamespace.AuthorizationRuleName);

            return(accessKeys);
        }
示例#6
0
 public AuthorizationRuleKeysAttributes(AccessKeys listKeysResource)
 {
     if (listKeysResource != null)
     {
         PrimaryConnectionString   = listKeysResource.PrimaryConnectionString;
         SecondaryConnectionString = listKeysResource.SecondaryConnectionString;
         PrimaryKey   = listKeysResource.PrimaryKey;
         SecondaryKey = listKeysResource.SecondaryKey;
         KeyName      = listKeysResource.KeyName;
     }
     ;
 }
        public static void Print(AccessKeys resource)
        {
            StringBuilder info = new StringBuilder();

            info.Append("DisasterRecoveryPairing auth key: ")
            .Append("\n\t Alias primary connection string: ").Append(resource.AliasPrimaryConnectionString)
            .Append("\n\t Alias secondary connection string: ").Append(resource.AliasSecondaryConnectionString)
            .Append("\n\t Primary key: ").Append(resource.PrimaryKey)
            .Append("\n\t Secondary key: ").Append(resource.SecondaryKey)
            .Append("\n\t Primary connection string: ").Append(resource.PrimaryConnectionString)
            .Append("\n\t Secondary connection string: ").Append(resource.SecondaryConnectionString);
            Utilities.Log(info.ToString());
        }
示例#8
0
        public async Task <string> GetConnectionStringAsync(string eventHub)
        {
            await EnsureAuthenticatedAsync();

            AzureOperationResponse <AccessKeys> responseKeys = await _client.EventHubs.ListKeysWithHttpMessagesAsync(_azureResourceIdentifier.ResourceGroupName,
                                                                                                                     _azureResourceIdentifier.Name, eventHub, "sender");

            AccessKeys keys = responseKeys.Body;

            var eventHubNamespaceUri    = new Uri($"sb://{_azureResourceIdentifier.Name}.servicebus.windows.net");
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(eventHubNamespaceUri, eventHub, keys.KeyName, keys.PrimaryKey);

            return(connectionStringBuilder.ToString());
        }
示例#9
0
 public PSListKeysAttributes(AccessKeys listKeysResource)
 {
     if (listKeysResource != null)
     {
         PrimaryConnectionString   = listKeysResource.PrimaryConnectionString;
         SecondaryConnectionString = listKeysResource.SecondaryConnectionString;
         PrimaryKey   = listKeysResource.PrimaryKey;
         SecondaryKey = listKeysResource.SecondaryKey;
         KeyName      = listKeysResource.KeyName;
         AliasPrimaryConnectionString   = listKeysResource.AliasPrimaryConnectionString;
         AliasSecondaryConnectionString = listKeysResource.AliasSecondaryConnectionString;
     }
     ;
 }
示例#10
0
        /// <summary>
        /// Rotates the connection string key of the Azure Service Bus Queue, returning the new connection string as result.
        /// </summary>
        /// <param name="keyType">The type of key to rotate.</param>
        /// <returns>
        ///     The new connection string according to the <paramref name="keyType"/>.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="keyType"/> is not within the bounds of the enumration.</exception>
        public async Task <string> RotateConnectionStringKeysForQueueAsync(KeyType keyType)
        {
            Guard.For <ArgumentOutOfRangeException>(
                () => !Enum.IsDefined(typeof(KeyType), keyType),
                $"Requires a KeyType that is either '{nameof(KeyType.PrimaryKey)}' or '{nameof(KeyType.SecondaryKey)}'");

            var    parameters = new RegenerateAccessKeyParameters(keyType);
            string queueName  = _configuration.ServiceBusNamespace.QueueName;
            const ServiceBusEntityType entity = ServiceBusEntityType.Queue;

            try
            {
                using IServiceBusManagementClient client = await CreateServiceManagementClientAsync();

                _logger.LogTrace(
                    "Start rotating {KeyType} connection string of Azure Service Bus {EntityType} '{EntityName}'...",
                    keyType, entity, queueName);

                AccessKeys accessKeys = await client.Queues.RegenerateKeysAsync(
                    _configuration.ServiceBusNamespace.ResourceGroup,
                    _configuration.ServiceBusNamespace.Namespace,
                    queueName,
                    _configuration.ServiceBusNamespace.AuthorizationRuleName,
                    parameters);

                _logger.LogInformation(
                    "Rotated {KeyType} connection string of Azure Service Bus {EntityType} '{EntityName}'",
                    keyType, entity, queueName);

                switch (keyType)
                {
                case KeyType.PrimaryKey:   return(accessKeys.PrimaryConnectionString);

                case KeyType.SecondaryKey: return(accessKeys.SecondaryConnectionString);

                default:
                    throw new ArgumentOutOfRangeException(nameof(keyType), keyType, "Unknown key type");
                }
            }
            catch (Exception exception)
            {
                _logger.LogError(
                    exception, "Failed to rotate the {KeyType} connection string of the Azure Service Bus {EntityType} '{EntityName}'", keyType, entity, queueName);

                throw;
            }
        }
示例#11
0
        /// <summary>
        ///
        /// </summary>
        /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="accessKeys"></param>
        /// <returns>ApiResponse of Object(void)</returns>
        public Org.OpenAPITools.Client.ApiResponse <Object> ValidateWithHttpInfo(AccessKeys accessKeys)
        {
            // verify the required parameter 'accessKeys' is set
            if (accessKeys == null)
            {
                throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'accessKeys' when calling DefaultApi->Validate");
            }

            Org.OpenAPITools.Client.RequestOptions requestOptions = new Org.OpenAPITools.Client.RequestOptions();

            String[] @contentTypes = new String[] {
                "application/json"
            };

            // to determine the Accept header
            String[] @accepts = new String[] {
                "application/json"
            };

            foreach (var contentType in @contentTypes)
            {
                requestOptions.HeaderParameters.Add("Content-Type", contentType);
            }

            foreach (var accept in @accepts)
            {
                requestOptions.HeaderParameters.Add("Accept", accept);
            }

            requestOptions.Data = accessKeys;


            // make the HTTP request

            var response = this.Client.Post <Object>("/validate", requestOptions, this.Configuration);

            if (this.ExceptionFactory != null)
            {
                Exception exception = this.ExceptionFactory("Validate", response);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(response);
        }
        public async Task NamespaceAuthorizationRuleRegenerateKey()
        {
            IgnoreTestInLiveMode();
            //create namespace
            _resourceGroup = await CreateResourceGroupAsync();

            ServiceBusNamespaceCollection namespaceCollection = _resourceGroup.GetServiceBusNamespaces();
            string namespaceName = await CreateValidNamespaceName(namespacePrefix);

            ServiceBusNamespaceResource          serviceBusNamespace = (await namespaceCollection.CreateOrUpdateAsync(WaitUntil.Completed, namespaceName, new ServiceBusNamespaceData(DefaultLocation))).Value;
            NamespaceAuthorizationRuleCollection ruleCollection      = serviceBusNamespace.GetNamespaceAuthorizationRules();

            //create authorization rule
            string ruleName = Recording.GenerateAssetName("authorizationrule");
            ServiceBusAuthorizationRuleData parameter = new ServiceBusAuthorizationRuleData()
            {
                Rights = { AccessRights.Listen, AccessRights.Send }
            };
            NamespaceAuthorizationRuleResource authorizationRule = (await ruleCollection.CreateOrUpdateAsync(WaitUntil.Completed, ruleName, parameter)).Value;

            Assert.NotNull(authorizationRule);
            Assert.AreEqual(authorizationRule.Data.Rights.Count, parameter.Rights.Count);

            AccessKeys keys1 = await authorizationRule.GetKeysAsync();

            Assert.NotNull(keys1);
            Assert.NotNull(keys1.PrimaryConnectionString);
            Assert.NotNull(keys1.SecondaryConnectionString);

            AccessKeys keys2 = await authorizationRule.RegenerateKeysAsync(new RegenerateAccessKeyOptions(KeyType.PrimaryKey));

            if (Mode != RecordedTestMode.Playback)
            {
                Assert.AreNotEqual(keys1.PrimaryKey, keys2.PrimaryKey);
                Assert.AreEqual(keys1.SecondaryKey, keys2.SecondaryKey);
            }

            AccessKeys keys3 = await authorizationRule.RegenerateKeysAsync(new RegenerateAccessKeyOptions(KeyType.SecondaryKey));

            if (Mode != RecordedTestMode.Playback)
            {
                Assert.AreEqual(keys2.PrimaryKey, keys3.PrimaryKey);
                Assert.AreNotEqual(keys2.SecondaryKey, keys3.SecondaryKey);
            }
        }
示例#13
0
        public async Task RotateServiceBusSecrets_WithValidArguments_RotatesPrimarySecondaryAlternatively()
        {
            // Arrange
            var config = TestConfig.Create();
            KeyRotationConfig keyRotationConfig = config.GetKeyRotationConfig();

            _logger.LogInformation("Using Service Principal [ClientID: '{ClientId}']", keyRotationConfig.ServicePrincipal.ClientId);
            const ServiceBusEntityType entity = ServiceBusEntityType.Topic;

            var keyVaultAuthentication = new ServicePrincipalAuthentication(
                keyRotationConfig.ServicePrincipal.ClientId,
                keyRotationConfig.ServicePrincipal.ClientSecret);

            var keyVaultConfiguration = new KeyVaultConfiguration(keyRotationConfig.KeyVault.VaultUri);
            var secretProvider        = new KeyVaultSecretProvider(keyVaultAuthentication, keyVaultConfiguration);

            AzureServiceBusClient azureServiceBusClient = CreateAzureServiceBusClient(keyRotationConfig, secretProvider, entity);
            var rotation = new AzureServiceBusKeyRotation(azureServiceBusClient, keyVaultAuthentication, keyVaultConfiguration, _logger);

            var        client = new ServiceBusConfiguration(keyRotationConfig, _logger);
            AccessKeys keysBefore1stRotation = await client.GetConnectionStringKeysForTopicAsync();

            // Act
            await rotation.RotateServiceBusSecretAsync(keyRotationConfig.KeyVault.SecretName);

            // Assert
            string secondaryConnectionString = await secretProvider.GetRawSecretAsync(keyRotationConfig.KeyVault.SecretName);

            AccessKeys keysAfter1stRotation = await client.GetConnectionStringKeysForTopicAsync();

            Assert.True(secondaryConnectionString == keysAfter1stRotation.SecondaryConnectionString, "Secondary connection string should be set in Azure Key Vault after first rotation");
            Assert.NotEqual(keysBefore1stRotation.PrimaryConnectionString, keysAfter1stRotation.PrimaryConnectionString);
            Assert.NotEqual(keysBefore1stRotation.SecondaryConnectionString, keysAfter1stRotation.SecondaryConnectionString);

            await rotation.RotateServiceBusSecretAsync(keyRotationConfig.KeyVault.SecretName);

            string primaryConnectionString = await secretProvider.GetRawSecretAsync(keyRotationConfig.KeyVault.SecretName);

            AccessKeys keysAfter2ndRotation = await client.GetConnectionStringKeysForTopicAsync();

            Assert.True(primaryConnectionString == keysAfter2ndRotation.PrimaryConnectionString, "Primary connection string should be set in Azure Key Vault after second rotation");
            Assert.NotEqual(keysAfter1stRotation.PrimaryConnectionString, keysAfter2ndRotation.PrimaryConnectionString);
            Assert.NotEqual(keysAfter2ndRotation.SecondaryConnectionString, keysAfter1stRotation.SecondaryConnectionString);
        }
示例#14
0
        /// <summary>
        ///   Performs the tasks needed to create a new Event Hubs namespace within a resource group, intended to be used as
        ///   an ephemeral container for the Event Hub instances used in a given test run.
        /// </summary>
        ///
        /// <returns>The key attributes for identifying and accessing a dynamically created Event Hubs namespace.</returns>
        ///
        public static async Task<NamespaceProperties> CreateNamespaceAsync()
        {
            var subscription = TestEnvironment.EventHubsSubscription;
            var resourceGroup = TestEnvironment.EventHubsResourceGroup;
            var token = await ResourceManager.AquireManagementTokenAsync();

            string CreateName() => $"net-eventhubs-{ Guid.NewGuid().ToString("D") }";

            using (var client = new EventHubManagementClient(new TokenCredentials(token)) { SubscriptionId = subscription })
            {
                var location = await ResourceManager.QueryResourceGroupLocationAsync(token, resourceGroup, subscription);

                var eventHubsNamespace = new EHNamespace(sku: new Sku("Standard", "Standard", 12), tags: ResourceManager.GenerateTags(), isAutoInflateEnabled: true, maximumThroughputUnits: 20, location: location);
                eventHubsNamespace = await ResourceManager.CreateRetryPolicy<EHNamespace>().ExecuteAsync(() => client.Namespaces.CreateOrUpdateAsync(resourceGroup, CreateName(), eventHubsNamespace));

                AccessKeys accessKey = await ResourceManager.CreateRetryPolicy<AccessKeys>().ExecuteAsync(() => client.Namespaces.ListKeysAsync(resourceGroup, eventHubsNamespace.Name, TestEnvironment.EventHubsDefaultSharedAccessKey));
                return new NamespaceProperties(eventHubsNamespace.Name, accessKey.PrimaryConnectionString);
            }
        }
示例#15
0
        public async Task QueueAuthorizationRuleRegenerateKey()
        {
            IgnoreTestInLiveMode();
            //create queue
            string          queueName = Recording.GenerateAssetName("queue");
            ServiceBusQueue queue     = (await _queueCollection.CreateOrUpdateAsync(WaitUntil.Completed, queueName, new ServiceBusQueueData())).Value;
            NamespaceQueueAuthorizationRuleCollection ruleCollection = queue.GetNamespaceQueueAuthorizationRules();

            //create authorization rule
            string ruleName = Recording.GenerateAssetName("authorizationrule");
            ServiceBusAuthorizationRuleData parameter = new ServiceBusAuthorizationRuleData()
            {
                Rights = { AccessRights.Listen, AccessRights.Send }
            };
            NamespaceQueueAuthorizationRule authorizationRule = (await ruleCollection.CreateOrUpdateAsync(WaitUntil.Completed, ruleName, parameter)).Value;

            Assert.NotNull(authorizationRule);
            Assert.AreEqual(authorizationRule.Data.Rights.Count, parameter.Rights.Count);

            AccessKeys keys1 = await authorizationRule.GetKeysAsync();

            Assert.NotNull(keys1);
            Assert.NotNull(keys1.PrimaryConnectionString);
            Assert.NotNull(keys1.SecondaryConnectionString);

            AccessKeys keys2 = await authorizationRule.RegenerateKeysAsync(new RegenerateAccessKeyOptions(KeyType.PrimaryKey));

            //the recordings are sanitized therefore cannot be compared
            if (Mode != RecordedTestMode.Playback)
            {
                Assert.AreNotEqual(keys1.PrimaryKey, keys2.PrimaryKey);
                Assert.AreEqual(keys1.SecondaryKey, keys2.SecondaryKey);
            }

            AccessKeys keys3 = await authorizationRule.RegenerateKeysAsync(new RegenerateAccessKeyOptions(KeyType.SecondaryKey));

            if (Mode != RecordedTestMode.Playback)
            {
                Assert.AreEqual(keys2.PrimaryKey, keys3.PrimaryKey);
                Assert.AreNotEqual(keys2.SecondaryKey, keys3.SecondaryKey);
            }
        }
示例#16
0
        public async Task EventhubAuthorizationRuleRegenerateKey()
        {
            //create eventhub
            string           eventhubName = Recording.GenerateAssetName("eventhub");
            EventHubResource eventHub     = (await _eventHubCollection.CreateOrUpdateAsync(WaitUntil.Completed, eventhubName, new EventHubData())).Value;
            EventHubAuthorizationRuleCollection ruleCollection = eventHub.GetEventHubAuthorizationRules();

            //create authorization rule
            string ruleName = Recording.GenerateAssetName("authorizationrule");
            AuthorizationRuleData parameter = new AuthorizationRuleData()
            {
                Rights = { AccessRights.Listen, AccessRights.Send }
            };
            EventHubAuthorizationRuleResource authorizationRule = (await ruleCollection.CreateOrUpdateAsync(WaitUntil.Completed, ruleName, parameter)).Value;

            Assert.NotNull(authorizationRule);
            Assert.AreEqual(authorizationRule.Data.Rights.Count, parameter.Rights.Count);

            AccessKeys keys1 = await authorizationRule.GetKeysAsync();

            Assert.NotNull(keys1);
            Assert.NotNull(keys1.PrimaryConnectionString);
            Assert.NotNull(keys1.SecondaryConnectionString);

            AccessKeys keys2 = await authorizationRule.RegenerateKeysAsync(new RegenerateAccessKeyOptions(KeyType.PrimaryKey));

            //the recordings are sanitized therefore cannot be compared
            if (Mode != RecordedTestMode.Playback)
            {
                Assert.AreNotEqual(keys1.PrimaryKey, keys2.PrimaryKey);
                Assert.AreEqual(keys1.SecondaryKey, keys2.SecondaryKey);
            }

            AccessKeys keys3 = await authorizationRule.RegenerateKeysAsync(new RegenerateAccessKeyOptions(KeyType.SecondaryKey));

            if (Mode != RecordedTestMode.Playback)
            {
                Assert.AreEqual(keys2.PrimaryKey, keys3.PrimaryKey);
                Assert.AreNotEqual(keys2.SecondaryKey, keys3.SecondaryKey);
            }
        }
示例#17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="accessKeys"></param>
        /// <returns></returns>
        public void Validate(AccessKeys accessKeys)
        {
            // verify the required parameter 'accessKeys' is set
            if (accessKeys == null)
            {
                throw new ApiException(400, "Missing required parameter 'accessKeys' when calling Validate");
            }


            var path = "/validate";

            path = path.Replace("{format}", "json");

            var    queryParams  = new Dictionary <String, String>();
            var    headerParams = new Dictionary <String, String>();
            var    formParams   = new Dictionary <String, String>();
            var    fileParams   = new Dictionary <String, FileParameter>();
            String postBody     = null;

            postBody = ApiClient.Serialize(accessKeys);                                     // http body (model) parameter

            // authentication setting, if any
            String[] authSettings = new String[] {  };

            // make the HTTP request
            IRestResponse response = (IRestResponse)ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);

            if (((int)response.StatusCode) >= 400)
            {
                throw new ApiException((int)response.StatusCode, "Error calling Validate: " + response.Content, response.Content);
            }
            else if (((int)response.StatusCode) == 0)
            {
                throw new ApiException((int)response.StatusCode, "Error calling Validate: " + response.ErrorMessage, response.ErrorMessage);
            }

            return;
        }
示例#18
0
        public void InitializeBase(IWebDriver objDriver)
        {
            //LoginPage = new MdnHomePage(driver);
            //LoginPage1 = new MdnLoginPage1(driver);
            //HomePage = new MdnHomePage(driver);
            //CommonPage = new MdnCommonPage(driver);

            #region initialize old
            driver                = objDriver;
            CheckOutobj           = new CheckOut(driver);
            takeScreenhsot        = new ScreenShot(driver);
            approvalrequest       = new Approvalrequestobject(driver);
            instructors           = new Instructor(driver);
            approvalrequest       = new Approvalrequestobject(driver);
            DomainConsoleobj      = new DomainConsole(driver);
            ManageGradebookobj    = new ManageGradebook();
            Instructorsobj        = new Instructorspof();
            MyResponsibilitiesobj = new My_Responsibilities(driver);
            manageuserobj         = new ManageUsers(driver);
            objTrainingHome       = new TrainingHomes(driver);
            objCurriculum         = new CreateCurriculum(driver);
            classroomcourse       = new ClassroomCourse(driver);
            ContentSearchobj      = new ContentSearch(driver);
            objCreate             = new Create(driver);
            detailspage           = new Details(driver);


            TrainingHomeobj         = new TrainingHomes(driver);
            AdminstrationConsoleobj = new AdminstrationConsole(driver);
            Testsobj             = new Tests(driver);
            Detailsobj           = new Details(driver);
            EditSummaryobj       = new EditSummary(driver);
            Scorm1_2obj          = new Scorm1_2(driver);
            EditQuestionobj      = new EditQuestion(driver);
            EditQuestionGroupobj = new EditQuestionGroup(driver);

            AddUsrObj = new AddUsers(driver);

            generalcourseobj           = new GeneralCourse(driver);
            myteachingscheduleobj      = new MyTeachingSchedule();
            professionaldevelopmentobj = new ProfessionalDevelopments(driver);
            documentobj                = new Document(driver);
            CreateNewAccountobj        = new CreateNewAccount(driver);
            ManageUsersobj             = new ManageUsers(driver);
            Createobj                  = new Create(driver);
            summaryobj                 = new Summary(driver);
            reauiredtrainingconsoleobj = new RequiredTrainingConsoles(driver);
            requiredtrainingobj        = new RequiredTraining(driver);
            Trainingobj                = new Training(driver);
            Loginobj      = new Login(driver);
            Contentobj    = new Content(driver);
            Creditsobj    = new Credits(driver);
            AddContentobj = new AddContent(driver);
            Summaryobj    = new Summary(driver);
            ScheduleAndManageSectionobj = new ScheduleAndManageSection(driver);
            SearchResultsobj            = new SearchResults(driver);
            CourseSectionobj            = new CreateNewCourseSectionAndEventPage(driver);
            Transcriptsobj              = new Transcripts(driver);
            Productsobj                 = new Products(driver);
            BrowseTrainingCatalogobj    = new BrowseTrainingCatalog(driver);
            ShoppingCartsobj            = new ShoppingCarts(driver);
            ProfessionalDevelopmentsobj = new ProfessionalDevelopments(driver);
            Createnewproficencyscaleobj = new Createnewproficencyscale(driver);
            Createnewcompetencyobj      = new Createnewcompetency(driver);
            CreateNewSucessProfileobj   = new CreateNewSucessProfile(driver);
            SucessProfileobj            = new SucessProfile(driver);
            Searchobj             = new Search(driver);
            TrainingActivitiesobj = new TrainingActivities(driver);
            ProfessionalDevelopments_learnerobj = new ProfessionalDevelopments_learner(driver);
            Organizationobj             = new Organization(driver);
            DevelopmentPlansobj         = new DevelopmentPlans(driver);
            AddDevelopmentActivitiesobj = new AddDevelopmentActivities(driver);
            MyAccountobj            = new MyAccount(driver);
            UsersUtilobj            = new UsersUtil(driver);
            MyCalendersobj          = new MyCalenders(driver);
            MyReportsobj            = new MyReports(driver);
            Config_Reportsobj       = new Config_Reports(driver);
            ConfigurationConsoleobj = new ConfigurationConsole(driver);
            ApprovalPathobj         = new ApprovalPath(driver);
            MyMessageobj            = new MyMessages(driver);
            MessageUtilobj          = new MessageUtil(driver);
            MyRequestsobj           = new MyRequests(driver);
            Blogsobj = new Blogs(driver);
            CollabarationSpacesobj = new CollabarationSpaces(driver);
            Faqsobj                     = new Faqs(driver);
            HomePageFeedobj             = new HomePageFeed(driver);
            ProductTypesobj             = new ProductTypes(driver);
            Surveysobj                  = new Surveys(driver);
            SurveyScalesobj             = new SurveyScales(driver);
            AuditingConsolesobj         = new AuditingConsoles(driver);
            Categoryobj                 = new Category(driver);
            Trainingsobj                = new Trainings(driver);
            VirtualMeetingsobj          = new VirtualMeetings(driver);
            CreditTypeobj               = new CreditType(driver);
            AssignedUserobj             = new AssignedUser(driver);
            AddUsersobj                 = new AddUsers(driver);
            CustomFieldobj              = new CustomField(driver);
            CreateNewCustomFieldobj     = new CreateNewCustomField(driver);
            EditFieldobj                = new EditField(driver);
            EducationLevelobj           = new EducationLevel(driver);
            EditOrganizationobj         = new EditOrganization(driver);
            SelectManagerobj            = new SelectManager(driver);
            Roleobj                     = new Role(driver);
            SelectTrainingPOCobj        = new SelectTrainingPOC(driver);
            Complexobj                  = new Complex(driver);
            AccountCodesobj             = new AccountCodes(driver);
            AccountCodeTypesobj         = new AccountCodeTypes(driver);
            DiscountCodesobj            = new DiscountCodes(driver);
            ManageTaxRatesobj           = new ManageTaxRates(driver);
            TaxItemCategoriesobj        = new TaxItemCategories(driver);
            Certificatesobj             = new Certificates(driver);
            CourseProvidersobj          = new CourseProviders(driver);
            ExternalLearningsobj        = new ExternalLearnings(driver);
            ExternalLearningConsolesobj = new ExternalLearningConsoles(driver);
            ExternalLearningtypesobj    = new ExternalLearningtypes(driver);
            RequiredTrainingConsolesobj = new RequiredTrainingConsoles(driver);
            SelectProfileobj            = new SelectProfile(driver);
            TrainingProfilesobj         = new TrainingProfiles(driver);
            EditTrainingProfileobj      = new EditTrainingProfile(driver);
            MergeUsersobj               = new MergeUsers(driver);
            UserGroupobj                = new UserGroup(driver);
            SelectCertificateobj        = new SelectCertificate(driver);
            ManageProficencyScaleobj    = new ManageProficencyScale(driver);
            ArchivedProficencyScaleobj  = new ArchivedProficencyScale(driver);
            MappedContentobj            = new MappedContent(driver);
            MappedCompetencyobj         = new MappedCompetency(driver);
            ManageSuccessProfileobj     = new ManageSuccessProfile(driver);
            FAQ_lobj                    = new FAQ_l(driver);
            Announcements_lobj          = new Announcements_l(driver);
            JobTitlesobj                = new JobTitles(driver);
            ManageJobTitleobj           = new ManageJobTitle(driver);
            ManagePricingScheduleobj    = new ManagePricingSchedule(driver);
            ExternalLearningSearchobj   = new ExternalLearningSearch(driver);
            urlobj              = new url(driver);
            skinobj             = new skin(driver);
            MyOwnLearningobj    = new MyOwnLearningUtils(driver);
            CurrentTrainingsobj = new CurrentTrainings(driver);
            scormobj            = new Scorm12(driver);
            aicccourse          = new AICC(driver);
            ojtcourse           = new OJT(driver);
            TrainingCatalogobj  = new TrainingCatalogUtil(driver);
            accesskeys          = new AccessKeys(driver);
            #endregion
        }
示例#19
0
 protected abstract void Validate(AccessKeys accessKeys);
示例#20
0
 /// <summary>
 ///
 /// </summary>
 /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="accessKeys"></param>
 /// <returns></returns>
 public void Invalidate(AccessKeys accessKeys)
 {
     InvalidateWithHttpInfo(accessKeys);
 }
        private static Mock <IKeyVaultAuthentication> CreateStubKeyVaultAuthentication(string vaultUrl, string secretName, AccessKeys keys)
        {
            var stubKeyVaultClient = new Mock <IKeyVaultClient>();

            stubKeyVaultClient.Setup(c => c.SetSecretWithHttpMessagesAsync(
                                         vaultUrl, secretName, It.Is <string>(value => value == keys.PrimaryConnectionString || value == keys.SecondaryConnectionString), null, null, null, null, default))
            .ReturnsAsync(new AzureOperationResponse <SecretBundle>());

            var stubKeyVaultAuthentication = new Mock <IKeyVaultAuthentication>();

            stubKeyVaultAuthentication.Setup(a => a.AuthenticateAsync())
            .ReturnsAsync(stubKeyVaultClient.Object);

            return(stubKeyVaultAuthentication);
        }
示例#22
0
 /// <summary>
 ///
 /// </summary>
 /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="accessKeys"></param>
 /// <returns></returns>
 public void Validate(AccessKeys accessKeys)
 {
     ValidateWithHttpInfo(accessKeys);
 }
示例#23
0
        public async Task CreateGetUpdateDeleteDisasterRecovery()
        {
            IgnoreTestInLiveMode();
            _resourceGroup = await CreateResourceGroupAsync();

            //create namespace1
            string namespaceName1 = await CreateValidNamespaceName("testnamespacemgmt");

            ServiceBusNamespaceCollection namespaceCollection = _resourceGroup.GetServiceBusNamespaces();
            ServiceBusNamespaceData       parameters1         = new ServiceBusNamespaceData(DefaultLocation)
            {
                Sku = new Models.Sku(SkuName.Premium)
                {
                    Tier     = SkuTier.Premium,
                    Capacity = 1
                }
            };
            ServiceBusNamespace serviceBusNamespace1 = (await namespaceCollection.CreateOrUpdateAsync(true, namespaceName1, parameters1)).Value;

            //create namespace2 with a different location
            string namespaceName2 = await CreateValidNamespaceName("testnamespacemgmt");

            ServiceBusNamespaceData parameters2 = new ServiceBusNamespaceData(AzureLocation.EastUS)
            {
                Sku = new Models.Sku(SkuName.Premium)
                {
                    Tier     = SkuTier.Premium,
                    Capacity = 1
                }
            };
            ServiceBusNamespace serviceBusNamespace2 = (await namespaceCollection.CreateOrUpdateAsync(true, namespaceName2, parameters2)).Value;

            //create authorization rule on namespace1
            string ruleName = Recording.GenerateAssetName("authorizationrule");
            ServiceBusAuthorizationRuleData ruleParameter = new ServiceBusAuthorizationRuleData()
            {
                Rights = { AccessRights.Listen, AccessRights.Send }
            };
            NamespaceAuthorizationRule authorizationRule = (await serviceBusNamespace1.GetNamespaceAuthorizationRules().CreateOrUpdateAsync(true, ruleName, ruleParameter)).Value;

            Assert.NotNull(authorizationRule);
            Assert.AreEqual(authorizationRule.Data.Rights.Count, ruleParameter.Rights.Count);

            //create a disaster recovery
            string disasterRecoveryName    = Recording.GenerateAssetName("disasterrecovery");
            DisasterRecoveryData parameter = new DisasterRecoveryData()
            {
                PartnerNamespace = serviceBusNamespace2.Id
            };
            DisasterRecovery disasterRecovery = (await serviceBusNamespace1.GetDisasterRecoveries().CreateOrUpdateAsync(true, disasterRecoveryName, parameter)).Value;

            Assert.NotNull(disasterRecovery);
            Assert.AreEqual(disasterRecovery.Id.Name, disasterRecoveryName);
            Assert.AreEqual(disasterRecovery.Data.PartnerNamespace, serviceBusNamespace2.Id.ToString());

            //get the disaster recovery - primary
            disasterRecovery = await serviceBusNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);

            Assert.AreEqual(disasterRecovery.Data.Role, RoleDisasterRecovery.Primary);

            //get the disaster recovery - secondary
            DisasterRecovery disasterRecoverySec = await serviceBusNamespace2.GetDisasterRecoveries().GetAsync(disasterRecoveryName);

            Assert.AreEqual(disasterRecoverySec.Data.Role, RoleDisasterRecovery.Secondary);

            //wait for completion, this may take several minutes in live and record mode
            disasterRecovery = await serviceBusNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);

            int i = 0;

            while (disasterRecovery.Data.ProvisioningState != ProvisioningStateDisasterRecovery.Succeeded && i < 100)
            {
                if (Mode != RecordedTestMode.Playback)
                {
                    await Task.Delay(5000);
                }
                i++;
                disasterRecovery = await serviceBusNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);
            }

            //check name availability
            CheckNameAvailabilityResult nameAvailability = await serviceBusNamespace1.CheckDisasterRecoveryNameAvailabilityAsync(new CheckNameAvailability(disasterRecoveryName));

            Assert.IsFalse(nameAvailability.NameAvailable);

            List <NamespaceDisasterRecoveryAuthorizationRule> rules = await disasterRecovery.GetNamespaceDisasterRecoveryAuthorizationRules().GetAllAsync().ToEnumerableAsync();

            Assert.IsTrue(rules.Count > 0);

            //get access keys of the authorization rule
            NamespaceDisasterRecoveryAuthorizationRule rule = rules.First();
            AccessKeys keys = await rule.GetKeysAsync();

            Assert.NotNull(keys);

            //break pairing and wait for competion
            await disasterRecovery.BreakPairingAsync();

            disasterRecovery = await serviceBusNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);

            i = 0;
            while (disasterRecovery.Data.ProvisioningState != ProvisioningStateDisasterRecovery.Succeeded && i < 100)
            {
                if (Mode != RecordedTestMode.Playback)
                {
                    await Task.Delay(5000);
                }
                i++;
                disasterRecovery = await serviceBusNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);
            }

            //get all disaster recoveries for a name space
            List <DisasterRecovery> disasterRcoveries = await serviceBusNamespace1.GetDisasterRecoveries().GetAllAsync().ToEnumerableAsync();

            Assert.IsTrue(disasterRcoveries.Count >= 1);

            //delete disaster recovery;
            await disasterRecovery.DeleteAsync(true);
        }
示例#24
0
 /// <summary>
 /// Get the owner's access key
 /// </summary>
 /// <returns></returns>
 public AccessKey GetOwnerWorkspaceAccessKey()
 => AccessKeys.FirstOrDefault(x => x.HasPermissionFlags(WorkspaceAccessPermissions.Owner));
示例#25
0
 /// <summary>
 ///
 /// </summary>
 /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception>
 /// <param name="accessKeys"></param>
 /// <returns>Task of void</returns>
 public async System.Threading.Tasks.Task ValidateAsync(AccessKeys accessKeys)
 {
     await ValidateAsyncWithHttpInfo(accessKeys);
 }
示例#26
0
 /// <summary>
 /// Determine if an access key has access to this workspace
 /// </summary>
 /// <param name="accessKey"></param>
 /// <returns></returns>
 public bool HasAccess(string accessKey)
 => AccessKeys.Any(x => x.AccountName == accessKey);
        public async Task CreateGetUpdateDeleteDisasterRecovery()
        {
            _resourceGroup = await CreateResourceGroupAsync();

            //create namespace1
            string namespaceName1 = await CreateValidNamespaceName("testnamespacemgmt");

            EventHubNamespaceCollection namespaceCollection = _resourceGroup.GetEventHubNamespaces();
            EventHubNamespaceResource   eHNamespace1        = (await namespaceCollection.CreateOrUpdateAsync(WaitUntil.Completed, namespaceName1, new EventHubNamespaceData(DefaultLocation))).Value;

            //create namespace2 with a different location
            string namespaceName2 = await CreateValidNamespaceName("testnamespacemgmt");

            EventHubNamespaceResource eHNamespace2 = (await namespaceCollection.CreateOrUpdateAsync(WaitUntil.Completed, namespaceName2, new EventHubNamespaceData(AzureLocation.EastUS))).Value;

            //create authorization rule on namespace1
            string ruleName = Recording.GenerateAssetName("authorizationrule");
            AuthorizationRuleData ruleParameter = new AuthorizationRuleData()
            {
                Rights = { AccessRights.Listen, AccessRights.Send }
            };
            NamespaceAuthorizationRuleResource authorizationRule = (await eHNamespace1.GetNamespaceAuthorizationRules().CreateOrUpdateAsync(WaitUntil.Completed, ruleName, ruleParameter)).Value;

            Assert.NotNull(authorizationRule);
            Assert.AreEqual(authorizationRule.Data.Rights.Count, ruleParameter.Rights.Count);

            //create a disaster recovery
            string disasterRecoveryName    = Recording.GenerateAssetName("disasterrecovery");
            DisasterRecoveryData parameter = new DisasterRecoveryData()
            {
                PartnerNamespace = eHNamespace2.Id
            };
            DisasterRecoveryResource armDisasterRecovery = (await eHNamespace1.GetDisasterRecoveries().CreateOrUpdateAsync(WaitUntil.Completed, disasterRecoveryName, parameter)).Value;

            Assert.NotNull(armDisasterRecovery);
            Assert.AreEqual(armDisasterRecovery.Id.Name, disasterRecoveryName);
            Assert.AreEqual(armDisasterRecovery.Data.PartnerNamespace, eHNamespace2.Id.ToString());

            //get the disaster recovery - primary
            armDisasterRecovery = await eHNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);

            Assert.AreEqual(armDisasterRecovery.Data.Role, RoleDisasterRecovery.Primary);

            //get the disaster recovery - secondary
            DisasterRecoveryResource armDisasterRecoverySec = await eHNamespace2.GetDisasterRecoveries().GetAsync(disasterRecoveryName);

            Assert.AreEqual(armDisasterRecoverySec.Data.Role, RoleDisasterRecovery.Secondary);

            //wait for completion, this may take several minutes in live and record mode
            armDisasterRecovery = await eHNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);

            int i = 0;

            while (armDisasterRecovery.Data.ProvisioningState != ProvisioningStateDisasterRecovery.Succeeded && i < 100)
            {
                if (Mode != RecordedTestMode.Playback)
                {
                    await Task.Delay(5000);
                }
                i++;
                armDisasterRecovery = await eHNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);
            }
            System.Console.WriteLine(i);

            //check name availability
            CheckNameAvailabilityResult nameAvailability = await eHNamespace1.CheckDisasterRecoveryNameAvailabilityAsync(new CheckNameAvailabilityOptions(disasterRecoveryName));

            Assert.IsFalse(nameAvailability.NameAvailable);

            List <DisasterRecoveryAuthorizationRuleResource> rules = await armDisasterRecovery.GetDisasterRecoveryAuthorizationRules().GetAllAsync().ToEnumerableAsync();

            Assert.IsTrue(rules.Count > 0);

            //get access keys of the authorization rule
            DisasterRecoveryAuthorizationRuleResource rule = rules.First();
            AccessKeys keys = await rule.GetKeysAsync();

            Assert.NotNull(keys);

            //break pairing and wait for completion
            await armDisasterRecovery.BreakPairingAsync();

            armDisasterRecovery = await eHNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);

            i = 0;
            while (armDisasterRecovery.Data.ProvisioningState != ProvisioningStateDisasterRecovery.Succeeded && i < 100)
            {
                if (Mode != RecordedTestMode.Playback)
                {
                    await Task.Delay(5000);
                }
                i++;
                armDisasterRecovery = await eHNamespace1.GetDisasterRecoveries().GetAsync(disasterRecoveryName);
            }

            //get all disaster recoveries for a name space
            List <DisasterRecoveryResource> disasterRcoveries = await eHNamespace1.GetDisasterRecoveries().GetAllAsync().ToEnumerableAsync();

            Assert.IsTrue(disasterRcoveries.Count >= 1);

            //delete disaster recovery;
            await armDisasterRecovery.DeleteAsync(WaitUntil.Completed);
        }
示例#28
0
        public async Task <DomainSharedAccessKeys> RenewDomainKey(string credentialsAzureSubscriptionId, string credentialsTenantId, string credentialsClientId,
                                                                  string credentialsClientSecret, string domainName, string resourceGroupName, AccessKeys key)
        {
            try
            {
                //Management SDKs (Microsoft.Azure.Management.EventGrid)
                EventGridManagementClient managementClient = new EventGridManagementClient(credentials: new CustomLoginCredentials(credentialsTenantId, credentialsClientId, credentialsClientSecret));
                managementClient.SubscriptionId = credentialsAzureSubscriptionId;
                DomainSharedAccessKeys domainKeys = await managementClient.Domains.RegenerateKeyAsync(
                    resourceGroupName : resourceGroupName,
                    domainName : domainName,
                    keyName : key == AccessKeys.key1? "key1" : "key2");

                return(domainKeys);
            }
            catch (Exception ex)
            {
                _logger?.LogError($"Unknown Exception. Type: {ex.GetType().ToString()} ; Message: {ex.Message} ; Details: {ex.ToString()}");
                return(null);
            }
        }
示例#29
0
 public virtual void Validate(NancyContext context, AccessKeys accessKeys)
 {
     Validate(accessKeys);
 }
示例#30
0
        /// <summary>
        /// 验证访问授权是否合法
        /// </summary>
        /// <param name="key"></param>
        /// <param name="secert"></param>
        public static bool Vaild(string key, string secert)
        {
            var ret = AccessKeys.Any(a => a.AccessKeyId == key && a.AccessKeySecret == secert);

            return(ret);
        }