/**********************************************************************************
         * Upload CA for proof of possession
         *********************************************************************************/
        public async Task <bool> AddDpsGroupEnrollment(string certPath)
        {
            try
            {
                var             certificate     = new X509Certificate2(certPath);
                Attestation     attestation     = X509Attestation.CreateFromRootCertificates(certificate);
                EnrollmentGroup enrollmentGroup =
                    new EnrollmentGroup(
                        "Test",
                        attestation)
                {
                    ProvisioningStatus = ProvisioningStatus.Enabled
                };

                EnrollmentGroup enrollmentGroupResult =
                    await _provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

                return(true);
            }
            catch (Exception e)
            {
                _logger.LogError($"Exception in DeleteDpsEnrollment() : {e.Message}");
            }
            return(false);
        }
Ejemplo n.º 2
0
        public async Task DisableEnrollmentGroupAsync(string enrollmentGroupId)
        {
            var groupEnrollment = await _provisioningServiceClient.GetEnrollmentGroupAsync(enrollmentGroupId);

            if (groupEnrollment.ProvisioningStatus.Value != ProvisioningStatus.Disabled)
            {
                groupEnrollment.ProvisioningStatus = ProvisioningStatus.Disabled;
                var update = await _provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(groupEnrollment);
            }
        }
        public static async Task<EnrollmentGroup> CreateEnrollmentGroup(ProvisioningServiceClient provisioningServiceClient, AttestationMechanismType attestationType, string groupId, ReprovisionPolicy reprovisionPolicy, AllocationPolicy allocationPolicy, CustomAllocationDefinition customAllocationDefinition, ICollection<string> iothubs, DeviceCapabilities capabilities)
        {
            Attestation attestation;
            switch (attestationType)
            {
                case AttestationMechanismType.Tpm:
                    throw new NotSupportedException("Group enrollments do not support tpm attestation");
                case AttestationMechanismType.SymmetricKey:
                    string primaryKey = CryptoKeyGenerator.GenerateKey(32);
                    string secondaryKey = CryptoKeyGenerator.GenerateKey(32);
                    attestation = new SymmetricKeyAttestation(primaryKey, secondaryKey);
                    break;

                case AttestationMechanismType.X509:
                default:
                    throw new NotSupportedException("Test code has not been written for testing this attestation type yet");
            }

            var enrollmentGroup = new EnrollmentGroup(groupId, attestation)
            {
                Capabilities = capabilities,
                ReprovisionPolicy = reprovisionPolicy,
                AllocationPolicy = allocationPolicy,
                CustomAllocationDefinition = customAllocationDefinition,
                IotHubs = iothubs,
            };

            return await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);
        }
Ejemplo n.º 4
0
        public static async Task RunSample()
        {
            Console.WriteLine("Starting sample...");

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(ProvisioningConnectionString))
            {
                #region Create a new enrollmentGroup config
                Console.WriteLine("\nCreating a new enrollmentGroup...");
                var             certificate     = new X509Certificate2(X509RootCertPath);
                Attestation     attestation     = X509Attestation.CreateFromRootCertificates(certificate);
                EnrollmentGroup enrollmentGroup =
                    new EnrollmentGroup(
                        EnrollmentGroupId,
                        attestation)
                {
                    ProvisioningStatus = ProvisioningStatus.Enabled
                };
                Console.WriteLine(enrollmentGroup);
                #endregion

                #region Create the enrollmentGroup
                Console.WriteLine("\nAdding new enrollmentGroup...");
                EnrollmentGroup enrollmentGroupResult =
                    await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

                Console.WriteLine("\nEnrollmentGroup created with success.");
                Console.WriteLine(enrollmentGroupResult);
                #endregion
            }
        }
