public void X509AttestationCreateFromClientCertificatesSucceedOnPrimaryString()
        {
            // arrange
            string primary = PUBLIC_KEY_CERTIFICATE_STRING;

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

            // assert
            Assert.IsNotNull(attestation.ClientCertificates.Primary);
            Assert.IsNull(attestation.ClientCertificates.Secondary);
            Assert.IsNull(attestation.RootCertificates);
            Assert.IsNull(attestation.CAReferences);
        }
        public void X509AttestationCreateFromClientCertificatesThrowsOnNullPrimaryCertificate()
        {
            // arrange
            X509Certificate2 primaryCert   = null;
            X509Certificate2 secondaryCert = null;
            string           primaryStr    = null;
            string           secondaryStr  = null;

            // act - assert
            TestAssert.Throws <ArgumentException>(() => X509Attestation.CreateFromClientCertificates(primaryCert));
            TestAssert.Throws <ArgumentException>(() => X509Attestation.CreateFromClientCertificates(primaryCert, secondaryCert));
            TestAssert.Throws <ArgumentException>(() => X509Attestation.CreateFromClientCertificates(primaryStr));
            TestAssert.Throws <ArgumentException>(() => X509Attestation.CreateFromClientCertificates(primaryStr, secondaryStr));
        }
        public async Task CreateIndividualEnrollment(
            string individualEnrollmentId,
            X509Certificate2 enrollmentCertificate)
        {
            _logger.LogInformation("Starting CreateIndividualEnrollment...");

            using (ProvisioningServiceClient provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(
                           Configuration.GetConnectionString("DpsConnection")))
            {
                _logger.LogInformation("Creating a new individualEnrollment...");

                Attestation attestation = X509Attestation.CreateFromClientCertificates(enrollmentCertificate);
                //IndividualEnrollment individualEnrollment =
                //    new IndividualEnrollment(
                //            IndividualEnrollmentId,
                //            attestation);

                IndividualEnrollment individualEnrollment =
                    new IndividualEnrollment(individualEnrollmentId, attestation)
                {
                    ProvisioningStatus = ProvisioningStatus.Enabled,
                    DeviceId           = individualEnrollmentId,
                    Capabilities       = new Microsoft.Azure.Devices.Shared.DeviceCapabilities
                    {
                        IotEdge = true
                    },
                    InitialTwinState = new TwinState(
                        new Microsoft.Azure.Devices.Shared.TwinCollection("{ \"updatedby\":\"" + "damien" + "\", \"timeZone\":\"" + TimeZoneInfo.Local.DisplayName + "\" }"),
                        new Microsoft.Azure.Devices.Shared.TwinCollection("{}")
                        ),
                    ReprovisionPolicy = new ReprovisionPolicy
                    {
                        MigrateDeviceData   = false,
                        UpdateHubAssignment = true
                    }
                };

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

                var individualEnrollmentResult =
                    await provisioningServiceClient
                    .CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment)
                    .ConfigureAwait(false);

                _logger.LogInformation("EnrollmentGroup created with success.");
                _logger.LogInformation($"{individualEnrollmentResult}");
            }
        }
