Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Newtonsoft.Json dependency issues #422

Closed
clydewallace opened this issue May 8, 2018 · 49 comments
Closed

Newtonsoft.Json dependency issues #422

clydewallace opened this issue May 8, 2018 · 49 comments
Labels
type: non-library issue API issue not solvable via the SDK

Comments

@clydewallace
Copy link

clydewallace commented May 8, 2018

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

To reproduce, simply install twilio via nuget after newtonsoft is already installed because you will most certainly have a more updated version of newstonsoft.

Exception/Log

   at Twilio.Clients.TwilioRestClient.ProcessResponse(Response response)
   at Twilio.Clients.TwilioRestClient.Request(Request request)
   at Twilio.Rest.Api.V2010.Account.MessageResource.Create(CreateMessageOptions options, ITwilioRestClient client)
   at Twilio.Rest.Api.V2010.Account.MessageResource.Create(PhoneNumber to, String pathAccountSid, PhoneNumber from, String messagingServiceSid, String body, List`1 mediaUrl, Uri statusCallback, String applicationSid, Nullable`1 maxPrice, Nullable`1 provideFeedback, Nullable`1 validityPeriod, String maxRate, Nullable`1 forceDelivery, String providerSid, ContentRetentionEnum contentRetention, AddressRetentionEnum addressRetention, Nullable`1 smartEncoded, ITwilioRestClient client)
   

Steps to Reproduce

Feature Request

If this is a feature request, make sure you search Issues for an existing
request before creating a new one!

@rheldt
Copy link

rheldt commented May 30, 2018

Having same issue here using Newtonsoft Json v10.0.3. Was already in a project that I added Twilio to.

@pdcmagno
Copy link

Hi.

I am having this issue as well. Newtonsoft v9.0.1 is installed together with Twilio, and this error occurred. I tried downgrading Newtonsoft and Twilio to different versions but still having the error.

Anyone knows how to fix this?

@aussiealf
Copy link

I am in the same boat, Doesn't matter what is in the bindingRedirect from Nuget in the app.config it still displays this error. It is like Twilio is somehow finding an old version of newtonsoft.json to load.

@dsghi
Copy link

dsghi commented Jul 31, 2018

Can you provide more details of your app and environment?

@aussiealf
Copy link

In my case I am using Twilio for 2FA to send SMS tokens. I have recently updated my Nuget packages which now has Newtonsoft.Json v11 installed, there is a bindingRedirect in my app.config and in deployment the the app.config is correctly call .exe.config and is being used as I have other settings in there that my app is seeing.

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Cors" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.IdentityModel.Tokens.Jwt" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.IdentityModel.Tokens" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

Other packages that depend on Newtonsoft.Json such as Owin, SignalR are working OK, so not sure why Twilio is specifically looking for 9.

I have checked in my references and ensured all references have Specific Version = False, and in the application path only 1 DLL for Newtonsoft.Json is there which is 11.

Error occurred on server: FileLoadException
Error in SendUserAuthToken: Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
at Twilio.Clients.TwilioRestClient.ProcessResponse(Response response)
at Twilio.Clients.TwilioRestClient.Request(Request request)
at Twilio.Rest.Api.V2010.Account.MessageResource.Create(CreateMessageOptions options, ITwilioRestClient client)
at Twilio.Rest.Api.V2010.Account.MessageResource.Create(PhoneNumber to, String pathAccountSid, PhoneNumber from, String messagingServiceSid, String body, List1 mediaUrl, Uri statusCallback, String applicationSid, Nullable1 maxPrice, Nullable1 provideFeedback, Nullable1 validityPeriod, String maxRate, Nullable1 forceDelivery, String providerSid, ContentRetentionEnum contentRetention, AddressRetentionEnum addressRetention, Nullable1 smartEncoded, ITwilioRestClient client)
at Expand.Communication.SMS.SMSClient.SendSMS(UnitOfWork Session, String To, String Body, String AuditBody)
at Expand.Security.Authentication.AuthenticationTokenModule.SendUserAuthToken(User User)
at Expand.Communication.Services.CoreService.SendUserAuthToken(String Username)

