public static async Task <IEnumerable <string> > CreateDevices(string hubConnectionString, IEnumerable <string> deviceIds)
        {
            if (deviceIds.Count() <= 1)
            {
                return(new string[] { await CreateDevice(hubConnectionString, deviceIds.FirstOrDefault()) });
            }

            IotHubConnectionStringBuilder connection = IotHubConnectionStringBuilder.Create(hubConnectionString);
            RegistryManager registryManager          = RegistryManager.CreateFromConnectionString(connection.ToString());

            var tempIds = deviceIds;

            do
            {
                await registryManager.AddDevices2Async(tempIds.Take(100).Select(deviceId => new Device(deviceId)));

                tempIds = tempIds.Skip(100);
            } while (tempIds.Any());

            ConcurrentBag <Device> devices = new ConcurrentBag <Device>();

            tempIds = deviceIds;

            do
            {
                await Task.WhenAll(tempIds.Take(50).Select(x => AddDevice(devices, x, registryManager)));

                tempIds = tempIds.Skip(50);
            } while (tempIds.Any());


            return(devices.Select(x => "HostName=" + connection.HostName + ";DeviceId=" + x.Id + ";SharedAccessKey=" + x.Authentication.SymmetricKey.PrimaryKey));
        }
Esempio n. 2
0
        /// <summary>
        /// Registers devices with the IoT Hub.
        /// </summary>
        /// <param name="registryManager">An instance of <c>RegistryManager</c></param>
        /// <param name="deviceIds">The list of device ids to register.</param>
        /// <param name="enable">Devices will be registered with enabled state if this is set to true.</param>
        /// <returns>Any errors returned during the bulk register operation (and bulk update operation if devices are being enabled also).</returns>
        private async Task <IEnumerable <DeviceRegistryOperationError> > RegisterDevices(RegistryManager registryManager, List <string> deviceIds, bool enable = false)
        {
            IEnumerable <DeviceRegistryOperationError> registerErrors = deviceIds.Where(
                id => !AzureIoTDeviceIdRegex.IsMatch(id)
                )
                                                                        .Select(
                id => new DeviceRegistryOperationError()
            {
                ErrorCode   = ErrorCode.ArgumentInvalid,
                DeviceId    = id,
                ErrorStatus = String.Format(Labels.AzureIoTDeviceIdInvalid, id)
            }
                );
            IEnumerable <DeviceRegistryOperationError> updateErrors = Enumerable.Empty <DeviceRegistryOperationError>();
            List <Device> deviceList = deviceIds.Where(
                id => AzureIoTDeviceIdRegex.IsMatch(id)
                ).Select(
                id => { return(new Device(id)
                {
                    Status = enable ? DeviceStatus.Enabled : DeviceStatus.Disabled
                }); }
                ).ToList();

            if (deviceList.Count > 0)
            {
                BulkRegistryOperationResult registerResult = await registryManager.AddDevices2Async(deviceList);

                if (!registerResult.IsSuccessful)
                {
                    // Some devices were already registered.
                    // Explicity enable those devices only if the argument is set to true, otherwise skip this step.
                    if (enable)
                    {
                        IEnumerable <string> deviceIdsToUpdate = registerResult.Errors
                                                                 .Where(
                            error => error.ErrorCode == ErrorCode.DeviceAlreadyExists
                            )
                                                                 .Select(
                            error => error.DeviceId
                            );

                        updateErrors = await SetStatuses(registryManager, deviceIdsToUpdate, DeviceStatus.Enabled);
                    }
                }

                registerErrors = registerErrors.Concat(GetRegistryOperationErrors(registerResult, ErrorCode.DeviceAlreadyExists));
            }

            return(registerErrors.Concat(updateErrors));
        }
Esempio n. 3
0
        /// <summary>
        /// Register a list of devices
        /// </summary>
        /// <param name="devices"></param>
        /// <returns></returns>
        public static async Task <BulkRegistryOperationResult> AddDevices2Async(IEnumerable <Device> devices)
        {
            BulkRegistryOperationResult operationResults;

            try
            {
                operationResults = await registryManager.AddDevices2Async(devices);

                return(operationResults);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{Utils.FormatExceptionMessage(ex)}");
                throw ex;
            }
        }
        private async Task <string[]> RegisterBatchDeviceAsync(
            RegistryManager registryManager,
            string[] ids,
            CancellationToken cancellationToken)
        {
            var devices = from id in ids
                          select new Device(id)
            {
                Authentication = new AuthenticationMechanism
                {
                    SymmetricKey = new SymmetricKey()
                }
            };

            try
            {
                var result = await registryManager.AddDevices2Async(
                    devices,
                    cancellationToken);

                if (result.IsSuccessful)
                {
                    _telemetryClient.TrackMetric(
                        "registration-count",
                        ids.Length);

                    return(ids);
                }
                else
                {
                    throw new InvalidOperationException(
                              $"{result.Errors.Length} errors detected while registering devices");
                }
            }
            catch (Exception ex)
            {
                _telemetryClient.TrackException(ex);

                throw;
            }
        }
