简体   繁体   中英

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

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

'sourceData.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

The stack trace was as below. The test is run using Specflow.

Message: Test method RoboticsRegressionTests.Feature.RoboticsRegressionFeature.PublishFile_ABTesting_IoTHub threw exception: System.NullReferenceException: Object reference not set to an instance of an object.

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 () 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()

You may be hitting the following issue reported here: 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 on the above link can help your case as well.指定的解决方法是否也能帮助您解决问题。

hth

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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