@aussiealf
Copy link

This is the same as #431

@aussiealf
Copy link

Same as #405

@dprothero
Copy link
Contributor

Does someone have a .csproj they could share with us that reproduces the issue?

@dsghi
Copy link

dsghi commented Jul 31, 2018

What version of VS and .net? I've never had an issue using the latest version of Newtonsoft.Json in my projects, I've upgraded a few of them more than once... this is the whole point of binding redirects, if you have multiple versions present, you specify which your application uses.

Perhaps you're running into an issue with automatic binding? Note that automatic redirection does not modify the source app.config so essentially you wouldn't see it. https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/how-to-enable-and-disable-automatic-binding-redirection

@dsghi
Copy link

dsghi commented Jul 31, 2018

I can reproduce the error if I manually edit my .csproj reference to version 9... with 11 installed..

    <Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
      <HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
    </Reference>

when it should be

    <Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
      <HintPath>..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
    </Reference>

@aussiealf
Copy link

aussiealf commented Jul 31, 2018

it is strange, in my case all on my proj files have

    <Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
      <HintPath>..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
      <SpecificVersion>False</SpecificVersion>
    </Reference>

This is my Twilio reference

    <Reference Include="Twilio, Version=5.14.1.0, Culture=neutral, processorArchitecture=MSIL">
      <HintPath>..\packages\Twilio.5.14.1\lib\net451\Twilio.dll</HintPath>
      <SpecificVersion>False</SpecificVersion>
    </Reference>

@aussiealf
Copy link

