简体   繁体   English

上传到 azure blob 失败,但有异常

[英]Upload to azure blob fails with exception

I tried uploading file as below我尝试上传文件如下

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

Then the below method is called from else condition as in above method然后从上面的方法中的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);
            }
        }

The code to create device client as below创建设备客户端的代码如下

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

While debugging one of the sourceData property from ' UploadFileThroughIoTHub ' method comes as below在调试来自“ UploadFileThroughIoTHub ”方法的sourceData属性之一时,如下所示

'sourceData.ReadTimeout' threw an exception of type 'System.InvalidOperationException' “sourceData.ReadTimeout”引发了“System.InvalidOperationException”类型的异常

The stack trace was as below.堆栈跟踪如下。 The test is run using Specflow.该测试使用 Specflow 运行。

Message: Test method RoboticsRegressionTests.Feature.RoboticsRegressionFeature.PublishFile_ABTesting_IoTHub threw exception: System.NullReferenceException: Object reference not set to an instance of an object.消息:测试方法 RoboticsRegressionTests.Feature.RoboticsRegressionFeature.PublishFile_ABTesting_IoTHub 抛出异常: System.NullReferenceException:未将对象引用设置为对象的实例。

Stack Trace: IAuthorizationProvider.GetPasswordAsync() HttpClientHelper.ExecuteAsync(HttpMethod httpMethod, Uri requestUri, Func 3 modifyRequestMessageAsync, Func 2 isSuccessful, Func 3 processResponseMessageAsync, IDictionary 2 errorMappingOverrides, CancellationToken cancellationToken) HttpClientHelper.PostAsync[T1,T2](Uri requestUri, T1 entity, IDictionary 2 errorMappingOverrides, IDictionary 2 customHeaders, CancellationToken cancellationToken) 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() line 32 --- End of stack trace from previous location where exception was thrown --- <b__0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- ExclusiveSynchronizationContext.BeginMessageLoop堆栈跟踪: IAuthorizationProvider.GetPasswordAsync() HttpClientHelper.ExecuteAsync(HttpMethod httpMethod, Uri requestUri, Func 3 modifyRequestMessageAsync, Func 2 isSuccessful, Func 3 processResponseMessageAsync, IDictionary 2 errorMappingOverrides, CancellationToken cancelationToken) HttpClientHelper.PostAsync[T1,T1 requestUri,T1 requestUri entity, IDictionary 2 errorMappingOverrides, IDictionary 2 customHeaders, CancellationToken cancelationToken) HttpTransportHandler.UploadToBlobAsync(String blobName, Stream source) DataAccessService.UploadFileThroughIoTHub(Guid objectId, FileInfo file, TransportType transportType) line 592 RoboticsRegressionStepDefinition(transportTypeStringType,StringTypeFiles,TransportType,StringType3tFiles) ) 第 873 行 <b__0>d.MoveNext() 第 32 行 --- 从上一个抛出异常的位置开始的堆栈跟踪结束 --- <b__0>d.MoveNext() --- 从上一个异常位置开始的堆栈跟踪结束被抛出 --- ExclusiveSynchronizationContext.BeginMessageLoop () line 125 AsyncHelpers.RunSync[T](Func`1 task) line 72 BindingInvoker.InvokeBinding(IBinding binding, IContextManager contextManager, Object[] arguments, ITestTracer testTracer, TimeSpan& duration) line 49 TestExecutionEngine.ExecuteStepMatch(BindingMatch match, Object[] arguments) line 395 TestExecutionEngine.ExecuteStep(IContextManager contextManager, StepInstance stepInstance) line 316 TestExecutionEngine.OnAfterLastStep() line 132 RoboticsRegressionFeature.ScenarioCleanup() RoboticsRegressionFeature.PublishFile(String testcaseName, String instanceType, String transportType, String numberOfTimes, String[] exampleTags) line 179 RoboticsRegressionFeature.PublishFile_ABTesting_IoTHub() () 第 125 行 AsyncHelpers.RunSync[T](Func`1 任务) 第 72 行 BindingInvoker.InvokeBinding(IBinding binding, IContextManager contextManager, Object[] arguments, ITestTracer testTracer, TimeSpan& duration) 第 49 行 TestExecutionEngine.ExecuteStepMatch(BindingMatch match, 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[] 示例第 179 行 RoboticsRegressionFeature.PublishFile_ABTesting_IoTHub()

You may be hitting the following issue reported here: https://github.com/Azure/azure-iot-sdk-csharp/issues/259您可能会遇到此处报告的以下问题: https : //github.com/Azure/azure-iot-sdk-csharp/issues/259

Please check the .NET version you are using or see if the workaround specified at "labiraus commented on Dec 23, 2017" on the above link can help your case as well.请检查您使用的 .NET 版本,或查看上述链接中“labiraus 于 2017 年 12 月 23 日评论”中指定的解决方法是否也能帮助您解决问题。

hth

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM