【发布时间】:2020-04-10 05:07:27
【问题描述】:
我尝试上传文件如下
public async Task UploadFiles(string instanceType, string transportType, int numberOfFiles)
{
var instance = FeatureTestContext.Instances[instanceType];
var registeredType = GetTypeDefinition(instance.GetTypeId());
var objectId = instance.GetId();
for (int i = 0; i < numberOfFiles; i++)
{
var file = new FileInfo($"{objectId}-{i}-{DateTime.UtcNow.Ticks}.txt");
var storagePath = $"UAT/Robotics/{instanceType}";
File.WriteAllLines(file.FullName, new string[] { instance.AsJson(), Guid.NewGuid().ToString(), DateTime.Now.ToString()});
if (transportType.Equals("gateway", StringComparison.InvariantCultureIgnoreCase))
{
var response = await DataAccessService.UploadFileAsync(objectId, instance.GetModel(), file, storagePath);
Assert.IsTrue(response, "Expected the file to be uploaded");
}
else if (transportType.Equals("edge", StringComparison.InvariantCultureIgnoreCase))
{
//rest to the edge module ID since this is what will be used when the edge module uploads the file.
objectId = Guid.Parse(_fixture.RoboticsEdgeModuleId);
Assert.Fail("Uploading files from the edge causes Edge to fail");
var response = await DataAccessService.SendFileUploadCommandAsync(
_fixture.RoboticsEdgeModuleId,
file.Name,
File.ReadAllText(file.FullName),
"abb.ability.device");
Assert.IsTrue(response, "Exepcted to be able to send the uploadFile command");
}
else
{
await DataAccessService.UploadFileThroughIoTHub(objectId, file, Client.TransportType.Amqp);
}
var fileUpload = new FileUpload();
fileUpload.File = file;
fileUpload.ObjectId = objectId;
fileUpload.Model = instance.GetModel();
fileUpload.StoragePath = storagePath;
ScenarioTestContext.FileUploads.Add(fileUpload);
}
}
然后像上面的方法一样从 else 条件调用下面的方法
public async Task UploadFileThroughIoTHub(Guid objectId, FileInfo file, TransportType transportType)
{
var deviceClient = _provisioningService.CreateDeviceClient(transportType);
using (var sourceData = new FileStream(file.FullName, FileMode.Open))
{
await deviceClient.UploadToBlobAsync($"{objectId}/{file.Name}", sourceData);
}
}
创建设备客户端的代码如下
public Client.DeviceClient CreateDeviceClient(Client.TransportType transportType)
{
if (_fixture.DeviceName == null && _deviceKey == null) return null;
if (_client == null)
{
if (_fixture.UseCertificate)
{
var initialPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), PathCertPath.ToString());
DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(initialPath);
FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*");
var cert = new X509Certificate2(File.ReadAllBytes(Path.Combine(initialPath, filesInDir[0].ToString())),
"123",
X509KeyStorageFlags.UserKeySet);
var auth = new DeviceAuthenticationWithX509Certificate(Path.GetFileName(filesInDir[0].ToString().Replace(".pfx", "")), cert);
_client = DeviceClient.Create(_fixture.IoTHubHostName, auth, transportType);
}
else if (!_fixture.UseCertificate)
{
_client = Client.DeviceClient.Create(_fixture.IoTHubHostName,
new Client.DeviceAuthenticationWithRegistrySymmetricKey(_fixture.DeviceName, _deviceKey),
transportType);
}
}
return _client;
}
在调试 'UploadFileThroughIoTHub' 方法的 sourceData 属性之一时,如下所示
“sourceData.ReadTimeout”引发了“System.InvalidOperationException”类型的异常
堆栈跟踪如下。测试使用 Specflow 运行。
消息: 测试方法 RoboticsRegressionTests.Feature.RoboticsRegressionFeature.PublishFile_ABTesting_IoTHub 抛出异常: System.NullReferenceException:对象引用未设置为对象的实例。
堆栈跟踪:
IAuthorizationProvider.GetPasswordAsync()
HttpClientHelper.ExecuteAsync(HttpMethod httpMethod, Uri requestUri, Func3 modifyRequestMessageAsync, Func2 isSuccessful, Func3 processResponseMessageAsync, IDictionary2 errorMappingOverrides, CancellationToken cancelToken)
HttpClientHelper.PostAsync[T1,T2](Uri requestUri, T1 entity, IDictionary2 errorMappingOverrides, IDictionary2 customHeaders, CancellationToken cancelToken)
HttpTransportHandler.UploadToBlobAsync(字符串 blobName,流源)
DataAccessService.UploadFileThroughIoTHub(Guid objectId, FileInfo file, TransportType transportType) 第 592 行
RoboticsRegressionStepDefinition.UploadFiles(String instanceType, String transportType, Int32 numberOfFiles) 第 873 行
【问题讨论】:
标签: c# visual-studio azure specflow azure-iot-hub