OK so I have created a new project added in SignalR to have a reference to Newtonsoft 11 already in my project, then added Twilio and setup a quick test, shockingly it works fine... :( so agreed @dsghi there is something happening somewhere.

I know in my case I also removed the Twilio.Signed package and replaced it with Twilio (as I am not doing Strongly Typed Signed assemblies anymore.

So I will keep going through my project references and try and work out what is happening.

The plot thickens

@dsghi
Copy link

dsghi commented Jul 31, 2018

Good luck!

@mnoreen
Copy link

mnoreen commented Aug 24, 2018

So is there an answer here? I have several C# console apps and a website (VS2017, .NET 4.7.1, C#). When I let Nuget update my package references, this happens as the original poster indicates. In the past, I've had to go back to the old version of Newtonsoft, but this strikes me as a problem with the Twilio DLL, and there ought to be a better solution then having a bunch of assemblybindings littering everything up, or being held to old dependency.

"Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. "

@dprothero
Copy link
Contributor

We cannot reproduce the issue @mnoreen. Would you be able to share a full project with us that exhibits the behavior?

@mnoreen
Copy link

mnoreen commented Aug 27, 2018

I can recreate one (I've just gone through and reverted everything to "old" versions). However, I would say, you don't even need a "project" file. I have a .NET webforms-based website (targets the 4.7.1 framework and we use VS 2017 to manage it).

There is no project file there. There is a web.config. The nuget package manager pulls in the latest DLLs, then updates the web config with the assembly bindings that aussiealf mentions earlier in this thread.

I have a page that allows us to send an SMS message out using Twilio. When I let the nuget package manager update everything, it throws the exception that is the subject of this thread. When I revert back to the old Newtonsoft (and other dependent dlls), and yank out the assembly bindings, it works. Pretty cut and dry.

Same thing happened the last time I tried to update to the latest Twilio dll. I'm just getting concerned about having some very old DLL dependencies.

@dprothero
I just created a brand new console app, used nuget to add Twilio and its dependencies. When I compiled it, it complained about the same thing. I can upload it, but would first need to remove our Account SID and Token... it should be pretty obvious where to substitute in your own.

@mnoreen
Copy link

mnoreen commented Aug 27, 2018

@dprothero

Here is the console app I created today the exhibits the problematic behavior. When I build it, I get the following in the Output window:

>------ Rebuild All started: Project: TwilioTest, Configuration: Debug Any CPU ------
1>  No way to resolve conflict between "Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" and "Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed". Choosing "Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" arbitrarily.
1>  Consider app.config remapping of assembly "Microsoft.IdentityModel.Tokens, Culture=neutral, PublicKeyToken=31bf3856ad364e35" from Version "5.1.2.0" [] to Version "5.2.4.0" [C:\dev\SolutionFiles\IBitsApps\packages\Microsoft.IdentityModel.Tokens.5.2.4\lib\net451\Microsoft.IdentityModel.Tokens.dll] to solve conflict and get rid of warning.
1>  Consider app.config remapping of assembly "Newtonsoft.Json, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" from Version "10.0.0.0" [] to Version "11.0.0.0" [C:\dev\SolutionFiles\IBitsApps\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll] to solve conflict and get rid of warning.
1>  Consider app.config remapping of assembly "System.IdentityModel.Tokens.Jwt, Culture=neutral, PublicKeyToken=31bf3856ad364e35" from Version "5.1.2.0" [] to Version "5.2.4.0" [C:\dev\SolutionFiles\IBitsApps\packages\System.IdentityModel.Tokens.Jwt.5.2.4\lib\net451\System.IdentityModel.Tokens.Jwt.dll] to solve conflict and get rid of warning.
1>C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(2110,5): warning MSB3276: Found conflicts between different versions of the same dependent assembly. Please set the "AutoGenerateBindingRedirects" property to true in the project file. For more information, see http://go.microsoft.com/fwlink/?LinkId=294190.
1>  TwilioTest -> C:\dev\IBits\ConsoleApps\TwilioTest\bin\Debug\TwilioTest.exe
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

TwilioTest.zip

I haven't been able to track all the details down yet, but there's something about the "Auto-generate binding redirects" checkbox (go to project properties, then the Application tab). Checking that box, the build warnings go away. I have no app.config, so I'm not sure what that did. Does rebuilding somehow change what gets compiled into the .exe.?

I'm beginning to wonder if there's some issue with nuget, app.configs, and some other hidden VS settings... Once I get things working and released into production, I'll try to do some more testing...

@dprothero
Copy link
Contributor

@mnoreen Probably in the .csproj file. I will take a look at this.

@dprothero
Copy link
Contributor

@mnoreen Your project definitely reproduces the issue. It's possible there's some kind of conflict between the version of Newtonsoft.Json package that Twilio requires and one of the Microsoft Identity libraries requirement. We will continue to research.

In the meantime, the workaround is to definitely to enable Automatic Binding Redirection in your csproj files: https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/how-to-enable-and-disable-automatic-binding-redirection#enabling-automatic-binding-redirects-manually

@dprothero
Copy link
Contributor

Here's a quick way to fix your existing projects that have this issue: In Visual Studio, open the Package Manager Console (Tools... NuGet Package Manager... Package Manager Console) and run the following command: Get-Project –All | Add-BindingRedirect

@aussiealf
Copy link

Im glad you got a repro project, I tried but couldn't repro on a fresh project.

Out of interest David, could it have something to do with the comment I made about the Twilio proj file

Currently the Twilio package versioning has [9.0.1) which I believe means it will only use Newtonsoft 9 and all minors, but no newer majors. As per https://docs.microsoft.com/en-us/nuget/reference/package-versioning

The only reason why I dont think this is it is the fact that this is purely a Nuget config issue, so we shouldn't be getting a FileLoad error in our .NET app cause this wouldn't look at the Nuget environment anyway. The thing that gets me is that I have the binding redirect there but it doesn't seem to adhere to that binding.

@dprothero
Copy link
Contributor

@aussiealf I believe [9.0.1) is equivalent to just 9.0.1. Someone here changed it recently in an attempt to fix this issue, but it has no observable effect. Both just mean "at least v9.0.1 or higher". It's not restricted to just minors.

I believe the root of the problem is when you have multiple packages that have different versions of JSON.NET required and the only way to solve that is with binding redirects. We don't normally run into these because automatic binding redirects is typically turned on by default.

@mnoreen
Copy link

mnoreen commented Jun 13, 2019

I was wondering if there was anymore discussion / resolution to this. For some reason, I decided to give Twilio another shot. I have a C# .NET class library with Newtonsoft.Json already added to it (12.02, latest rev as of now). I used nuget to add Twilio (5.30.0).

My class library DLL wraps up a bunch of boilerplate code so my console app basically just has to call a simple .Send() method.

I still get an exception thrown when the class library calls MessageResource.Create():

"Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0"

Oddly enough, the SMS text message is sent to my cell phone, I just also get the exception in my code:

Exception particulars include:

InnerException: null

Message: "Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified."

Source: "Twilio"

StackTrace:  "   at Twilio.Clients.TwilioRestClient.ProcessResponse(Response response) at Twilio.Rest.Api.V2010.Account.MessageResource.Create(CreateMessageOptions options, ITwilioRestClient client) at Twilio.Rest.Api.V2010.Account.MessageResource.Create(PhoneNumber to, String pathAccountSid, PhoneNumber from, String messagingServiceSid, String body, List`1 mediaUrl, Uri statusCallback, String applicationSid, Nullable`1 maxPrice, Nullable`1 provideFeedback, Nullable`1 validityPeriod, Nullable`1 forceDelivery, Nullable`1 smartEncoded, String interactiveData, Nullable`1 forceOptIn, ITwilioRestClient client) at [myclasslib].SMS.sendTwilio() in [path-to-myclaslib]\\SMS.cs:line 99 at [myclasslib].SMS.Send(List`1 mobileNumberList, String msg) in [path-to-myclaslib]\\SMS.cs:line 53"
TargetSite: {Twilio.Http.Response ProcessResponse(Twilio.Http.Response)}

@rheldt
Copy link

rheldt commented Jun 13, 2019

@mnoreen are you using the Nuget library, or do you have the source in your solution?

@mnoreen
Copy link

mnoreen commented Jun 13, 2019

@rheldt I used nuget to add the "Twilio REST API helper library" (v 5.30.0)

@rheldt
Copy link

rheldt commented Jun 13, 2019

@mnoreen I ended up resolving this by dropping the Twilio source in my solution rather than using the Nuget library. That lets me use the same version of Json.Net across the solution. No, it's not ideal, but it works nicely. Alternatively, you could downgrade to Json.Net version 10 in your solution and use the Nuget library. See if that works?

@mnoreen
Copy link

mnoreen commented Jun 13, 2019

@rheldt Yes, I did downgrade Json.Net to v10 and it did work. I just think this seems to be a long standing "issue"...?

When you say "dropping the Twilio source in my solution..." could you elaborate? I'm not sure I quite follow, but I like where you going with it! I would like to have the same version of Json.Net across my solution (as I have a large number of console apps that rely on my core/common class lib).

@rheldt
Copy link

rheldt commented Jun 13, 2019

@mnoreen You'd need to download the source:
github.com/twilio/twilio-csharp/tree/master/src/Twilio

Include that project in your solution. Then, add references to your other project(s) that needs Twilio.

You will probably also need to add a few Nuget libraries. I'm using the following, but YMMV:
Newtonsoft.Json
Microsoft.IdentityModel.JsonWebTokens
Microsoft.IdentityModel.Logging
Microsoft.IdentityModel.Tokens
System.IdentityModel.Tokens.Jwt

@Andy1986ios
Copy link

@rheldt Ah! I get it now :) For now, I've just downgraded my reference to Newtonsoft.Json 10x.

Does it seem "odd" that you can add the source code and get your solution to work, but adding the already compiled DLL creates the problem behavior? You'd think it would be the same thing...

Just my .02: I appreciate that it's open source and here on GitHub. But... it's a commerical, for profit, product/service. You'd think there would be more support and activity here to create a nice clean .NET library.

Thanks for your help.

@rheldt Ah! I get it now :) For now, I've just downgraded my reference to Newtonsoft.Json 10x.

Does it seem "odd" that you can add the source code and get your solution to work, but adding the already compiled DLL creates the problem behavior? You'd think it would be the same thing...

Just my .02: I appreciate that it's open source and here on GitHub. But... it's a commerical, for profit, product/service. You'd think there would be more support and activity here to create a nice clean .NET library.

Thanks for your help.

@mnoreen You'd need to download the source:
github.com/twilio/twilio-csharp/tree/master/src/Twilio

Include that project in your solution. Then, add references to your other project(s) that needs Twilio.

You will probably also need to add a few Nuget libraries. I'm using the following, but YMMV:
Newtonsoft.Json
Microsoft.IdentityModel.JsonWebTokens
Microsoft.IdentityModel.Logging
Microsoft.IdentityModel.Tokens
System.IdentityModel.Tokens.Jwt

@NagarajAdepu
Copy link

Try renaming the Newtonsoft.Json.dll from below locations and rebuild your project.

Visual studio actually looks for Newtonsoft.Json.dll from below locations by default.

C:\Program Files\Microsoft SDKs\Azure.NET SDK\v2.9\bin\plugins\Diagnostics

C:\Program Files\Microsoft SDKs\Azure.NET SDK\v2.9\ToolsRef

C:\Program Files (x86)\MSBuild\Microsoft\NuGet

C:\Program Files (x86)\Common Files\microsoft shared\VsHub\1.0.0.0\lib

C:\Program Files\IIS\Microsoft Web Deploy V3

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Blend

@thinkingserious
Copy link
Contributor

Hello @clydewallace, @mnoreen,

I'm checking in to find out if folks are still having an issue with the latest version of this helper library.

I was not able to reproduce the issue utilizing the following steps:

  • Using Visual Studio 2019 Community Edition
  • Created new Console App (.NET Core)
  • Added latest version of Newtonsoft as a dependency (12.0.3) via Nuget
  • Added Twilio (5.38.0) via Nuget

With best regards,

Elmer

@thinkingserious thinkingserious added status: waiting for feedback waiting for feedback from the submitter type: question question directed at the library and removed difficulty: easy fix is easy in difficulty status: help wanted requesting help from the community type: bug bug in the library labels Mar 21, 2020
@mnoreen
Copy link

mnoreen commented Mar 23, 2020

@thinkingserious I just went through the process of giving this another go around...

I have two large Visual Studio solutions, one that contains a bunch of console apps and one asp.net website (webforms), all targeting .NET Framework 4.8. In both, I used nuget to update package references:

Twilio
5.31.2 -> 5.38.0

Newtonsoft.Json
10.0.3 -> 12.0.3

Unfortunately for me... the problem persists... specifically with the asp.net website. As soon as I call the MessageResource.Create() method, it throws an exception:

"Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. … "

Again, the "odd thing" (although ALL of this is odd to me!) is that it SMS message does get sent (I got the text message on my iPhone); the MessageResource.Create() method "worked" but also threw that exception, so as far as my code knows, it didn't work...

I used nuget to go back to Newtonsoft.Json 10.0.3 and it works with no exceptions again.

@thinkingserious
Copy link
Contributor

Hello @mnoreen,

I was unable to reproduce the error in a Windows Forms App (.NET Framework) app.

Here are the steps I followed:

  1. Install .NET 4.8 Developer Pack
  2. Create a new project using the Windows Forms App (.NET Framework) template, setting the target framework to .NET 4.8
  3. Added latest version of Newtonsoft as a dependency (12.0.3) via Nuget
  4. Added Twilio (5.38.0) via Nuget
  5. Added a single button in the Form Designer, double clicked the button to create a click event handler and utilized the following code:
private void ButtonSendSMS_Click(object sender, EventArgs e)
{
    var twilioAccountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
    var twilioAuthToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
    TwilioClient.Init(twilioAccountSid, twilioAuthToken);

    MessageResource.Create(
        new PhoneNumber(Environment.GetEnvironmentVariable("MY_PHONE_NUMBER")),
        from: new PhoneNumber(Environment.GetEnvironmentVariable("TWILIO_PHONE_NUMBER")),
        body: "Hello World!"
    );
}
  1. Ran the program and clicked the button. SMS received without error.

Could you please let me know if I'm missing anything with respect to duplicating your development environment?

With best regards,

Elmer

@mnoreen
Copy link

mnoreen commented Mar 23, 2020

@thinkingserious
As mentioned... we have an asp.net webforms website, not a winforms app. The website is asp.net webforms, targeting .NET Framework 4.8.

It seems to work ok in my console apps, even without binding redirects. But not the asp.net website w/out dropping back to the older version of Newtonsoft.Json.

@thinkingserious
Copy link
Contributor

Hi @mnoreen,

I have attempted to re-create the issue with the proper project type.

For this test, I used the ASP.NET Web Application (.NET Framework) template and selected Web Forms as the project type with a target of .NET Framework 4.8. (Is that the correct project template?)

Newtonsoft.json version 12.0.2 was pre-installed, so I bumped it to 12.0.3 and then installed Twilio 5.38.0 via Nuget.

I then added the following code to Global.asax.cs:

void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    var twilioAccountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
    var twilioAuthToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
    TwilioClient.Init(twilioAccountSid, twilioAuthToken);

    MessageResource.Create(
        new PhoneNumber(Environment.GetEnvironmentVariable("TWILIO_PHONE_NUMBER")),
        from: new PhoneNumber(Environment.GetEnvironmentVariable("TWILIO_PHONE_NUMBER")),
        body: "Hello World!"
    );
}

