register device on iothub bulk import and send data

class Program
{
static RegistryManager registryManager;

static string connectionString = “iothub-connection”;

static void Main(string[] args)
{
//Task t1 = senddata();
//t1.Wait();

//Task t1 = BulkImport();
//t1.Wait();

}

private static async Task senddata()
{
try
{
DeviceClient deviceClient = DeviceClient.Create(“eu1ecoinstecuioth.azure-devices.net”,
new DeviceAuthenticationWithRegistrySymmetricKey(“deviceid”, “device-key”), Microsoft.Azure.Devices.Client.TransportType.Mqtt);
while (true)
{
await deviceClient.SendEventAsync(new Microsoft.Azure.Devices.Client.Message() { MessageId=””});
}
}
catch (Exception ex)
{

throw;
}

}

static string GetContainerSasUri(CloudBlobContainer container)
{
// Set the expiry time and permissions for the container.
// In this case no start time is specified, so the
// shared access signature becomes valid immediately.
var sasConstraints = new SharedAccessBlobPolicy();
sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24);
sasConstraints.Permissions =
SharedAccessBlobPermissions.Write |
SharedAccessBlobPermissions.Read |
SharedAccessBlobPermissions.Delete;

// Generate the shared access signature on the container,
// setting the constraints directly on the signature.
string sasContainerToken = container.GetSharedAccessSignature(sasConstraints);

// Return the URI string for the container,
// including the SAS token.
return container.Uri + sasContainerToken;
}

private static async Task BulkImport()
{
try
{
registryManager = RegistryManager.CreateFromConnectionString(connectionString);

StorageCredentials storageCredentials = new StorageCredentials(“storagename”, “storageKey”);
CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, useHttps: true);
// Create a blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

CloudBlobContainer container = blobClient.GetContainerReference(“bulkiothubimport”);
CloudBlockBlob blob = container.GetBlockBlobReference(“devices.txt”);

var containerSasUri = GetContainerSasUri(container);

// Provision 1,000 more devices
var serializedDevices = new List<string>();

for (var i = 0; i < 5; i++)
{
// Create a new ExportImportDevice
// CryptoKeyGenerator is in the Microsoft.Azure.Devices.Common namespace
var deviceToAdd = new ExportImportDevice()
{
Id = i + “Demo”,
Status = DeviceStatus.Enabled,
Authentication = new AuthenticationMechanism()
{
SymmetricKey = new SymmetricKey()
{
PrimaryKey = CryptoKeyGenerator.GenerateKey(32),
SecondaryKey = CryptoKeyGenerator.GenerateKey(32)
}
},
ImportMode = ImportMode.Create
};

// Add device to the list
serializedDevices.Add(JsonConvert.SerializeObject(deviceToAdd));
}

// Write the list to the blob
var sb = new StringBuilder();
serializedDevices.ForEach(serializedDevice => sb.AppendLine(serializedDevice));
await blob.DeleteIfExistsAsync();

using (CloudBlobStream stream = await blob.OpenWriteAsync())
{
byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString());
for (var i = 0; i < bytes.Length; i += 500)
{
int length = Math.Min(bytes.Length – i, 500);
await stream.WriteAsync(bytes, i, length);
}
}

// Call import using the blob to add new devices
// Log information related to the job is written to the same container
// This normally takes 1 minute per 100 devices
JobProperties importJob =
await registryManager.ImportDevicesAsync(containerSasUri, containerSasUri);

// Wait until job is finished
while (true)
{
importJob = await registryManager.GetJobAsync(importJob.JobId);
if (importJob.Status == JobStatus.Completed ||
importJob.Status == JobStatus.Failed ||
importJob.Status == JobStatus.Cancelled)
{
// Job has finished executing
break;
}

await Task.Delay(TimeSpan.FromSeconds(5));
}
}
catch (Exception ex)
{
throw ex;
}
}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s