Esempio n. 1
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
            }
        }
        public async Task <bool> AddDpsGroupEnrollment(StringBuilder certContents)
        {
            try
            {
                byte[]          byteArray       = ASCIIEncoding.ASCII.GetBytes(certContents.ToString());
                var             certificate     = new X509Certificate2(byteArray);
                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);
        }
Esempio n. 3
0
        private static async Task CreateOrUpdateEnrollmentGroupAsync()
        {
            using (var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(dpsConnectionString))
            {
                Console.WriteLine("Connected to sample provisioning service successfully.");

                Console.WriteLine();
                // Create a new enrollmentGroup config
                Console.WriteLine("Creating 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);

                // Create the enrollmentGroup
                Console.WriteLine("Adding new enrollmentGroup...");
                EnrollmentGroup enrollmentGroupResult = await provisioningServiceClient.CreateOrUpdateEnrollmentGroupAsync(enrollmentGroup).ConfigureAwait(false);

                Console.WriteLine("EnrollmentGroup created :");
                Console.WriteLine(enrollmentGroupResult);
            }
        }
        /**********************************************************************************
         * 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);
        }
Esempio n. 5
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);
            }
        }
Esempio n. 6
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
            }
        }
Esempio n. 7
0
        public async Task CleanUpAndCreateEnrollmentGroupAsync()
        {
            Attestation attestation = X509Attestation
                                      .CreateFromRootCertificates(
                this.personalSignedX509Certificate);

            this.ready = await this.service
                         .CleanUpAndCreateEnrollmentGroupAsync(
                attestation)
                         .ConfigureAwait(false);
        }
        public void X509AttestationCreateFromRootCertificatesThrowsOnNullPrimaryCertificate()
        {
            // arrange
            X509Certificate2 primaryCert   = null;
            X509Certificate2 secondaryCert = null;
            string           primaryStr    = null;
            string           secondaryStr  = null;

            // act - assert
            TestAssert.Throws <ArgumentException>(() => X509Attestation.CreateFromRootCertificates(primaryCert));
            TestAssert.Throws <ArgumentException>(() => X509Attestation.CreateFromRootCertificates(primaryCert, secondaryCert));
            TestAssert.Throws <ArgumentException>(() => X509Attestation.CreateFromRootCertificates(primaryStr));
            TestAssert.Throws <ArgumentException>(() => X509Attestation.CreateFromRootCertificates(primaryStr, secondaryStr));
        }
        public void X509AttestationCreateFromRootCertificatesSucceedOnPrimaryString()
        {
            // arrange
            string primary = PUBLIC_KEY_CERTIFICATE_STRING;

            // act
            X509Attestation attestation = X509Attestation.CreateFromRootCertificates(primary);

            // assert
            Assert.IsNotNull(attestation.RootCertificates.Primary);
            Assert.IsNull(attestation.RootCertificates.Secondary);
            Assert.IsNull(attestation.ClientCertificates);
            Assert.IsNull(attestation.CAReferences);
        }
        public void X509AttestationCreateFromRootCertificatesSucceedOnPrimaryCertificate()
        {
            // arrange
            X509Certificate2 primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING));

            // act
            X509Attestation attestation = X509Attestation.CreateFromRootCertificates(primary);

            primary.Dispose();

            // assert
            Assert.IsNotNull(attestation.RootCertificates.Primary);
            Assert.IsNull(attestation.RootCertificates.Secondary);
            Assert.IsNull(attestation.ClientCertificates);
            Assert.IsNull(attestation.CAReferences);
        }
        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);
        }
Esempio 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}");
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.DpsName, DPSResources.AddEnrollment))
            {
                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:
                    if (this.IsParameterBound(c => c.EndorsementKey))
                    {
                        attestation = new TpmAttestation(this.EndorsementKey, this.IsParameterBound(c => c.StorageRootKey) ? this.StorageRootKey : null);
                    }
                    else
                    {
                        throw new ArgumentException("Endorsement key is requried.");
                    }
                    break;

                case PSAttestationMechanismType.X509:
                    if (!this.IsParameterBound(c => c.PrimaryCertificate) && !this.IsParameterBound(c => c.SecondaryCertificate))
                    {
                        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))
                    {
                        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.PrimaryCertificate);

                            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.");
                }

                IndividualEnrollment enrollment = new IndividualEnrollment(this.RegistrationId, attestation);

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

                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());
                }

                IndividualEnrollment result = client.CreateOrUpdateIndividualEnrollmentAsync(enrollment).GetAwaiter().GetResult();
                this.WriteObject(IotDpsUtils.ToPSIndividualEnrollment(result));
            }
        }
        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;
                    }

                    switch (enrollment.Attestation)
                    {
                    case SymmetricKeyAttestation attestation:
                        if (this.IsParameterBound(c => c.PrimaryKey) || this.IsParameterBound(c => c.SecondaryKey))
                        {
                            enrollment.Attestation = new SymmetricKeyAttestation(
                                this.IsParameterBound(c => c.PrimaryKey) ? this.PrimaryKey : attestation.PrimaryKey,
                                this.IsParameterBound(c => c.SecondaryKey) ? this.SecondaryKey : attestation.SecondaryKey
                                );
                        }
                        break;

                    case X509Attestation attestation:
                        bool updatedPrimaryCAName   = this.IsParameterBound(c => c.PrimaryCAName);
                        bool updatedSecondaryCAName = this.IsParameterBound(c => c.SecondaryCAName);

                        bool updatedPrimaryCertificate   = this.IsParameterBound(c => c.PrimaryCertificate);
                        bool updatedSecondaryCertificate = this.IsParameterBound(c => c.SecondaryCertificate);

                        if (updatedPrimaryCAName || updatedSecondaryCAName)
                        {
                            enrollment.Attestation = X509Attestation.CreateFromCAReferences(
                                updatedPrimaryCAName ? this.PrimaryCAName : attestation.CAReferences.Primary,
                                updatedSecondaryCAName ? this.SecondaryCAName : (attestation.CAReferences.Secondary ?? null)
                                );
                        }
                        else if (updatedPrimaryCertificate || updatedSecondaryCertificate)
                        {
                            string primaryCer = string.Empty, secondaryCer = string.Empty;
                            if (!updatedPrimaryCertificate)
                            {
                                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))
                                {
                                    enrollment.Attestation = X509Attestation.CreateFromRootCertificates(primaryCer, secondaryCer);
                                }
                                else
                                {
                                    enrollment.Attestation = X509Attestation.CreateFromClientCertificates(primaryCer, secondaryCer);
                                }
                            }
                            else
                            {
                                if (this.IsParameterBound(c => c.RootCertificate))
                                {
                                    enrollment.Attestation = X509Attestation.CreateFromRootCertificates(primaryCer);
                                }
                                else
                                {
                                    enrollment.Attestation = X509Attestation.CreateFromClientCertificates(primaryCer);
                                }
                            }
                        }
                        break;

                    default: break;
                    }
                }
                else
                {
                    throw new ArgumentException("The enrollment doesn't exist.");
                }

                EnrollmentGroup result = client.CreateOrUpdateEnrollmentGroupAsync(enrollment).GetAwaiter().GetResult();
                this.WriteObject(IotDpsUtils.ToPSEnrollmentGroup(result));
            }
        }