Exemple #1
0
        public override void ExecuteCmdlet()
        {
            Path = ResolveUserPath(Path);
            if (ShouldProcess(CertificateName, Properties.Resources.AddIotHubCertificate))
            {
                string   certificate = string.Empty;
                FileInfo fileInfo    = new FileInfo(this.Path);
                switch (fileInfo.Extension.ToLower(CultureInfo.InvariantCulture))
                {
                case ".cer":
                    var certificateByteContent = File.ReadAllBytes(this.Path);
                    certificate = Convert.ToBase64String(certificateByteContent);
                    break;

                case ".pem":
                    certificate = File.ReadAllText(this.Path);
                    break;

                default:
                    certificate = this.Path;
                    break;
                }

                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.ResourceGroupName;
                    this.Name            = this.InputObject.Name;
                    this.CertificateName = this.InputObject.CertificateName;
                    this.Etag            = this.InputObject.Etag;
                }

                if (ParameterSetName.Equals(ResourceIdParameterSet))
                {
                    this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                    this.Name            = IotHubUtils.GetIotHubName(this.ResourceId);
                    this.CertificateName = IotHubUtils.GetIotHubCertificateName(this.ResourceId);
                }

                try
                {
                    certificate = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(certificate));

                    CertificateBodyDescription certificateBodyDescription = new CertificateBodyDescription();
                    certificateBodyDescription.Certificate = certificate;

                    CertificateDescription certificateDescription;
                    if (this.Etag != null)
                    {
                        certificateDescription = this.IotHubClient.Certificates.CreateOrUpdate(this.ResourceGroupName, this.Name, this.CertificateName, certificateBodyDescription, this.Etag);
                    }
                    else
                    {
                        certificateDescription = this.IotHubClient.Certificates.CreateOrUpdate(this.ResourceGroupName, this.Name, this.CertificateName, certificateBodyDescription);
                    }

                    this.WriteObject(IotHubUtils.ToPSCertificateDescription(certificateDescription));
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
Exemple #2
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.DeviceId, Properties.Resources.AddIotHubDevice))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                PSDeviceCapabilities psDeviceCapabilities = new PSDeviceCapabilities();
                psDeviceCapabilities.IotEdge = this.EdgeEnabled.IsPresent;

                PSAuthenticationMechanism auth = new PSAuthenticationMechanism();

                PSDevice device = new PSDevice();
                device.Id = this.DeviceId;
                switch (this.AuthMethod)
                {
                case PSDeviceAuthType.x509_thumbprint:
                    auth.Type           = PSAuthenticationType.SelfSigned;
                    auth.X509Thumbprint = new PSX509Thumbprint();
                    auth.X509Thumbprint.PrimaryThumbprint   = this.authTypeDynamicParameter.PrimaryThumbprint;
                    auth.X509Thumbprint.SecondaryThumbprint = this.authTypeDynamicParameter.SecondaryThumbprint;
                    break;

                case PSDeviceAuthType.x509_ca:
                    auth.Type = PSAuthenticationType.CertificateAuthority;
                    break;

                default:
                    auth.SymmetricKey = new PSSymmetricKey();
                    auth.Type         = PSAuthenticationType.Sas;
                    break;
                }
                device.Authentication = auth;
                device.Capabilities   = psDeviceCapabilities;
                device.Status         = this.Status;
                device.StatusReason   = this.StatusReason;

                if (this.EdgeEnabled.IsPresent)
                {
                    IList <Device> childDevices = new List <Device>();
                    foreach (string childDeviceId in this.Children)
                    {
                        Device childDevice = registryManager.GetDeviceAsync(childDeviceId).GetAwaiter().GetResult();

                        if (childDevice == null)
                        {
                            throw new ArgumentException($"The entered children device \"{childDeviceId}\" doesn't exist.");
                        }

                        if (childDevice.Capabilities.IotEdge)
                        {
                            throw new ArgumentException($"The entered children device \"{childDeviceId}\" should be non-edge device.");
                        }

                        if (!string.IsNullOrEmpty(childDevice.Scope) && !this.Force.IsPresent)
                        {
                            throw new ArgumentException($"The entered children device \"{childDeviceId}\" already has a parent device, please use '-Force' to overwrite.");
                        }

                        childDevices.Add(childDevice);
                    }
                }
                else
                {
                    if (this.ParentDeviceId != null)
                    {
                        Device parentDevice = registryManager.GetDeviceAsync(this.ParentDeviceId).GetAwaiter().GetResult();

                        if (parentDevice == null)
                        {
                            throw new ArgumentException($"The entered parent device \"{this.ParentDeviceId}\" doesn't exist.");
                        }

                        if (!parentDevice.Capabilities.IotEdge)
                        {
                            throw new ArgumentException($"The entered parent device \"{this.ParentDeviceId}\" should be an edge device.");
                        }

                        device.Scope = parentDevice.Scope;
                    }
                }

                Device newDevice = registryManager.AddDeviceAsync(IotHubDataPlaneUtils.ToDevice(device)).GetAwaiter().GetResult();
                this.WriteObject(IotHubDataPlaneUtils.ToPSDevice(newDevice));

                if (this.EdgeEnabled.IsPresent)
                {
                    foreach (string childDeviceId in this.Children)
                    {
                        Device childDevice = registryManager.GetDeviceAsync(childDeviceId).GetAwaiter().GetResult();

                        if (childDevice.Capabilities.IotEdge)
                        {
                            throw new ArgumentException($"The entered children device \"{childDeviceId}\" should be non-edge device.");
                        }

                        if (!string.IsNullOrEmpty(childDevice.Scope) && !this.Force.IsPresent)
                        {
                            throw new ArgumentException($"The entered children device \"{childDeviceId}\" already has a parent device, please use '-Force' to overwrite.");
                        }

                        childDevice.Scope = newDevice.Scope;
                        registryManager.UpdateDeviceAsync(childDevice).GetAwaiter().GetResult();
                    }
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(Name, Properties.Resources.UpdateIotHub))
            {
                IotHubDescription iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.Name);

                switch (ParameterSetName)
                {
                case UpdateSkuParameterSet:

                    var psIotHubSku = new PSIotHubSkuInfo()
                    {
                        Name     = this.SkuName,
                        Capacity = this.Units
                    };

                    iotHubDescription.Sku = IotHubUtils.ToIotHubSku(psIotHubSku);
                    break;

                case UpdateEventHubEndpointPropertiesParameterSet:

                    iotHubDescription.Properties.EventHubEndpoints["events"].RetentionTimeInDays = this.EventHubRetentionTimeInDays;
                    iotHubDescription.Properties.EventHubEndpoints["operationsMonitoringEvents"].RetentionTimeInDays = this.EventHubRetentionTimeInDays;
                    break;

                case UpdateFileUploadPropertiesParameterSet:

                    iotHubDescription.Properties.EnableFileUploadNotifications = this.EnableFileUploadNotifications;

                    if (this.FileUploadStorageConnectionString != null)
                    {
                        iotHubDescription.Properties.StorageEndpoints["$default"].ConnectionString = this.FileUploadStorageConnectionString;
                    }

                    if (this.FileUploadContainerName != null)
                    {
                        iotHubDescription.Properties.StorageEndpoints["$default"].ContainerName = this.FileUploadContainerName;
                    }

                    if (this.FileUploadSasUriTtl != null)
                    {
                        iotHubDescription.Properties.StorageEndpoints["$default"].SasTtlAsIso8601 = this.FileUploadSasUriTtl;
                    }

                    if (this.FileUploadNotificationTtl != null)
                    {
                        iotHubDescription.Properties.MessagingEndpoints["fileNotifications"].TtlAsIso8601 = this.FileUploadNotificationTtl;
                    }

                    if (this.FileUploadNotificationMaxDeliveryCount != null)
                    {
                        iotHubDescription.Properties.MessagingEndpoints["fileNotifications"].MaxDeliveryCount = (int)this.FileUploadNotificationMaxDeliveryCount;
                    }

                    break;

                case UpdateCloudToDevicePropertiesParameterSet:

                    if (this.CloudToDevice != null)
                    {
                        iotHubDescription.Properties.CloudToDevice = IotHubUtils.ToCloudToDeviceProperties(this.CloudToDevice);
                    }

                    break;

                case UpdateOperationsMonitoringPropertiesParameterSet:

                    if (this.OperationsMonitoringProperties != null)
                    {
                        iotHubDescription.Properties.OperationsMonitoringProperties = IotHubUtils.ToOperationsMonitoringProperties(this.OperationsMonitoringProperties);
                    }

                    break;

                default:
                    throw new ArgumentException("BadParameterSetName");
                }

                this.IotHubClient.IotHubResource.CreateOrUpdate(this.ResourceGroupName, this.Name, iotHubDescription);
                IotHubDescription updatedIotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.Name);
                this.WriteObject(IotHubUtils.ToPSIotHub(updatedIotHubDescription), false);
            }
        }
        public override void ExecuteCmdlet()
        {
            IotHubDescription iotHubDescription;

            if (ParameterSetName.Equals(InputObjectParameterSet))
            {
                this.ResourceGroupName = this.InputObject.Resourcegroup;
                this.IotHubName        = this.InputObject.Name;
                iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
            }
            else
            {
                if (ParameterSetName.Equals(ResourceIdParameterSet))
                {
                    this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                    this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                }

                iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
            }

            IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
            SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
            PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
            RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

            if (ShouldProcess(this.DeviceId, Properties.Resources.RemoveIotHubDevice))
            {
                try
                {
                    if (string.IsNullOrEmpty(this.DeviceId))
                    {
                        IList <Device>       devices       = new List <Device>();
                        IEnumerable <string> deviceResults = registryManager.CreateQuery("Select * from Devices").GetNextAsJsonAsync().GetAwaiter().GetResult();
                        foreach (string deviceResult in deviceResults)
                        {
                            Device d = JsonConvert.DeserializeObject <Device>(deviceResult);
                            devices.Add(registryManager.GetDeviceAsync(d.Id).GetAwaiter().GetResult());
                        }
                        var result = registryManager.RemoveDevices2Async(devices).GetAwaiter().GetResult();

                        if (result.IsSuccessful)
                        {
                            if (PassThru.IsPresent)
                            {
                                this.WriteObject(true);
                            }
                        }
                        else
                        {
                            if (PassThru.IsPresent)
                            {
                                this.WriteObject(false);
                            }
                        }
                    }
                    else
                    {
                        Device d = registryManager.GetDeviceAsync(this.DeviceId).GetAwaiter().GetResult();
                        if (d != null)
                        {
                            registryManager.RemoveDeviceAsync(this.DeviceId).GetAwaiter().GetResult();
                            if (PassThru.IsPresent)
                            {
                                this.WriteObject(true);
                            }
                        }
                        else
                        {
                            throw new ArgumentNullException("The target device doesn't exist.");
                        }
                    }
                }
                catch
                {
                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(false);
                    }
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.IotHubName, Properties.Resources.NewIotHubSasToken))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                if (this.IsParameterBound(c => c.ModuleId) && !this.IsParameterBound(c => c.DeviceId))
                {
                    throw new ArgumentException("You are unable to get sas token for module without device information.");
                }

                if (!this.IsParameterBound(c => c.Duration))
                {
                    this.Duration = 3600;
                }

                string resourceUri = string.Empty;
                string keyName     = string.Empty;
                string key         = string.Empty;

                if (this.IsParameterBound(c => c.DeviceId))
                {
                    IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                    SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryRead);
                    PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                    RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                    if (this.IsParameterBound(c => c.ModuleId))
                    {
                        Module module = registryManager.GetModuleAsync(this.DeviceId, this.ModuleId).GetAwaiter().GetResult();
                        if (module != null)
                        {
                            if (module.Authentication.Type.Equals(AuthenticationType.Sas))
                            {
                                resourceUri = string.Format("{0}/devices/{1}/modules/{2}", iotHubDescription.Properties.HostName, this.DeviceId, this.ModuleId);
                                key         = this.KeyType.Equals(PSKeyType.primary) ? module.Authentication.SymmetricKey.PrimaryKey : module.Authentication.SymmetricKey.SecondaryKey;
                            }
                            else
                            {
                                throw new ArgumentException("This module does not support SAS auth.");
                            }
                        }
                        else
                        {
                            throw new ArgumentException($"The entered module \"{this.ModuleId}\" doesn't exist.");
                        }
                    }
                    else
                    {
                        Device device = registryManager.GetDeviceAsync(this.DeviceId).GetAwaiter().GetResult();
                        if (device != null)
                        {
                            if (device.Authentication.Type.Equals(AuthenticationType.Sas))
                            {
                                resourceUri = string.Format("{0}/devices/{1}", iotHubDescription.Properties.HostName, this.DeviceId);
                                key         = this.KeyType.Equals(PSKeyType.primary) ? device.Authentication.SymmetricKey.PrimaryKey : device.Authentication.SymmetricKey.SecondaryKey;
                            }
                            else
                            {
                                throw new ArgumentException("This device does not support SAS auth.");
                            }
                        }
                        else
                        {
                            throw new ArgumentException($"The entered device \"{this.DeviceId}\" doesn't exist.");
                        }
                    }
                }
                else
                {
                    if (!this.IsParameterBound(c => c.KeyName))
                    {
                        this.KeyName = "iothubowner";
                    }
                    SharedAccessSignatureAuthorizationRule authPolicy = this.IotHubClient.IotHubResource.GetKeysForKeyName(this.ResourceGroupName, this.IotHubName, this.KeyName);
                    resourceUri = iotHubDescription.Properties.HostName;
                    keyName     = authPolicy.KeyName;
                    key         = this.KeyType.Equals(PSKeyType.primary) ? authPolicy.PrimaryKey : authPolicy.SecondaryKey;
                }

                this.WriteObject(this.createToken(resourceUri, keyName, key, this.Duration));
            }
        }