When I run the app (it launched in the web browser), I receive the SMS without error.

Perhaps I'm not looking in the right place for the error or my settings are less stringent than yours. In what window are you seeing the exception? Also, in the Exception Settings tab, you may have checked off more items in the Break When Thrown than I have.

With best regards,

Elmer

@mnoreen
Copy link

mnoreen commented Mar 24, 2020

@thinkingserious

Unfortunately, no that's not quite the same environment. That's a web APPLICATION project, not a website.

I was able to completely reproduce this by starting "from scratch."

  • I used VS 2017 to make sure it created a webforms website, not a web application. I created an Empty webforms site.

  • I used nuget to add Twilio and dependencies. Made sure all dependencies were "latest stable" versions.

  • created a single page with a button on it. On the button click, I have dirt simple code to do the MessageCreate().

Ran the website, clicked the button, and bam. Exception as per usual. I ran it through the debugger and as soon as it stepped over the Create() method, I got the text message on my iPhone and the exception was thrown.

I don't know how to make it any more straightforward than that.

`
public string sendTwilio()
{
var responses = new List();

    TwilioClient.Init(TwilioStuff.AccountSID, TwilioStuff.AccountToken);

    try
    {
        MessageResource smsResult = MessageResource.Create(
            from: new PhoneNumber(TwilioStuff.FromNumber),
            to: new PhoneNumber(TwilioStuff.ToNumber),
            body: "Hello world test from Twilio"
            );

        string s = String.Format("SMS: Direction: {0} | Status: {1} | SID: {2} | ErrorCode: {3} | ErrorMessage: {4} "
            , smsResult.Direction, smsResult.Status, smsResult.Sid, smsResult.ErrorCode, smsResult.ErrorMessage);

        responses.Add(s);

    }
    catch (ApiException ex)
    {
        // rethrow Twilio exception
        throw ex;
    }


    if (responses.Count == 0)
        responses.Add("no SMS response");


    return String.Join("<br /", responses);
}

`