Esempio n. 5
0
        private async void cmd01RegisterNewDevice_Click(object sender, RoutedEventArgs e)
        {
            RegistryManager rm = RegistryManager.CreateFromConnectionString(m_ownerConnection);

            Device[] devArr = new Device[10];
            for (int i = 0; i < 10; i++)
            {
                devArr[i] = new Device($"wpf{i}");
            }
            foreach (var item in await rm.GetDevicesAsync(1000))
            {
                if (item.Id.StartsWith("wpf"))
                {
                    await rm.RemoveDevices2Async(new Device[] { item });
                }
            }

            var resultAdd = await rm.AddDevices2Async(devArr);

            foreach (var item in resultAdd.Errors)
            {
                Debug.WriteLine(item);
            }

            //SAS
            var    builder = Microsoft.Azure.Devices.IotHubConnectionStringBuilder.Create(m_ownerConnection);
            Device pc      = await rm.GetDeviceAsync("PC");

            var sasBuilder = new SharedAccessSignatureBuilder()
            {
                Key        = pc.Authentication.SymmetricKey.PrimaryKey,
                Target     = String.Format("{0}/devices/{1}", builder.HostName, WebUtility.UrlEncode(pc.Id)),
                TimeToLive = TimeSpan.FromDays(5)
            };

            string sas = $"HostName={builder.HostName};DeviceId={pc.Id};SharedAccessSignature={sasBuilder.ToSignature()}";

            Debug.WriteLine($"SAS: {sas}");
        }