Example #4
0
        static async Task SetRegistrationDataAsync()
        {
            #region QueryingEnrollemnts
            Console.WriteLine("Fetching Existing Enrollments--------------------------------");
            using var serviceClient = ProvisioningServiceClient.CreateFromConnectionString(ServiceConnectionString);
            QuerySpecification qu = new QuerySpecification("SELECT * FROM enrollments");

            using (Query query = serviceClient.CreateIndividualEnrollmentQuery(qu))
            {
                while (query.HasNext())
                {
                    Console.WriteLine("\nQuerying the next enrollments...");
                    QueryResult queryResult = await query.NextAsync().ConfigureAwait(false);

                    Console.WriteLine(queryResult);
                }
            }
            Console.WriteLine("Enrollment Fetch Complete------------------------------------");
            #endregion

            #region CreateIndividualEnrollment
            Console.WriteLine("Starting SetRegistrationData");

            //Attestation attestation = X509Attestation.CreateFromClientCertificates(privateKey);


            var    pem        = System.IO.File.ReadAllText(@"D:\Code\Diality\CACerts\CACertificates\mydevice4-public.pem");
            string certBuffer = GetBytesFromPEM(pem, "CERTIFICATE");



            Attestation attestation = X509Attestation.CreateFromClientCertificates(certBuffer);



            IndividualEnrollment individualEnrollment = new IndividualEnrollment(SampleRegistrationId, attestation);

            individualEnrollment.DeviceId           = OptionalDeviceId;
            individualEnrollment.ProvisioningStatus = OptionalProvisioningStatus;
            individualEnrollment.IotHubHostName     = "vvk5cob-Iot-Hub-2.azure-devices.net";

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

            IndividualEnrollment individualEnrollmentResult =
                await serviceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

            Console.WriteLine("\nIndividualEnrollment created with success.");
            Console.WriteLine(individualEnrollmentResult);
            #endregion
        }
        public void X509AttestationCreateFromClientCertificatesSucceedOnPrimaryCertificate()
        {
            // arrange
            X509Certificate2 primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING));

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

            primary.Dispose();

            // assert
            Assert.IsNotNull(attestation.ClientCertificates.Primary);
            Assert.IsNull(attestation.ClientCertificates.Secondary);
            Assert.IsNull(attestation.RootCertificates);
            Assert.IsNull(attestation.CAReferences);
        }
        public IndividualEnrollment EnrollDevice(string deviceId, string password)
        {
            var cert = deviceManager.GenerateCertificate(deviceId);

            deviceManager.SaveCertificates(cert, deviceId, password);

            var publicCert = deviceManager.ReadPublicCertificate(deviceId);

            var attestation          = X509Attestation.CreateFromClientCertificates(publicCert);
            var individualEnrollment = new IndividualEnrollment($"{deviceId}", attestation)
            {
                DeviceId = deviceId
            };

            using (var provisioningClientService =
                       ProvisioningServiceClient.CreateFromConnectionString(configuration.GetValue <string>("DeviceProvisioningServiceConnection")))
            {
                var individualEnrollmentResult =
                    provisioningClientService.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).GetAwaiter().GetResult();

                return(individualEnrollment);
            }
        }
        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));
            }
        }
        public static async Task <IndividualEnrollment> CreateIndividualEnrollmentAsync(
            ProvisioningServiceClient provisioningServiceClient,
            string registrationId,
            AttestationMechanismType attestationType,
            X509Certificate2 authenticationCertificate,
            ReprovisionPolicy reprovisionPolicy,
            AllocationPolicy allocationPolicy,
            CustomAllocationDefinition customAllocationDefinition,
            ICollection <string> iotHubsToProvisionTo,
            DeviceCapabilities capabilities,
            MsTestLogger logger)
        {
            Attestation          attestation;
            IndividualEnrollment individualEnrollment;
            IndividualEnrollment createdEnrollment = null;

            switch (attestationType)
            {
            case AttestationMechanismType.Tpm:
                using (var tpmSim = new SecurityProviderTpmSimulator(registrationId))
                {
                    string base64Ek = Convert.ToBase64String(tpmSim.GetEndorsementKey());
                    individualEnrollment = new IndividualEnrollment(registrationId, new TpmAttestation(base64Ek))
                    {
                        Capabilities               = capabilities,
                        AllocationPolicy           = allocationPolicy,
                        ReprovisionPolicy          = reprovisionPolicy,
                        CustomAllocationDefinition = customAllocationDefinition,
                        IotHubs = iotHubsToProvisionTo
                    };

                    IndividualEnrollment temporaryCreatedEnrollment = null;
                    await RetryOperationHelper
                    .RetryOperationsAsync(
                        async() =>
                    {
                        temporaryCreatedEnrollment = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);
                    },
                        s_provisioningServiceRetryPolicy,
                        s_retryableExceptions,
                        logger)
                    .ConfigureAwait(false);

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

                    attestation = new TpmAttestation(base64Ek);
                    temporaryCreatedEnrollment.Attestation = attestation;

                    await RetryOperationHelper
                    .RetryOperationsAsync(
                        async() =>
                    {
                        createdEnrollment = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(temporaryCreatedEnrollment).ConfigureAwait(false);
                    },
                        s_provisioningServiceRetryPolicy,
                        s_retryableExceptions,
                        logger)
                    .ConfigureAwait(false);

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

                    return(createdEnrollment);
                }

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

            case AttestationMechanismType.X509:
                attestation = X509Attestation.CreateFromClientCertificates(authenticationCertificate);
                break;

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

            individualEnrollment = new IndividualEnrollment(registrationId, attestation)
            {
                Capabilities               = capabilities,
                AllocationPolicy           = allocationPolicy,
                ReprovisionPolicy          = reprovisionPolicy,
                CustomAllocationDefinition = customAllocationDefinition,
                IotHubs = iotHubsToProvisionTo,
            };

            await RetryOperationHelper
            .RetryOperationsAsync(
                async() =>
            {
                createdEnrollment = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);
            },
                s_provisioningServiceRetryPolicy,
                s_retryableExceptions,
                logger)
            .ConfigureAwait(false);

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

            return(createdEnrollment);
        }