Ejemplo n.º 5
0
        public async Task <(string primaryKey, string secondaryKey)> CreateEnrollementGroup(string enrollName)
        {
            var primaryKey   = Base64Encode(RandomString(50));
            var secondaryKey = Base64Encode(RandomString(50));

            var attestation      = new SymmetricKeyAttestation(primaryKey, secondaryKey);
            var enrollementGroup = new EnrollmentGroup(enrollName, attestation);

            var tags = new TwinCollection();

            tags["group-Enrollment"] = enrollName;

            var properties = new TwinCollection()
            {
            };

            enrollementGroup.InitialTwinState = new TwinState(tags, properties);
            enrollementGroup.IotHubs          = new List <string>();
            enrollementGroup.IotHubs.Add("CowHub.azure-devices.net");
            enrollementGroup.AllocationPolicy   = AllocationPolicy.Hashed;
            enrollementGroup.ProvisioningStatus = ProvisioningStatus.Enabled;
            enrollementGroup.ReprovisionPolicy  = new ReprovisionPolicy()
            {
                MigrateDeviceData   = true,
                UpdateHubAssignment = true
            };

            await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollementGroup);

            return(primaryKey, secondaryKey);
        }
Ejemplo n.º 6
0
        public static async Task SetGroupRegistrationDataAsync()
        {
            Console.WriteLine("Starting SetGroupRegistrationData");

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(ServiceConnectionString))
            {
                Console.WriteLine("\nCreating a new enrollmentGroup...");

                var certificate = new X509Certificate2(X509RootCertPathVar);

                Attestation attestation = X509Attestation.CreateFromRootCertificates(certificate);

                EnrollmentGroup enrollmentGroup = new EnrollmentGroup(SampleEnrollmentGroupId, attestation);

                Console.WriteLine(enrollmentGroup);
                Console.WriteLine("\nAdding new enrollmentGroup...");

                EnrollmentGroup enrollmentGroupResult =
                    await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

                Console.WriteLine("\nEnrollmentGroup created with success.");
                Console.WriteLine(enrollmentGroupResult);
            }
        }
