【问题标题】:Upload to azure blob fails with exception上传到 azure blob 失败并出现异常
【发布时间】: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 行 d.MoveNext() 第 32 行 --- 从先前抛出异常的位置结束堆栈跟踪 --- d.MoveNext() --- 从先前抛出异常的位置结束堆栈跟踪 --- ExclusiveSynchronizationContext.BeginMessageLoop() 第 125 行 AsyncHelpers.RunSync[T](Func`1 task) 第 72 行 BindingInvoker.InvokeBinding(IBinding binding, IContextManager contextManager, Object[] arguments, ITestTracer testTracer, TimeSpan& duration) 第 49 行 TestExecutionEngine.ExecuteStepMatch(BindingMatch 匹配,Object[] 参数)第 395 行 TestExecutionEngine.ExecuteStep(IContextManager contextManager, StepInstance stepInstance) 第 316 行 TestExecutionEngine.OnAfterLastStep() 第 132 行 RoboticsRegressionFeature.ScenarioCleanup() RoboticsRegressionFeature.PublishFile(String testcaseName, String instanceType, String transportType, String numberOfTimes, String[] exampleTags) 第 179 行 RoboticsRegressionFeature.PublishFile_ABTesting_IoTHub()

【问题讨论】:

    标签: c# visual-studio azure specflow azure-iot-hub


    【解决方案1】:

    您可能会遇到此处报告的以下问题: https://github.com/Azure/azure-iot-sdk-csharp/issues/259

    请检查您正在使用的 .NET 版本或查看是否指定了解决方法 “labiraus 于 2017 年 12 月 23 日发表评论” 上述链接也可以帮助您解决问题。

    【讨论】:

    • 看起来很相似。需要分析确认。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多