@mnoreen
Copy link

mnoreen commented Mar 24, 2020

@thinkingserious
Here is the website I created and reproduces the experience of the throwing the Exception:

System.IO.FileLoadException HResult=0x80131040 Message=Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) Source=Twilio StackTrace: at Twilio.Clients.TwilioRestClient.ProcessResponse(Response response) at Twilio.Clients.TwilioRestClient.Request(Request request) at Twilio.Rest.Api.V2010.Account.MessageResource.Create(CreateMessageOptions options, ITwilioRestClient client) at Twilio.Rest.Api.V2010.Account.MessageResource.Create(PhoneNumber to, String pathAccountSid, PhoneNumber from, String messagingServiceSid, String body, List1 mediaUrl, Uri statusCallback, String applicationSid, Nullable1 maxPrice, Nullable1 provideFeedback, Nullable1 validityPeriod, Nullable1 forceDelivery, ContentRetentionEnum contentRetention, AddressRetentionEnum addressRetention, Nullable1 smartEncoded, List1 persistentAction, ITwilioRestClient client)
at _Default.sendTwilio() in C:\Users\margo.noreen\source\repos\TwilioTest\TwilioTestWeb\Default.aspx.cs:line 31
at _Default.btnTestTwilio_Click(Object sender, EventArgs e) in C:\Users\margo.noreen\source\repos\TwilioTest\TwilioTestWeb\Default.aspx.cs:line 20
TwilioTestWeb.zip
`

In the App_Code directory, I created class to hold the "constants" for the Account SID and Token values as well as my "to" and "from" phone numbers. Before I zipped up this code, I replaced those with junk values, but that should be pretty obvious.
TwilioTestWeb.zip

@thinkingserious
Copy link
Contributor

Hello @mnoreen,

Thanks for the additional detail! It turns out that the template for creating an empty ASP.NET Web Site was removed in Visual Studio 2019 and can be installed via these instructions. After downloading and installing that template, I executed the following steps:

  1. Created ASP.NET Empty Web Site targeting .NET Framework 4.8
  2. Added latest version of Newtonsoft as a dependency (12.0.3) via Nuget
  3. Added Twilio (5.38.0) via Nuget
  4. Migrated code from TwilioTestWeb.zip
  5. Ran code, launched in browser (Firefox) and clicked the "Test Twilio" button.
  6. SMS received with no error raised in Visual Studio
  7. The message I see in the browser is SMS: Direction: outbound-api | Status: queued | SID: SMXXXXXXXXXXXXXXXX | ErrorCode: | ErrorMessage:

Could you please review the steps above and please note where I diverged from your setup?

Thanks!

@mnoreen
Copy link

mnoreen commented Mar 25, 2020

@thinkingserious As you can imagine, things are bit crazy right now. It might take a few days before I can get back to this. But while I have you... does this mean that you think the issue is closed? I'm a bit concerned that this issue isn't being taken seriously enough to debug. I appreciate your attention the last couple of days, really! But this has been raised on and off for... years now?! Just concerned about what the message for developer support is.

@thinkingserious
Copy link
Contributor

Hello @mnoreen,

I have not closed the issue because you are still experiencing the exception.

My next goal for this issue is to reproduce the exception locally.

I believe it could be a setting in Microsoft Visual Studio 2017, that I'm not seeing on my end, effecting the build. Perhaps the next step is to attempt to reproduce the exception within the Microsoft Visual Studio 2017 environment vs. 2019.

Thanks!

@thinkingserious
Copy link
Contributor

@mnoreen,

At the Visual Studio download page I see two versions of Visual Studio Community 2017 (15.0 and 15.9). Could you please verify which one you have? Thanks!

@mnoreen
Copy link

mnoreen commented Mar 25, 2020

@mnoreen,
At the Visual Studio download page I see two versions of Visual Studio Community 2017 (15.0 and 15.9). Could you please verify which one you have? Thanks!

15.9.21

We have the Professional version, not Community. And we tend to keep up with Microsoft's updates. This website of ours was originally created in much older versions of VS. Not sure why it would matter, but I could believe there's something to it. It's files.

I get the exception when I run our original website on my localhost in vs2017 or vs2019. It also occurs when running on our development and test web servers (full Windows Server 2016, full IIS, no VS).

When I get more time I can try running that small prototype I uploaded earlier in VS2019, and also on our dev and test servers.

Thx!

@thinkingserious
Copy link
Contributor

Ah, given you can reproduce in vs2019, I'll await your prototype for further testing. Thank you!

@mnoreen
Copy link

mnoreen commented Mar 25, 2020

@thinkingserious
I can run that test website both in VS2017 and VS2019 and get the exact same result*, and I guess that at least makes sense to me. I don't think (I guess I just don't see how) it's a VS issue, especially since it happens when I run it on a server w/ IIS as well as my localhost and iisexpress. It's an assembly binding issue. I'm not necessarily an expert at that, but it just seems, given the exception, that the twilio DLL is tied explicitly to that version. Other .NET libraries I've used seem to happily coexist with a base OR later version of a dependency.

*Result is:

  • SMS/text message IS actually sent by the .Create() method (I receive it on my iPhone)
  • the exception "Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0 …" is thrown

When I let the exception be rethrown (w/out capturing it first), I also noticed an Assembly Load Trace section that may help:

=== Pre-bind state information ===
LOG: DisplayName = Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
 (Fully-specified)
LOG: Appbase = file:///C:/Users/margo.noreen/source/repos/TwilioTest/TwilioTestWeb/
LOG: Initial PrivatePath = C:\Users\margo.noreen\source\repos\TwilioTest\TwilioTestWeb\bin
Calling assembly : Twilio, Version=5.38.0.0, Culture=neutral, PublicKeyToken=null.
===

@mnoreen
Copy link

mnoreen commented Mar 26, 2020

@thinkingserious
I made a stab at running the Microsoft Assembly Binding Log Viewer; then reran my test page. I'm attaching the results. I've not really delved that deep into .NET library building and how the runtime loads assemblies based on the code in a website, but I am hoping the Twilio team can make the effort to do so.
fuslogvwr and stack trace.zip

To my eye, it appears that when I run my test page, the Newtonsoft.Json library that is loaded is the the v12 version. That seems "correct" to me since that's what is in my websites Bin folder. But then, when I call the twilio method that in turns calls a Newtoonsoft.Json method, the exception is thrown because for some reason it explicitly wants the v10 version.

Hopefully you will be able to discern more and come up with a resolution.

Thanks!

@thinkingserious
Copy link
Contributor

@mnoreen,

Can you please tell me which other .NET libraries (particularly open source ones) you have used that don't exhibit this issue? I want to do some comparisons on how those projects are defining dependencies to Newtonsoft.json. Thanks!

@childish-sambino
Copy link
Contributor

@mnoreen I was able to recreate the issue you're seeing in VS2019 using the sample project you provided. But I'll defer to the comment here for why this is happening: #431 (comment)

High-level, binding redirects are required to avoid this issue and VS is able to help out. Just by upgrading the Twilio package version using NuGet in your sample project it added the appropriate binding redirects and the issue went away. I don't see anything we can/should do in this repo to alleviate the issue as it's core to .NET

@childish-sambino childish-sambino added type: non-library issue API issue not solvable via the SDK and removed status: waiting for feedback waiting for feedback from the submitter type: question question directed at the library labels Jul 30, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: non-library issue API issue not solvable via the SDK
Projects
None yet
Development

No branches or pull requests