首页 > 解决方案 > 上传到 azure blob 失败并出现异常

问题描述

我尝试上传文件如下

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);
            }
        }

然后从其他条件调用下面的方法,如上面的方法

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, Func 3 modifyRequestMessageAsync, Func2 isSuccessful, Func 3 processResponseMessageAsync, IDictionary2 errorMappingOverrides, CancellationToken cancelToken) HttpClientHelper.PostAsync[T1,T2](Uri requestUri, T1 entity, IDictionary2 errorMappingOverrides, IDictionary2 customHeaders, CancellationToken cancelToken) HttpTransportHandler.UploadToBlobAsync(String blobName, Stream source) DataAccessService.UploadFileThroughIoTHub(Guid objectId, FileInfo file, TransportType transportType) line 592 RoboticsRegressionStepDefinition.UploadFiles(String instanceType, String transportType, Int32 numberOfFiles) line 873 <b__0>d .MoveNext() 第 32 行 --- 从先前引发异常的位置结束堆栈跟踪 --- <b__0>d.MoveNext() --- 从先前引发异常的位置结束堆栈跟踪 --- ExclusiveSynchronizationContext。 BeginMessageLoop() 第 125 行 AsyncHelpers.RunSync[T](Func`1 任务) 第 72 行 BindingInvoker.InvokeBinding(IBinding binding, IContextManager contextManager, Object[] arguments, ITestTracer testTracer, TimeSpan&持续时间)第 49 行 TestExecutionEngine.ExecuteStepMatch(BindingMatch 匹配,对象 [] 参数)第 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()PublishFile(String testcaseName, String instanceType, String transportType, String numberOfTimes, String[] exampleTags) 第 179 行 RoboticsRegressionFeature.PublishFile_ABTesting_IoTHub()PublishFile(String testcaseName, String instanceType, String transportType, String numberOfTimes, String[] exampleTags) 第 179 行 RoboticsRegressionFeature.PublishFile_ABTesting_IoTHub()

标签: c#visual-studioazurespecflowazure-iot-hub

解决方案


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

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

hth


推荐阅读