alpacahq/alpaca-trade-api-csharp

[BUG]: Single line using disposes HTTP request before it is used

artemiusgreat opened this issue · 2 comments

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

Connecting to trading client the same way as shown in the example
Then, trying to request any information from it, tried methods tradeClient.GetAssetAsync and tradeClient.GetAccountAsync, the result is the same, exception Variable value is not available because the module is optimized. Click the drop down for options..

image

Couldn't find a lot in google or github issues but after trying to debug the API library, it seems to get stuck here.
Which looks like variable request is being disposed by optimizer before it is actually used.

image

Expected Behavior

Perhaps, using multiline scoped using would be more reliable.

using (var request = ...) 
{
   return callAndDeserialize(...);
}

instead of

using (var request = ...); 
return callAndDeserialize(...);

Steps To Reproduce

No response

Environment

- SDK Version: 7.0.4
- OS (version, bitness): Windows 11, x64
- .NET SDK (version): .NET Core 7.0
- target process .NET version/bitness: x64

Anything else?

After thinking about this code, I'm not even sure if HttpRequestMessage really needs to be disposed.
Response may contain stream but disposing request seems unnecessary.

I have to admit that primarily it appeared to be my fault.
I was using Live credentials with Environment.Paper
After switching to Live, request goes through successfully.
Although, I was able to figure this out only when I switched from Nuget to locally included project Alpaca.Markets.
I guess, when Nuget was compiled for release, it somehow optimizes exception, so the error Request not authorized on the screen below is not displayed anywhere.

image

@artemiusgreat Yes, the NuGet package contains a release build with all optimizations applied and I think it's the best option for most use cases.

Exception handling settings in Visual Studio allows you to catch exceptions at the place where they are thrown, not just in your code, and most probably it's a root cause of this "unexpected" behavior. But you can always write your try/catch block and set a breakpoint inside to examine the real exception details.

The RestClientErrorException contains not only the original HTTP error code but also the Alpaca error code and message if they are provided in response.