Ejemplo n.º 7
0
        public static async Task RunSample()
        {
            Console.WriteLine("Starting sample...");

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(_provisioningConnectionString))
            {
                #region Create a new enrollmentGroup config
                Console.WriteLine("\nCreating a new enrollmentGroup...");
                string          certificatePassword = ReadCertificatePassword();
                var             certificate         = new X509Certificate2(_x509RootCertPath, certificatePassword);
                Attestation     attestation         = X509Attestation.CreateFromRootCertificates(certificate);
                EnrollmentGroup enrollmentGroup     =
                    new EnrollmentGroup(
                        _enrollmentGroupId,
                        attestation);
                Console.WriteLine(enrollmentGroup);
                #endregion

                #region Create the enrollmentGroup
                Console.WriteLine("\nAdding new enrollmentGroup...");
                EnrollmentGroup enrollmentGroupResult =
                    await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

                Console.WriteLine("\nEnrollmentGroup created with success.");
                Console.WriteLine(enrollmentGroupResult);
                #endregion

                #region Get info of enrollmentGroup
                Console.WriteLine("\nGetting the enrollmentGroup information...");
                EnrollmentGroup getResult =
                    await provisioningServiceClient.GetEnrollmentGroupAsync(SampleEnrollmentGroupId).ConfigureAwait(false);

                Console.WriteLine(getResult);
                #endregion

                #region Query info of enrollmentGroup doc
                Console.WriteLine("\nCreating a query for enrollmentGroups...");
                QuerySpecification querySpecification = new QuerySpecification("SELECT * FROM enrollmentGroups");
                using (Query query = provisioningServiceClient.CreateEnrollmentGroupQuery(querySpecification))
                {
                    while (query.HasNext())
                    {
                        Console.WriteLine("\nQuerying the next enrollmentGroups...");
                        QueryResult queryResult = await query.NextAsync().ConfigureAwait(false);

                        Console.WriteLine(queryResult);
                    }
                }
                #endregion

                #region Delete info of enrollmentGroup
                Console.WriteLine("\nDeleting the enrollmentGroup...");
                await provisioningServiceClient.DeleteEnrollmentGroupAsync(getResult).ConfigureAwait(false);

                #endregion
            }
        }
        public static async Task <EnrollmentGroup> CreateEnrollmentGroupAsync(
            ProvisioningServiceClient provisioningServiceClient,
            AttestationMechanismType attestationType,
            string groupId,
            ReprovisionPolicy reprovisionPolicy,
            AllocationPolicy allocationPolicy,
            CustomAllocationDefinition customAllocationDefinition,
            ICollection <string> iothubs,
            DeviceCapabilities capabilities,
            MsTestLogger logger)
        {
            Attestation attestation;

            switch (attestationType)
            {
            case AttestationMechanismType.Tpm:
                throw new NotSupportedException("Group enrollments do not support tpm attestation");

            case AttestationMechanismType.SymmetricKey:
                string primaryKey   = CryptoKeyGenerator.GenerateKey(32);
                string secondaryKey = CryptoKeyGenerator.GenerateKey(32);
                attestation = new SymmetricKeyAttestation(primaryKey, secondaryKey);
                break;

            case AttestationMechanismType.X509:
            default:
                throw new NotSupportedException("Test code has not been written for testing this attestation type yet");
            }

            var enrollmentGroup = new EnrollmentGroup(groupId, attestation)
            {
                Capabilities               = capabilities,
                ReprovisionPolicy          = reprovisionPolicy,
                AllocationPolicy           = allocationPolicy,
                CustomAllocationDefinition = customAllocationDefinition,
                IotHubs = iothubs,
            };

            EnrollmentGroup createdEnrollmentGroup = null;
            await RetryOperationHelper
            .RetryOperationsAsync(
                async() =>
            {
                createdEnrollmentGroup = await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);
            },
                s_provisioningServiceRetryPolicy,
                s_retryableExceptions,
                logger)
            .ConfigureAwait(false);

            if (createdEnrollmentGroup == null)
            {
                throw new ArgumentException($"The enrollment entry with group Id {groupId} could not be created, exiting test.");
            }

            return(createdEnrollmentGroup);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Update the enrollment under test such that it forces it to reprovision to the hubs within <paramref name="iotHubsToReprovisionTo"/>
        /// </summary>
        private async Task UpdateEnrollmentToForceReprovision(EnrollmentType?enrollmentType, ProvisioningServiceClient provisioningServiceClient, ICollection <String> iotHubsToReprovisionTo, SecurityProvider security, string groupId)
        {
            if (enrollmentType == EnrollmentType.Individual)
            {
                IndividualEnrollment individualEnrollment = await provisioningServiceClient.GetIndividualEnrollmentAsync(security.GetRegistrationID()).ConfigureAwait(false);

                individualEnrollment.IotHubs = iotHubsToReprovisionTo;
                IndividualEnrollment individualEnrollmentResult = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);
            }
            else
            {
                EnrollmentGroup enrollmentGroup = await provisioningServiceClient.GetEnrollmentGroupAsync(groupId).ConfigureAwait(false);

                enrollmentGroup.IotHubs = iotHubsToReprovisionTo;
                EnrollmentGroup enrollmentGroupResult = await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);
            }
        }
        public async Task CreateEnrollmentGroupAsync()
        {
            Console.WriteLine("\nCreating a new enrollmentGroup...");
            Attestation     attestation     = X509Attestation.CreateFromRootCertificates(_groupIssuerCertificate);
            EnrollmentGroup enrollmentGroup =
                new EnrollmentGroup(
                    EnrollmentGroupId,
                    attestation);

            Console.WriteLine(enrollmentGroup);

            Console.WriteLine("\nAdding new enrollmentGroup...");
            EnrollmentGroup enrollmentGroupResult =
                await _provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

            Console.WriteLine("\nEnrollmentGroup created with success.");
            Console.WriteLine(enrollmentGroupResult);
        }
Ejemplo n.º 11
0
        private async Task <EnrollmentGroup> CreateEnrollmentGroupAsync(Attestation attestation)
        {
            EnrollmentGroup enrollmentGroupResult = null;

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(
                           this.DPSConnStr))
            {
                EnrollmentGroup enrollmentGroup = new EnrollmentGroup(
                    this.DPSEnrollmentGroup,
                    attestation);
                enrollmentGroup.ProvisioningStatus = ProvisioningStatus.Enabled;

                // Create the enrollmentGroup
                enrollmentGroupResult =
                    await provisioningServiceClient
                    .CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup)
                    .ConfigureAwait(false);
            }

            return(enrollmentGroupResult);
        }