Esempio n. 6
0
        private static async Task BulkCreateDevicesAsync(List <Device> devices, RegistryManager registryManager, DeviceProvisionStats stats)
        {
            try
            {
                var bulkResult = await registryManager.AddDevices2Async(devices);

                var totalErrors  = bulkResult?.Errors?.Length ?? 0;
                var totalCreated = devices.Count - totalErrors;
                if (totalCreated > 0)
                {
                    stats.IncrementCreated(totalCreated);
                }

                if (totalErrors > 0)
                {
                    stats.IncrementErrors(totalErrors);
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
        }
Esempio n. 7
0
        private async Task <IDictionary <string, string> > CreateIoTHubDevicesAndGetConnectionStringsAsync(
            IDictionary <string, List <DeviceDescription> > allDevices)
        {
            var result = new ConcurrentDictionary <string, string>();

            string[] deviceIds = allDevices.Keys.ToArray();

            Console.WriteLine($"{_actionMessage} devices...");
            if (RemoveDevices)
            {
                await RemoveDevicesAsync(deviceIds);
            }
            else
            {
                const int maxDevicesPerCall     = 100;
                int       numberOfCallsRequired = (int)Math.Ceiling(deviceIds.Length / (double)maxDevicesPerCall);
                for (int i = 0; i < numberOfCallsRequired; i++)
                {
                    string[] deviceIdsForCall = deviceIds.Skip(i * maxDevicesPerCall).Take(maxDevicesPerCall).ToArray();
                    BulkRegistryOperationResult bulkCreationResult =
                        await _registryManager.AddDevices2Async(deviceIdsForCall.Select(id => new Device(id)));

                    if (!bulkCreationResult.IsSuccessful)
                    {
                        Console.WriteLine("Failed creating devices...");
                        foreach (DeviceRegistryOperationError creationError in bulkCreationResult.Errors)
                        {
                            Console.WriteLine($"Device {creationError.DeviceId}: {creationError.ErrorStatus}");
                        }

                        throw new Exception();
                    }
                }
            }

            Console.WriteLine($"{_actionMessage} devices completed.");


            if (!RemoveDevices)
            {
                Console.WriteLine("Retrieving connection strings...");
                await InitializeBlobContainerAsync();

                string sasToken = _deviceExportContainer.GetSharedAccessSignature(new SharedAccessBlobPolicy(), "saspolicy");

                var containerSasUri = $"{_deviceExportContainer.Uri}{sasToken}";

                var job = await _registryManager.ExportDevicesAsync(containerSasUri, false);

                while (true)
                {
                    job = await _registryManager.GetJobAsync(job.JobId);

                    if (job.Status == JobStatus.Completed ||
                        job.Status == JobStatus.Failed ||
                        job.Status == JobStatus.Cancelled)
                    {
                        // Job has finished executing

                        break;
                    }

                    await Task.Delay(TimeSpan.FromSeconds(5));
                }

                var exportedDevices = new List <ExportImportDevice>();
                var blob            = _deviceExportContainer.GetBlobReference("devices.txt");
                using (var streamReader = new StreamReader(await blob.OpenReadAsync(), Encoding.UTF8))
                {
                    while (streamReader.Peek() != -1)
                    {
                        string line = await streamReader.ReadLineAsync();

                        var device = JsonConvert.DeserializeObject <ExportImportDevice>(line);
                        exportedDevices.Add(device);
                    }
                }

                await _deviceExportContainer.DeleteIfExistsAsync();

                await File.WriteAllTextAsync(CreatedDevicesJsonFileName, JsonConvert.SerializeObject(exportedDevices));

                foreach (ExportImportDevice device in exportedDevices.OrderBy(d => d.Id))
                {
                    result[device.Id] =
                        $"HostName={_iotHubConnectionStringBuilder.HostName};DeviceId={device.Id};SharedAccessKey={device.Authentication.SymmetricKey.PrimaryKey}";
                }

                Console.WriteLine("Retrieval complete.");
            }

            return(result);
        }
Esempio n. 8
0
 private Task <BulkRegistryOperationResult> CreateEdgeDevicesAsync(IEnumerable <Device> edgeDevices)
 {
     return(_registryManager.AddDevices2Async(edgeDevices));
 }
Esempio n. 9
0
        private static async Task BulkCreateAsync(RegistryManager registryManager, CancellationToken cancellationToken)
        {
            var devices = ReadFromCsv("devices.csv");

            // devices must be unique, so get existing devices
            var existingTwin = devices
                               .Select(x => registryManager.GetTwinAsync(x.Id))
                               .ToArray();

            await Task.WhenAll(existingTwin);

            var existingDevices = existingTwin
                                  .Select(task => task.Result)
                                  .Where(x => x != null)
                                  .ToArray();

            if (existingDevices.Length > 0)
            {
                Console.WriteLine($"{existingDevices.Length} devices already exist.");
            }

            // only insert devices that don't exist yet
            var devicesToUpload = devices
                                  .Where(device => existingDevices.All(existing => existing.DeviceId != device.Id))
                                  .Select(deviceInfo => new Device(deviceInfo.Id)
            {
                Status = deviceInfo.Enabed ? DeviceStatus.Enabled : DeviceStatus.Disabled
            })
                                  .ToList();

            if (devicesToUpload.Any())
            {
                Console.WriteLine($"Creating {devicesToUpload.Count} devices..");
                var result = await registryManager.AddDevices2Async(devicesToUpload, cancellationToken);

                if (!result.IsSuccessful)
                {
                    throw new AggregateException("Device creation failed!",
                                                 result.Errors.Select(e => new Exception(JsonSerializer.Serialize(new
                    {
                        deviceId = e.DeviceId,
                        code     = e.ErrorCode,
                        status   = e.ErrorStatus,
                        moduleid = e.ModuleId
                    }))));
                }
            }

            // need etag from cloud before updating, so fetch all devices again
            existingTwin = devices
                           .Select(deviceInfo => registryManager.GetTwinAsync(deviceInfo.Id))
                           .ToArray();

            await Task.WhenAll(existingTwin);

            var devicesInCloud = existingTwin
                                 .Select(task => task.Result)
                                 .ToArray();

            var twins = devices
                        .Select(d => new Twin(d.Id)
            {
                Tags = new TwinCollection(JsonSerializer.Serialize(new
                {
                    country    = d.Country,
                    building   = d.Building,
                    floor      = d.Floor,
                    sensorType = d.SensorType
                })),
                ETag = devicesInCloud.Single(cloudDevice => cloudDevice.DeviceId == d.Id).ETag
            })
                        .ToList();

            Console.WriteLine($"Updating twin state (and setting tags) on all {twins.Count} devices..");
            await registryManager.UpdateTwins2Async(twins, cancellationToken);
        }