Exemple #6
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(Name, ResourceProperties.Resources.NewAzureRmIotHubImportDevices))
            {
                var importDevicesRequest = new PSImportDevicesRequest()
                {
                    InputBlobContainerUri  = this.InputBlobContainerUri,
                    OutputBlobContainerUri = this.OutputBlobContainerUri
                };

                JobResponse jobResponse = this.IotHubClient.IotHubResource.ImportDevices(this.ResourceGroupName, this.Name, IotHubUtils.ToImportDevicesRequest(importDevicesRequest));
                this.WriteObject(IotHubUtils.ToPSIotHubJobResponse(jobResponse), false);
            }
        }
Exemple #7
0
        public override void ExecuteCmdlet()
        {
            RegistryStatistics registryStats = this.IotHubClient.IotHubResource.GetStats(this.ResourceGroupName, this.Name);

            this.WriteObject(IotHubUtils.ToPSIotHubRegistryStatistics(registryStats), false);
        }
Exemple #8
0
        public override void ExecuteCmdlet()
        {
            IEnumerable <EventHubConsumerGroupInfo> iotHubEHConsumerGroups = this.IotHubClient.IotHubResource.ListEventHubConsumerGroups(this.ResourceGroupName, this.Name, this.EventHubEndpointName);

            this.WriteObject(IotHubUtils.ToPSEventHubConsumerGroupInfo(iotHubEHConsumerGroups), true);
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.DeviceId, Properties.Resources.RemoveIotHubDeviceChildren))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                Device parentDevice = registryManager.GetDeviceAsync(this.DeviceId).GetAwaiter().GetResult();

                if (parentDevice == null)
                {
                    throw new ArgumentException($"The entered parent device \"{this.DeviceId}\" doesn't exist.");
                }

                if (!parentDevice.Capabilities.IotEdge)
                {
                    throw new ArgumentException($"The entered device \"{this.DeviceId}\" should be an edge device.");
                }

                IList <Device> childDevices = new List <Device>();

                if (this.Children != null)
                {
                    foreach (string childDeviceId in this.Children)
                    {
                        Device childDevice = registryManager.GetDeviceAsync(childDeviceId).GetAwaiter().GetResult();

                        if (childDevice == null)
                        {
                            throw new ArgumentException($"The entered children device \"{childDeviceId}\" doesn't exist.");
                        }

                        if (childDevice.Capabilities.IotEdge)
                        {
                            throw new ArgumentException($"The entered children device \"{childDeviceId}\" should be non-edge device.");
                        }

                        if (!string.IsNullOrEmpty(childDevice.Scope) && !childDevice.Scope.Equals(parentDevice.Scope))
                        {
                            throw new ArgumentException($"The entered children device \"{childDeviceId}\" isn\'t assigned as a child of entered device \"{this.DeviceId}\".");
                        }

                        childDevices.Add(childDevice);
                    }
                }
                else
                {
                    IEnumerable <string> deviceResults = registryManager.CreateQuery(IotHubDataPlaneUtils.GetNonEdgeDevices(parentDevice.Scope)).GetNextAsJsonAsync().GetAwaiter().GetResult();
                    foreach (string deviceResult in deviceResults)
                    {
                        Device d = JsonConvert.DeserializeObject <Device>(deviceResult);
                        childDevices.Add(registryManager.GetDeviceAsync(d.Id).GetAwaiter().GetResult());
                    }
                }

                try
                {
                    foreach (Device childDevice in childDevices)
                    {
                        childDevice.Scope = string.Empty;
                        registryManager.UpdateDeviceAsync(childDevice).GetAwaiter().GetResult();
                    }

                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(true);
                    }
                }
                catch
                {
                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(false);
                    }
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(Name, ResourceProperties.Resources.NewAzureRmIotHubImportDevices))
            {
                var exportDevicesRequest = new PSExportDevicesRequest()
                {
                    ExportBlobContainerUri = this.ExportBlobContainerUri,
                    ExcludeKeys            = this.ExcludeKeys.IsPresent
                };

                JobResponse jobResponse = this.IotHubClient.IotHubResource.ExportDevices(this.ResourceGroupName, this.Name, IotHubUtils.ToExportDevicesRequest(exportDevicesRequest));
                this.WriteObject(IotHubUtils.ToPSIotHubJobResponse(jobResponse), false);
            }
        }
        public override void ExecuteCmdlet()
        {
            IEnumerable <IotHubQuotaMetricInfo> iotHubQuotaMetrics = this.IotHubClient.IotHubResource.GetQuotaMetrics(this.ResourceGroupName, this.Name);

            this.WriteObject(IotHubUtils.ToPSIotHubQuotaMetrics(iotHubQuotaMetrics), true);
        }