Ejemplo n.º 12
0
        public async Task CreateDpsEnrollmentGroupAsync(
            string enrollmentGroupId,
            X509Certificate2 pemCertificate)
        {
            _logger.LogInformation("Starting CreateDpsEnrollmentGroupAsync...");
            _logger.LogInformation("Creating a new enrollmentGroup...");

            Attestation     attestation     = X509Attestation.CreateFromRootCertificates(pemCertificate);
            EnrollmentGroup enrollmentGroup = new EnrollmentGroup(enrollmentGroupId, attestation)
            {
                ProvisioningStatus = ProvisioningStatus.Enabled,
                ReprovisionPolicy  = new ReprovisionPolicy
                {
                    MigrateDeviceData   = false,
                    UpdateHubAssignment = true
                },
                Capabilities = new DeviceCapabilities
                {
                    IotEdge = false
                },
                InitialTwinState = new TwinState(
                    new TwinCollection("{ \"updatedby\":\"" + "damien" + "\", \"timeZone\":\"" + TimeZoneInfo.Local.DisplayName + "\" }"),
                    new TwinCollection("{ }")
                    )
            };

            _logger.LogInformation($"{enrollmentGroup}");
            _logger.LogInformation($"Adding new enrollmentGroup...");

            EnrollmentGroup enrollmentGroupResult = await _provisioningServiceClient
                                                    .CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup)
                                                    .ConfigureAwait(false);

            _logger.LogInformation($"EnrollmentGroup created with success.");
            _logger.LogInformation($"{enrollmentGroupResult}");
        }
