Good morning
I am building package for Xamrin.Forms. I follow how its done by James Montenango
Here are some important pieces of my .csproj
<TargetFrameworks>netstandard2.0;MonoAndroid10.0;Xamarin.iOS10</TargetFrameworks>
<ItemGroup>
<Compile Include="**\*.shared.cs" />
</ItemGroup>
<ItemGroup Condition=" $(TargetFramework.StartsWith('netstandard')) ">
<PackageReference Include="XTricks.Shared" Version="1.0.1" />
<PackageReference Include="Xamarin.Essentials" Version="1.6.1" />
</ItemGroup>
<ItemGroup Condition=" $(TargetFramework.StartsWith('MonoAndroid')) ">
<PackageReference Include="Xamarin.Forms" Version="5.0.0.2196" />
<PackageReference Include="Xamarin.GooglePlayServices.Location" Version="118.0.0.1" />
<PackageReference Include="XTricks.Shared" Version="1.0.1" />
<PackageReference Include="Xamarin.Essentials" Version="1.6.1" />
<Compile Include="**\*.android.cs" />
</ItemGroup>
<ItemGroup Condition=" $(TargetFramework.StartsWith('Xamarin.iOS')) ">
<PackageReference Include="Xamarin.Essentials" Version="1.6.1" />
<PackageReference Include="XTricks.Shared" Version="1.0.1" />
<Compile Include="**\*.apple.cs" />
</ItemGroup>
Everything is working except one important thing.
I would like to have two implementation of the same class for Android and for iOS.
For this purpose I declare and interface as:
IMyService.shared.cs
And I create two classes, one in Android folder called:
MyService.android.cs which implements IMyService.shared.cs
and second in Apple folder called MyService.apple.cs.
Now as is done in above library I would like to use service in shared code.
private static IMyService Service
{
get
{
#if NETSTANDARD1_0 || NETSTANDARD2_0
return null;
#else
return new MyService(); // And this code is red one. MyService cannot be found.
#endif
}
}
Basically I am stucked there. Does anyone know how to move foward?
Make sure you have same namespace to MyService class with your shared codes and then you just build your library.
Related
I need to add a Unit Test in an existing Visual Studio solution with 100s of tests. I wrote a simple Unit Test only to check if it is working.
My test code is:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Training.UnitTests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Assert.AreEqual(1, 1);
}
}
}
The projects used in the Visual Studio solution are of **SDK-Style**. Now when I try to run all the tests, I found that some of the tests run and some of test do not run as shown in the screenshot below (including my newly added sample test).
I do not understand why some tests are running and some tests do not run at all in Visual Studio's Test Explorer. All of these tests run fine in the Azure DevOps pipeline. I even tried to run my sample test individually in Visual Studio by pressing Ctrl + R + T but the test only builds not run. But if
Following are the sample project files of the UnitTest projects which run and those wo do not run.
.csproj of a running Project
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\..\..\_Solution\build.defaults.targets" />
<PropertyGroup>
<TargetFramework>net472</TargetFramework>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<OutputPath>$(SolutionDir)SystemTests\$(Configuration)</OutputPath>
<AssemblyTitle>SystemTest</AssemblyTitle>
<DebugType>full</DebugType>
<LangVersion>8</LangVersion>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<Optimize>false</Optimize>
<DebugSymbols>true</DebugSymbols>
<AssemblyName>SystemTest.Bus</AssemblyName>
</PropertyGroup>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<ItemGroup>
<Reference Include="PresentationCore" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MSTest.TestAdapter" Version="$(MSTestTestAdapterNugetVersion)" />
<PackageReference Include="MSTest.TestFramework" Version="$(MSTestTestAdapterNugetVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftNETTestSdkNugetVersion)" />
<PackageReference Include="FluentAssertions" Version="$(FluentAssertionsNugetVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\UnitTestSetups.csproj" />
<ProjectReference Include="..\..\Bus.Impl.csproj" />
</ItemGroup>
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<Copy SourceFiles="..\..\..\..\_Solution\automation.runsettings" DestinationFolder="$(OutDir)" />
</Target>
</Project>
.csproj file of a NOT running project:
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="..\..\..\..\_Solution\build.defaults.targets" />
<PropertyGroup>
<TargetFramework>net472</TargetFramework>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<OutputPath>$(SolutionDir)\Tests\$(Configuration)</OutputPath>
<AssemblyTitle>Training.UnitTests</AssemblyTitle>
<LangVersion>8</LangVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="PresentationFramework" />
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="$(FluentAssertionsNugetVersion)" />
<PackageReference Include="Moq" Version="$(MoqNugetVersion)" />
<PackageReference Include="MSTest.TestAdapter" Version="$(MSTestTestAdapterNugetVersion)" />
<PackageReference Include="MSTest.TestFramework" Version="$(MSTestTestAdapterNugetVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftNETTestSdkNugetVersion)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Caliburn.Micro" Version="$(VcSimNugetVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Training.csproj" />
</ItemGroup>
</Project>
QUESTION: Why only some of the UnitTests are running in Visual Studio's Test Explorer? The test which do not run in VS run fine in Azure DevOps pipeline.
Comparing both csprojs, I noticed the one which contains the tests that are not running contains the following line:
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
I've checked a previous answer and I believed the above line was either in the wrong place or not being used, reason why I've first recommended removing it to validate my assumption. It turns out it was not being used and after removing, it solved your problem.
I am trying to get some values from the appsettings.json. But whatever I try with the AdditionalTextsProvider doesn't work. Here is my code
IncrementalValuesProvider<AdditionalText> textFiles = context.AdditionalTextsProvider.Where(static file => file.Path.Contains("appsettings.json")); // tried many things here, like EndsWith(".json") etc..
IncrementalValuesProvider<(string name, string content)> namesAndContents = textFiles.Select((text, cancellationToken) => (name: Path.GetFileNameWithoutExtension(text.Path), content: text.GetText(cancellationToken)!.ToString()));
context.RegisterSourceOutput(namesAndContents, (spc, nameAndContent) =>
{
nameAndContent.content; //always empty
nameAndContent.name; //always empty
});
From the other hand, when I implement the ISourceGenerator (same solution, same projects) this line of code just works!
var file = context.AdditionalFiles.FirstOrDefault(x => x.Path.Contains("appsettings.json"));
The project which is referencing the code generator:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.123" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Scrutor" Version="4.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\myproject\myproject.csproj" />
<ProjectReference Include="..\myproject.EFCore\myproject.EFCore.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Include="appsettings.json" />
</ItemGroup>
</Project>
Code generator project :
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <!-- Generates a package at build -->
<IncludeBuildOutput>false</IncludeBuildOutput> <!-- Do not include the generator as a lib dependency -->
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<!-- Generator dependencies -->
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" GeneratePathProperty="true" PrivateAssets="all" />
</ItemGroup>
<PropertyGroup> <GetTargetPathDependsOn>$(GetTargetPathDependsOn);GetDependencyTargetPaths</GetTargetPathDependsOn>
</PropertyGroup>
<Target Name="GetDependencyTargetPaths">
<ItemGroup>
<TargetPathWithTargetPlatformMoniker Include="$(PKGNewtonsoft_Json)\lib\netstandard2.0\Newtonsoft.Json.dll" IncludeRuntimeDependency="false" />
</ItemGroup>
</Target>
<ItemGroup>
<!-- Package the generator in the analyzer directory of the nuget package -->
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<!-- Package the props file -->
</ItemGroup>
</Project>
If you combine the additional text provider with the compilation it works for me (inspired by this great post):
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var files = context.AdditionalTextsProvider
.Where(a => a.Path.EndsWith("appsettings.json"))
.Select((a, c) => (Path.GetFileNameWithoutExtension(a.Path), a.GetText(c)!.ToString()));
var compilationAndFiles = context.CompilationProvider.Combine(files.Collect());
context.RegisterSourceOutput(compilationAndFiles, (productionContext, sourceContext) => Generate(productionContext, sourceContext));
}
void Generate(SourceProductionContext context, (Compilation compilation, ImmutableArray<(string, string)> files) compilationAndFiles)
{
//emit generated files...
}
Update:
Tested again with Visual Studio 17.4. and combination with compilation seems not to be necessary anymore. Generator is called as expected when appsettings.json changes with only AdditionalTextsProvider registered.
I have tried replicate but everything works for me.
I define my source generator as this
namespace ConsoleAppSourceGenerator
{
[Generator]
public class TxtGenerator : IIncrementalGenerator
{
private static int counter;
public void Initialize(IncrementalGeneratorInitializationContext initContext)
{
IncrementalValuesProvider<AdditionalText> textFiles = initContext.AdditionalTextsProvider
.Where(static file => file.Path.EndsWith(".txt"));
IncrementalValuesProvider<(string name, string content)> namesAndContents = textFiles
.Select((text, cancellationToken) => (name: Path.GetFileNameWithoutExtension(text.Path), content: text.GetText(cancellationToken)!.ToString()));
initContext.RegisterSourceOutput(namesAndContents, (spc, nameAndContent) =>
{
spc.AddSource($"TxtFile.{nameAndContent.name}.g.cs", $#"
// Counter {Interlocked.Increment(ref counter)}
public static partial class TxtFile
{{
public const string {nameAndContent.name} = ""{nameAndContent.content}"";
}}");
});
}
}
}
and source generator project as this
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>Latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" />
</ItemGroup>
</Project>
Then in another project, where I have made a dummy foo.txt file I have
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
<ItemGroup>
<Compile Remove="$(CompilerGeneratedFilesOutputPath)/**/*.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ConsoleAppSourceGenerator\ConsoleAppSourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Include="foo.txt"/>
</ItemGroup>
</Project>
If I through Visual Studio look at Dependencies->Analyzers->ConsoleAppSourceGenerator>TxtFile.foo.g.cs then it correctly increase the counter on every change I to in the file (see step 9).
I store generated files in path ConsoleApp/Generated/ConsoleAppSourceGenerator/ConsoleAppSourceGenerator.TxtGenerator and whenever I rebuild the project it correctly updates the files.
Have you remembered to add the [Generator] attribute to the IIncrementalGenerator?
Could you test this out and validates this doesn't either work for you?
"AdditionalFiles" in your consuming project file is the key to ensuring these files are captured by your source/incremental generator.
Found out that using a "<AdditionalFiles Include='...' />" is not necessary in some projects such as ASPNET Core projects for Source/IncrementalGenerators. The .cshtml files are included as additional files by default.
Also, file globbing patterns work with the "Include" parameter.
I'm using ConfuserEx to obfuscate my app, but it requires whole .dll binary file.
So, is there a way to obfuscate it using cli and then pack it to single file, or
access binary before compressing it to single file, so i can obfuscate it
I tried to do exclude main binary by ExcludeFromSingleFile, but it didn't work
My .crproj file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>exe</OutputType>
<AssemblyName>jay-$(RuntimeIdentifier)</AssemblyName>
<PublishSingleFile>true</PublishSingleFile>
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Content Update="$(AssemblyName).dll">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="CloudFlareUtilities" Version="1.3.0" />
<PackageReference Include="Colorful.Console" Version="1.2.15" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="YamlDotNet" Version="9.1.4" />
</ItemGroup>
</Project>
You need to add it as a post-build event, for example:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>exe</OutputType>
<AssemblyName>jay-$(RuntimeIdentifier)</AssemblyName>
<PublishSingleFile>true</PublishSingleFile>
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<!-- runs: TheAppToPassItTo.exe "<path to dll>" -->
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="TheAppToPassItTo.exe "$(TargetPath)"" />
</Target>
<ItemGroup>
<PackageReference Include="CloudFlareUtilities" Version="1.3.0" />
<PackageReference Include="Colorful.Console" Version="1.2.15" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="YamlDotNet" Version="9.1.4" />
</ItemGroup>
</Project>
Edited To Add
So, it turns out that the new "single file" executable option doesn't build it's executable from the bin directory, but from the obj directory. This has to be a simple oversight from the .NET team. There are many times where you'd want to modify your executable code before packing it up. What you are asking for is not unreasonable.
We can accomplish this by implementing a kludge until this gets rectified. We will still use the "post-build" job, but we are going to do some string replacement to build the correct path to the executable you want to modify.
This is the new script:
#ECHO off
SET tp=$(TargetPath)
SET tp=%tp:\bin\=\obj\%
ECHO Target file to modify: %tp%
YourObfuscatorEngine.exe "%tp%"
This will get the target path, in my case it is:
D:\Repositories\Source\ConsoleApp2\ConsoleApp2\bin\Release\netcoreapp3.1\win-x64\ConsoleApp2.dll
Then we do a string replace. We replace \bin\ with \obj\. The path will then be:
D:\Repositories\Source\ConsoleApp2\ConsoleApp2\obj\Release\netcoreapp3.1\win-x64\ConsoleApp2.dll
Now when you call your obfuscator engine, it will modify the correct file.
Please keep in mind that if you turn on the PublishReadyToRun option, your path will change to:
D:\Repositories\Source\ConsoleApp2\ConsoleApp2\obj\Release\netcoreapp3.1\win-x64\R2R\ConsoleApp2.dll
Which will make this a tad more complicated. So just keep that in mind if you decide you want to do this.
At the end of the day, your post-build script will look like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>exe</OutputType>
<AssemblyName>jay-$(RuntimeIdentifier)</AssemblyName>
<PublishSingleFile>true</PublishSingleFile>
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="#ECHO off
SET tp=$(TargetPath)
SET tp=%25tp:\bin\=\obj\%25
ECHO Target file to modify: %25tp%25
YourObfuscatorEngine.exe "%25tp%25"" />
</Target>
<ItemGroup>
<PackageReference Include="CloudFlareUtilities" Version="1.3.0" />
<PackageReference Include="Colorful.Console" Version="1.2.15" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="YamlDotNet" Version="9.1.4" />
</ItemGroup>
</Project>
if you only need to modify the file on publish, I suggest hooking into the publish pipeline:
<Target Name="ObfuscateAssembly" BeforeTargets="PrepareForPublish">
<Exec Command="some.exe %(IntermediateAssembly.FullPath)" />
</Target>
In case a larger process is needed, e.g. for this sample all dependencies need to be present for the obfuscator to work on all assemblies, an extended method of hooking into the build process would be after ComputeResolvedFilesToPublishList where the SDK figures out what files are needed to publish.
Here's the full example where the obfuscator works on all the assemblies in a directory:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<PublishReadyToRun>True</PublishReadyToRun>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>False</SelfContained>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>
<Target Name="CalculateObfuscationInputs" DependsOnTargets="_ComputeAssembliesToPostprocessOnPublish">
<PropertyGroup>
<ObfuscationDir>$(IntermediateOutputPath)obfuscation\</ObfuscationDir>
</PropertyGroup>
<ItemGroup>
<AssembliesToObfuscate Include="#(ResolvedFileToPublish->WithMetadataValue('PostprocessAssembly', 'true'))" />
<AssembliesToObfuscateTemporaryLocation Include="#(AssembliesToObfuscate->'$(ObfuscationDir)%(Filename)%(Extension)')" />
<_PdbsToObfuscateInput Include="#(AssembliesToObfuscate->'%(RelativeDir)%(Filename).pdb')" />
<PdbsToObfuscate Include="#(_PdbsToObfuscateInput)" RelativePath="%(_PdbsToObfuscateInput.Identity)" Condition="Exists(%(_PdbsToObfuscateInput.Identity))" />
<PdbsToObfuscateTemporaryLocation Include="#(PdbsToObfuscate->'$(ObfuscationDir)%(Filename)%(Extension)')" />
</ItemGroup>
<MakeDir Directories="$(ObfuscationDir)" />
</Target>
<Target Name="PrepareForObfuscation" Inputs="#(AssembliesToObfuscate);#(PdbsToObfuscate)" Outputs="#(AssembliesToObfuscateTemporaryLocation);#(PdbsToObfuscateTemporaryLocation)">
<Copy SourceFiles="#(AssembliesToObfuscate);#(PdbsToObfuscate)" DestinationFiles="#(AssembliesToObfuscateTemporaryLocation);#(PdbsToObfuscateTemporaryLocation)" SkipUnchangedFiles="True" />
</Target>
<Target Name="ObfuscateAssembly" AfterTargets="ComputeResolvedFilesToPublishList" DependsOnTargets="CalculateObfuscationInputs;PrepareForObfuscation">
<Exec Command="some-obfuscator.exe $(ObfuscationDir)" />
<ItemGroup>
<ResolvedFileToPublish Remove="#(AssembliesToObfuscate);#(PdbsToObfuscate)" />
<ResolvedFileToPublish Include="#(AssembliesToObfuscateTemporaryLocation);#(PdbsToObfuscateTemporaryLocation)" />
</ItemGroup>
</Target>
</Project>
I am trying to call api using Flurl and here is my request which only fails on my testserver but works on live server and localhost as well
PickUp responseAsPickUpPointServiceResponse = null;
try
{
responseAsPickUpPointServiceResponse =
await new Flurl.Url(_baseUrl + "/rest//v1/servicepoint/findByPostalCode.json")
.SetQueryParam("apikey", APIKEY_WEB1)
.SetQueryParam("countryCode", countrycode)
.SetQueryParam("postalCode", zipcode)
.WithHeader("Accept", "application/json;charset=UTF-8")
.GetJsonAsync<PickUp>();
}
BUt it fails with error
Method not found: 'System.Threading.Tasks.Task`1 Flurl.Http.GeneratedExtensions.GetJsonAsync(Flurl.Http.IFlurlRequest, System.Threading.CancellationToken, System.Net.Http.HttpCompletionOption)
Has anyone idea how to fix this?
Same here, I got the same error Method not found [...] GetJsonAsync when running my integration tests although it was working well with unit tests.
In my case, there were two projects where Flurl.Http versions mismatched :
main.csproj
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Flurl" Version="3.0.0" />
<PackageReference Include="Flurl.Http" Version="3.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\other\imported.csproj" />
</ItemGroup>
</Project>
imported.csproj
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Flurl" Version="2.8.2" />
<PackageReference Include="Flurl.Http" Version="2.4.2" />
</ItemGroup>
</Project>
The error was fixed by bumping Flurl version to 3.0.1 everywhere :
In both files :
<PackageReference Include="Flurl" Version="3.0.1" />
<PackageReference Include="Flurl.Http" Version="3.0.1" />
I know this error is common but I couldn't find any SO question to solve my problem .
I have this piece of code :
public static T _download_serialized_json_data<T>(string url) where T : new()
{
//This Line raise the error
JsonConvert.ToObject(await new HttpClient().GetStringAsync(url));
}
catch (Exception) { }
//This line raise a second error(same as the first one)
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
}
I'm getting an error regarding the first and last lines of my code
Error CS0012 The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.
As if JsonConvert doesn't contain a definition for ToObject and DeserializeObject . I don't understand which reference am I missing . The wierd thing is, if I add another class on a different page, and add this method there with the same using , no error appears .
My csproj :
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.1" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Ver sion="2.1.1" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.1" />
</ItemGroup>
<TargetFramework>netstandard2.1</TargetFramework>
No idea how that happened, but that needs to be
<TargetFramework>netcoreapp2.1</TargetFramework>