Ejemplo n.º 13
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.DpsName, DPSResources.AddEnrollmentGroup))
            {
                ProvisioningServiceDescription provisioningServiceDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName         = this.DpsObject.ResourceGroupName;
                    this.DpsName                   = this.DpsObject.Name;
                    provisioningServiceDescription = IotDpsUtils.ConvertObject <PSProvisioningServiceDescription, ProvisioningServiceDescription>(this.DpsObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotDpsUtils.GetResourceGroupName(this.ResourceId);
                        this.DpsName           = IotDpsUtils.GetIotDpsName(this.ResourceId);
                    }

                    provisioningServiceDescription = GetIotDpsResource(this.ResourceGroupName, this.DpsName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRuleAccessRightsDescription> authPolicies = this.IotDpsClient.IotDpsResource.ListKeys(this.DpsName, this.ResourceGroupName);
                SharedAccessSignatureAuthorizationRuleAccessRightsDescription policy = IotDpsUtils.GetPolicy(authPolicies, PSAccessRightsDescription.EnrollmentWrite);
                PSIotDpsConnectionString  psIotDpsConnectionString = IotDpsUtils.ToPSIotDpsConnectionString(policy, provisioningServiceDescription.Properties.ServiceOperationsHostName);
                ProvisioningServiceClient client = ProvisioningServiceClient.CreateFromConnectionString(psIotDpsConnectionString.PrimaryConnectionString);

                Attestation    attestation = null;
                TwinCollection tags = new TwinCollection(), desiredProperties = new TwinCollection();

                if (this.IsParameterBound(c => c.Tag))
                {
                    tags = new TwinCollection(JsonConvert.SerializeObject(this.Tag));
                }

                if (this.IsParameterBound(c => c.Desired))
                {
                    desiredProperties = new TwinCollection(JsonConvert.SerializeObject(this.Desired));
                }

                switch (this.AttestationType)
                {
                case PSAttestationMechanismType.SymmetricKey:
                    if ((this.IsParameterBound(c => c.PrimaryKey) && !this.IsParameterBound(c => c.SecondaryKey)) ||
                        (!this.IsParameterBound(c => c.PrimaryKey) && this.IsParameterBound(c => c.SecondaryKey)))
                    {
                        throw new ArgumentException("Please provide both primary and secondary key.");
                    }
                    else
                    {
                        attestation = new SymmetricKeyAttestation(this.PrimaryKey, this.SecondaryKey);
                    }
                    break;

                case PSAttestationMechanismType.Tpm:
                    throw new ArgumentException("\"TPM\" is not a valid attestation mechanism for an enrollment group.");

                case PSAttestationMechanismType.X509:
                    if (!this.IsParameterBound(c => c.PrimaryCertificate) &&
                        !this.IsParameterBound(c => c.SecondaryCertificate) &&
                        (this.IsParameterBound(c => c.PrimaryCAName) || this.IsParameterBound(c => c.SecondaryCAName)))
                    {
                        if (!this.IsParameterBound(c => c.PrimaryCAName))
                        {
                            throw new ArgumentException("Primary CA reference cannot be null or empty.");
                        }

                        if (this.IsParameterBound(c => c.SecondaryCAName))
                        {
                            attestation = X509Attestation.CreateFromCAReferences(this.PrimaryCAName, this.SecondaryCAName);
                        }
                        else
                        {
                            attestation = X509Attestation.CreateFromCAReferences(this.PrimaryCAName);
                        }
                    }
                    else if (!this.IsParameterBound(c => c.PrimaryCAName) &&
                             !this.IsParameterBound(c => c.SecondaryCAName) &&
                             (this.IsParameterBound(c => c.PrimaryCertificate) || this.IsParameterBound(c => c.SecondaryCertificate)))
                    {
                        string primaryCer = string.Empty, secondaryCer = string.Empty;

                        if (!this.IsParameterBound(c => c.PrimaryCertificate))
                        {
                            throw new ArgumentException("Primary certificate cannot be null or empty.");
                        }

                        primaryCer = IotDpsUtils.GetCertificateString(this.PrimaryCertificate);

                        if (this.IsParameterBound(c => c.SecondaryCertificate))
                        {
                            secondaryCer = IotDpsUtils.GetCertificateString(this.SecondaryCertificate);

                            if (this.IsParameterBound(c => c.RootCertificate))
                            {
                                attestation = X509Attestation.CreateFromRootCertificates(primaryCer, secondaryCer);
                            }
                            else
                            {
                                attestation = X509Attestation.CreateFromClientCertificates(primaryCer, secondaryCer);
                            }
                        }
                        else
                        {
                            if (this.IsParameterBound(c => c.RootCertificate))
                            {
                                attestation = X509Attestation.CreateFromRootCertificates(primaryCer);
                            }
                            else
                            {
                                attestation = X509Attestation.CreateFromClientCertificates(primaryCer);
                            }
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Please provide either CA reference or X509 certificate.");
                    }
                    break;

                default:
                    throw new ArgumentException("Please provide valid attestation mechanism.");
                }

                EnrollmentGroup enrollment = new EnrollmentGroup(this.Name, attestation);

                enrollment.InitialTwinState = new TwinState(tags, desiredProperties);
                enrollment.Capabilities     = new DeviceCapabilities()
                {
                    IotEdge = this.EdgeEnabled.IsPresent
                };

                switch (this.ReprovisionPolicy)
                {
                case PSReprovisionType.reprovisionandmigratedata:
                    enrollment.ReprovisionPolicy = new ReprovisionPolicy()
                    {
                        UpdateHubAssignment = true, MigrateDeviceData = true
                    };
                    break;

                case PSReprovisionType.reprovisionandresetdata:
                    enrollment.ReprovisionPolicy = new ReprovisionPolicy()
                    {
                        UpdateHubAssignment = true, MigrateDeviceData = false
                    };
                    break;

                case PSReprovisionType.never:
                    enrollment.ReprovisionPolicy = new ReprovisionPolicy()
                    {
                        UpdateHubAssignment = false, MigrateDeviceData = false
                    };
                    break;
                }

                if (this.IsParameterBound(c => c.AllocationPolicy))
                {
                    if (this.IsParameterBound(c => c.IotHubHostName))
                    {
                        throw new ArgumentException("\"IotHubHostName\" is not required when allocation-policy is defined.");
                    }

                    if (this.AllocationPolicy.Equals(PSAllocationPolicy.Static))
                    {
                        if (this.IsParameterBound(c => c.IotHub))
                        {
                            if (this.IotHub.Length > 1)
                            {
                                throw new ArgumentException("Please provide only one hub when allocation-policy is defined as Static.");
                            }
                        }
                        else
                        {
                            throw new ArgumentException("Please provide a hub to be assigned with device.");
                        }
                    }

                    if (this.AllocationPolicy.Equals(PSAllocationPolicy.Custom))
                    {
                        if (!this.IsParameterBound(c => c.WebhookUrl))
                        {
                            throw new ArgumentException("Please provide an Azure function url when allocation-policy is defined as Custom.");
                        }

                        if (!this.IsParameterBound(c => c.ApiVersion))
                        {
                            throw new ArgumentException("Please provide an Azure function api-version when allocation-policy is defined as Custom.");
                        }

                        enrollment.CustomAllocationDefinition = new CustomAllocationDefinition()
                        {
                            WebhookUrl = this.WebhookUrl, ApiVersion = this.ApiVersion
                        };
                    }

                    enrollment.AllocationPolicy = (Devices.Provisioning.Service.AllocationPolicy)Enum.Parse(typeof(Devices.Provisioning.Service.AllocationPolicy), this.AllocationPolicy.ToString());
                    enrollment.IotHubs          = this.IotHub;
                }
                else
                {
                    if (this.IsParameterBound(c => c.IotHub))
                    {
                        throw new ArgumentException("Please provide allocation policy.");
                    }

                    if (this.IsParameterBound(c => c.IotHubHostName))
                    {
                        enrollment.IotHubHostName = this.IotHubHostName;
                    }
                }

                if (this.IsParameterBound(c => c.ProvisioningStatus))
                {
                    enrollment.ProvisioningStatus = (ProvisioningStatus)Enum.Parse(typeof(ProvisioningStatus), this.ProvisioningStatus.ToString());
                }

                EnrollmentGroup result = client.CreateOrUpdateEnrollmentGroupAsync(enrollment).GetAwaiter().GetResult();
                this.WriteObject(IotDpsUtils.ToPSEnrollmentGroup(result));
            }
        }
Ejemplo n.º 14
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.DpsName, DPSResources.AddEnrollmentGroup))
            {
                ProvisioningServiceDescription provisioningServiceDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName         = this.DpsObject.ResourceGroupName;
                    this.DpsName                   = this.DpsObject.Name;
                    provisioningServiceDescription = IotDpsUtils.ConvertObject <PSProvisioningServiceDescription, ProvisioningServiceDescription>(this.DpsObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotDpsUtils.GetResourceGroupName(this.ResourceId);
                        this.DpsName           = IotDpsUtils.GetIotDpsName(this.ResourceId);
                    }

                    provisioningServiceDescription = GetIotDpsResource(this.ResourceGroupName, this.DpsName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRuleAccessRightsDescription> authPolicies = this.IotDpsClient.IotDpsResource.ListKeys(this.DpsName, this.ResourceGroupName);
                SharedAccessSignatureAuthorizationRuleAccessRightsDescription policy = IotDpsUtils.GetPolicy(authPolicies, PSAccessRightsDescription.EnrollmentWrite);
                PSIotDpsConnectionString  psIotDpsConnectionString = IotDpsUtils.ToPSIotDpsConnectionString(policy, provisioningServiceDescription.Properties.ServiceOperationsHostName);
                ProvisioningServiceClient client = ProvisioningServiceClient.CreateFromConnectionString(psIotDpsConnectionString.PrimaryConnectionString);

                EnrollmentGroup enrollment = client.GetEnrollmentGroupAsync(this.Name).GetAwaiter().GetResult();

                if (enrollment != null)
                {
                    // Updating ProvisioningStatus

                    if (this.IsParameterBound(c => c.ProvisioningStatus))
                    {
                        enrollment.ProvisioningStatus = (ProvisioningStatus)Enum.Parse(typeof(ProvisioningStatus), this.ProvisioningStatus.ToString());
                    }

                    // Updating InitialTwinState

                    if (this.IsParameterBound(c => c.Tag) || this.IsParameterBound(c => c.Desired))
                    {
                        TwinCollection tags = this.IsParameterBound(c => c.Tag) ? new TwinCollection(JsonConvert.SerializeObject(this.Tag)) : (enrollment.InitialTwinState != null ? enrollment.InitialTwinState.Tags : new TwinCollection());
                        TwinCollection desiredProperties = this.IsParameterBound(c => c.Desired) ? new TwinCollection(JsonConvert.SerializeObject(this.Desired)) : (enrollment.InitialTwinState != null ? enrollment.InitialTwinState.DesiredProperties : new TwinCollection());
                        enrollment.InitialTwinState = new TwinState(tags, desiredProperties);
                    }

                    // Updating Capabilities

                    if (this.IsParameterBound(c => c.EdgeEnabled))
                    {
                        enrollment.Capabilities = new DeviceCapabilities()
                        {
                            IotEdge = this.EdgeEnabled
                        };
                    }

                    // Updating ReprovisionPolicy

                    if (this.IsParameterBound(c => c.ReprovisionPolicy))
                    {
                        switch (this.ReprovisionPolicy)
                        {
                        case PSReprovisionType.reprovisionandmigratedata:
                            enrollment.ReprovisionPolicy = new ReprovisionPolicy()
                            {
                                UpdateHubAssignment = true, MigrateDeviceData = true
                            };
                            break;

                        case PSReprovisionType.reprovisionandresetdata:
                            enrollment.ReprovisionPolicy = new ReprovisionPolicy()
                            {
                                UpdateHubAssignment = true, MigrateDeviceData = false
                            };
                            break;

                        case PSReprovisionType.never:
                            enrollment.ReprovisionPolicy = new ReprovisionPolicy()
                            {
                                UpdateHubAssignment = false, MigrateDeviceData = false
                            };
                            break;
                        }
                    }

                    // Updating AllocationPolicy and Hub

                    if (this.IsParameterBound(c => c.IotHubHostName) && this.IsParameterBound(c => c.AllocationPolicy))
                    {
                        throw new ArgumentException("\"IotHubHostName\" is not required when allocation-policy is defined.");
                    }

                    if (this.IsParameterBound(c => c.IotHubHostName) && this.IsParameterBound(c => c.IotHub))
                    {
                        throw new ArgumentException("\"IotHubHostName\" is not required when IotHub is defined.");
                    }

                    if (this.IsParameterBound(c => c.IotHubHostName))
                    {
                        enrollment.IotHubHostName             = this.IotHubHostName;
                        enrollment.CustomAllocationDefinition = null;
                        enrollment.AllocationPolicy           = null;
                        enrollment.IotHubs = null;
                    }

                    if (this.IsParameterBound(c => c.AllocationPolicy))
                    {
                        enrollment.AllocationPolicy = (Devices.Provisioning.Service.AllocationPolicy)Enum.Parse(typeof(Devices.Provisioning.Service.AllocationPolicy), this.AllocationPolicy.ToString());
                    }

                    switch (enrollment.AllocationPolicy)
                    {
                    case Devices.Provisioning.Service.AllocationPolicy.Static:
                        if (this.IsParameterBound(c => c.IotHub))
                        {
                            if (this.IotHub.Length > 1)
                            {
                                throw new ArgumentException("Please provide only one hub when allocation-policy is defined as Static.");
                            }

                            enrollment.IotHubs = this.IotHub;
                        }
                        enrollment.CustomAllocationDefinition = null;
                        enrollment.IotHubHostName             = null;
                        break;

                    case Devices.Provisioning.Service.AllocationPolicy.Custom:
                        if (enrollment.CustomAllocationDefinition == null)
                        {
                            if (!this.IsParameterBound(c => c.WebhookUrl))
                            {
                                throw new ArgumentException("Please provide an Azure function url when allocation-policy is defined as Custom.");
                            }

                            if (!this.IsParameterBound(c => c.ApiVersion))
                            {
                                throw new ArgumentException("Please provide an Azure function api-version when allocation-policy is defined as Custom.");
                            }
                        }

                        string webhookUrl = string.Empty, apiVersion = string.Empty;
                        webhookUrl = this.IsParameterBound(c => c.WebhookUrl) ? this.WebhookUrl : enrollment.CustomAllocationDefinition.WebhookUrl;
                        apiVersion = this.IsParameterBound(c => c.ApiVersion) ? this.ApiVersion : enrollment.CustomAllocationDefinition.ApiVersion;

                        enrollment.CustomAllocationDefinition = new CustomAllocationDefinition()
                        {
                            WebhookUrl = webhookUrl, ApiVersion = apiVersion
                        };
                        enrollment.IotHubHostName = null;
                        if (this.IsParameterBound(c => c.IotHub))
                        {
                            enrollment.IotHubs = this.IotHub;
                        }
                        break;

                    case Devices.Provisioning.Service.AllocationPolicy.Hashed:
                    case Devices.Provisioning.Service.AllocationPolicy.GeoLatency:
                        if (this.IsParameterBound(c => c.IotHub))
                        {
                            enrollment.IotHubs = this.IotHub;
                        }
                        enrollment.CustomAllocationDefinition = null;
                        enrollment.IotHubHostName             = null;
                        break;

                    default:
                        if (this.IsParameterBound(c => c.IotHub))
                        {
                            throw new ArgumentException("Please provide allocation policy.");
                        }
                        break;
                    }
                }
                else
                {
                    throw new ArgumentException("The enrollment doesn't exist.");
                }

                EnrollmentGroup result = client.CreateOrUpdateEnrollmentGroupAsync(enrollment).GetAwaiter().GetResult();
                this.WriteObject(IotDpsUtils.ToPSEnrollmentGroup(result));
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Update the enrollment under test such that it forces it to reprovision to the hubs within <paramref name="iotHubsToReprovisionTo"/>
        /// </summary>
        private async Task UpdateEnrollmentToForceReprovision(EnrollmentType? enrollmentType, ProvisioningServiceClient provisioningServiceClient, ICollection<String> iotHubsToReprovisionTo, SecurityProvider security, string groupId)
        {
            if (enrollmentType == EnrollmentType.Individual)
            {
                IndividualEnrollment retrievedEnrollment = null;
                await RetryOperationHelper
                            .RetryOperationsAsync(
                                async () =>
                                {
                                    retrievedEnrollment = await provisioningServiceClient.GetIndividualEnrollmentAsync(security.GetRegistrationID()).ConfigureAwait(false);
                                },
                                s_provisioningServiceRetryPolicy,
                                s_retryableExceptions,
                                Logger)
                            .ConfigureAwait(false);

                if (retrievedEnrollment == null)
                {
                    throw new ArgumentException($"The individual enrollment entry with registration Id {security.GetRegistrationID()} could not be retrieved, exiting test.");
                }

                retrievedEnrollment.IotHubs = iotHubsToReprovisionTo;
                IndividualEnrollment updatedEnrollment = null;

                await RetryOperationHelper
                            .RetryOperationsAsync(
                                async () =>
                                {
                                    updatedEnrollment = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(retrievedEnrollment).ConfigureAwait(false);
                                },
                                s_provisioningServiceRetryPolicy,
                                s_retryableExceptions,
                                Logger)
                            .ConfigureAwait(false);

                if (updatedEnrollment == null)
                {
                    throw new ArgumentException($"The individual enrollment entry with registration Id {security.GetRegistrationID()} could not be updated, exiting test.");
                }
            }
            else
            {
                EnrollmentGroup retrievedEnrollmentGroup = null;
                await RetryOperationHelper
                            .RetryOperationsAsync(
                                async () =>
                                {
                                    retrievedEnrollmentGroup = await provisioningServiceClient.GetEnrollmentGroupAsync(groupId).ConfigureAwait(false);
                                },
                                s_provisioningServiceRetryPolicy,
                                s_retryableExceptions,
                                Logger)
                            .ConfigureAwait(false);

                if (retrievedEnrollmentGroup == null)
                {
                    throw new ArgumentException($"The enrollment group entry with group Id {groupId} could not be retrieved, exiting test.");
                }

                retrievedEnrollmentGroup.IotHubs = iotHubsToReprovisionTo;
                EnrollmentGroup updatedEnrollmentGroup = null;

                await RetryOperationHelper
                            .RetryOperationsAsync(
                                async () =>
                                {
                                    updatedEnrollmentGroup = await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(retrievedEnrollmentGroup).ConfigureAwait(false);
                                },
                                s_provisioningServiceRetryPolicy,
                                s_retryableExceptions,
                                Logger)
                            .ConfigureAwait(false);

                if (updatedEnrollmentGroup == null)
                {
                    throw new ArgumentException($"The enrollment group entry with group Id {groupId} could not be updated, exiting test.");
                }
            }
        }