Could not load file or assembly 'Microsoft.Azure.Graphs' - c#

I've created an Azure Function to connect to a CosmosDB Graph. I'm using the nuget package Microsoft.Azure.Graph 0.3.0-preview and am getting the error when I hit the endpoint of the function.
Exception while executing function: GetTrain -> Could not load file or assembly 'Microsoft.Azure.Graphs, Version=0.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
The code for the function is below, but it doesn't even get as far as that.
[FunctionName("GetThing")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = "thing/{id}")]HttpRequestMessage req, string id, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string endpoint = ConfigurationManager.AppSettings["endpoint"];
string authKey = ConfigurationManager.AppSettings["authkey"];
string db = ConfigurationManager.AppSettings["db"];
string collection = ConfigurationManager.AppSettings["collection"];
DocumentClient client = new DocumentClient(new Uri(endpoint), authKey,
new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp });
DocumentCollection graph = await client.CreateDocumentCollectionIfNotExistsAsync(
UriFactory.CreateDatabaseUri(db),
new DocumentCollection { Id = collection },
new RequestOptions { OfferThroughput = 1000 });
IDocumentQuery<dynamic> query = client.CreateGremlinQuery<dynamic>(graph, $"g.V('{id}').has('thing')");
// Fetching the name from the path parameter in the request URL
return req.CreateResponse(HttpStatusCode.OK, "Hello");
}
Update
Seems there is a build warning, completely didn't see that. Any thoughts?
Warning MSB3270 There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "C:\Users\blah.nuget\packages\microsoft.azure.graphs\0.3.0-preview\lib\net461\Microsoft.Azure.Graphs.dll", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.

This issue is resolve for packages Microsoft.Azure.Graphs >= 0.3.1-preview.
As others have pointed out, the issue was that Microsoft.Azure.Graphs was previously targeting x64 platform only. New versions of the assembly are now compiled targeting AnyCPU (MSIL).

Try the 0.2.4-preview version of the Microsoft.Azure.Graphs package. There seems to be an issue with the 0.3.0 release. See recent comments on the SDK page:
https://learn.microsoft.com/en-us/azure/cosmos-db/graph-sdk-dotnet
And I added a GitHub issue:
https://github.com/Azure/azure-documentdb-dotnet/issues/361

This issue on github fixes everything to me https://github.com/Azure/azure-documentdb-dotnet/issues/361 only change Any Cpu to x64

Related

In ASP.NET Core FromHeader is causing the Request.Body to be fully read

In ASP.Net Core, I have this action method:
[HttpPost("things")]
[DisableFormValueModelBinding]
public async Task<IActionResult> UploadAsync()
{
using StreamReader sr = new StreamReader(Request.Body);
string body = await sr.ReadToEndAsync().ConfigureAwait(false);
int bodyLength = body.Length;
return Ok();
}
It works just fine. The body is streamed, and I can read it all. However, as soon as I attempt to get a header:
[HttpPost("things")]
[DisableFormValueModelBinding]
public async Task<IActionResult> UploadAsync(
[FromHeader(Name = "X-Test")] string test)
{
using StreamReader sr = new StreamReader(Request.Body);
string body = await sr.ReadToEndAsync().ConfigureAwait(false);
int bodyLength = body.Length;
return Ok();
}
The body is already at the end of the stream and zero bytes is read. Obviously I am reading from a header, which should not affect the request body. If I change the code to this:
[HttpPost("things")]
[DisableFormValueModelBinding]
public async Task<IActionResult> UploadAsync()
{
string test = Request.Headers["X-Test"].First();
using StreamReader sr = new StreamReader(Request.Body);
string body = await sr.ReadToEndAsync().ConfigureAwait(false);
int bodyLength = body.Length;
return Ok();
}
The action begins to work again, and I am even reading the header. If I switch back to FromHeader it fails again. Obviously, FromHeader is doing something internally which is messing with the request body.
It is important for me to get this working with FromHeader so that Swagger continues to work. Without FromHeader, I am unable to specify a header value in Swagger.
So I began searching and I found this page:
https://github.com/dotnet/aspnetcore/issues/18087
It appears others were having similar problems with using FromQuery, and some have worked around it by:
Results in:
System.IO.IOException: Unexpected end of Stream, the content may have already been read by another component. at Microsoft.AspNetCore.WebUtilities.MultipartReaderStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
And is "fixed" with:
[DisableFormValueModelBinding] and factories.RemoveType();
Assembly Microsoft.AspNetCore.WebUtilities, Version=3.1.0.0
Assembly Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0
...
Double-check your DisableFormValueModelBindingAttribute code to make sure that it's removing FormFileValueProviderFactory.
I went to try it to see if it made any difference but the latest version of those libraries visible to me in NuGet is 2.2.0 and 2.2.5 which is the latest stable and what I have installed. And this type (FormFileValueProviderFactory) does not exist in those libraries yet. Inspection using ILSpy shows it indeed is not there. VS does show my target framework is .NET Core 3.1.
In any case, I am not even sure this would solve my problem.
Anybody have any suggestions what could be going wrong for me?
Thanks!
I have confirmed if I search for FormFileValueProviderFactory in the ValueProviderFactories in my DisableFormValueModelBindingAttribute, I can find it by simply doing a Where(p => p.GetType().Name == "FormFileValueProviderFactory").FirstOrDefault(). Then if I remove it from the factories list, everything just works.
So the question now becomes why cannot I reference that type. Since I have the type pulled up I can look at the assembly being referenced and it is C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\3.1.10\Microsoft.AspNetCore.Mvc.Core.dll. This means it is not even using the NuGet at all, but is using this assembly. So I began removing older and unnecessary NuGet references when I discovered why this project is set up this way. There are some ASP.NET Core MVC utilities in a helper library, including the DisableFormValueModelBindingAttribute. This library is currently configured to be netstandard2.1, which is why the ASP.NET Core stuff cannot be referenced.
To fix this, all I had to do was change the target framework to be netcoreapp3.1 and add this to reference ASP.NET Core:
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
Everything works now.

Using ValueTuple with PackageReference on Azure Cloud Services

I'm trying to convert my c# projects from old to new csproj style, but this breaks my Azure cloud service at runtime because the ReferenceAssembly of System.ValueTuple.dll is copied instead of the implementing assembly.
This is the same problem as described in this closed/abandoned issue.
As my projects are currently targeting .NET 4.6.2, the problem is "solvable" by targeting .NET 4.7+, as that comes with System.ValueTuple and hence does not need to reference it as a NuGet package.
I would like to avoid this situation, if possible, as:
This requires an additional deploy step to install .net 4.7+ runtimes on the worker roles, as they come with .net 4.6.2 installed. https://learn.microsoft.com/en-us/azure/cloud-services/cloud-services-guestos-update-matrix#family-5-releases
This seems as "the easy way out", and I would like to know if the problem can be solved otherwise.
Additional description of the issue:
I'll use:
refDLL for: packages\system.valuetuple\4.5.0\ref\net461\System.ValueTuple.dll, and
libDLL for packages\system.valuetuple\4.5.0\lib\net461\System.ValueTuple.dll.
They are easily distinguishable, as refDLL is 40 kb and libDLL is 78 kb.
The actual code and complete build log file is found here: https://www.dropbox.com/s/kquv5voa19jfonz/AzureCloudService1.zip?dl=0
I have a solution struture as follows:
AzureCloudService1
WorkerRole1 (old csproj)
WorkerRole2 (new csproj)
After building the cloud service the
WorkerRole1\bin\Debug has libDLL.
WorkerRole2\bin\Debug\net461 has libDLL
AzureCloudService1\obj\Debug\WorkerRole1 has libDLL
AzureCloudService1\obj\Debug\WorkerRole2 has refDLL
From the logs, I noticed the following difference between WorkerRole1 and WorkerRole2.
WorkerRole1:
C:\Users\jonas\source\repos\AzureCloudService1\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll
CopyLocal = true
FusionName = System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51
HintPath = ..\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll
ImageRuntime = v4.0.30319
MSBuildSourceProjectFile = C:\Users\jonas\source\repos\AzureCloudService1\WorkerRole1\WorkerRole1.csproj
MSBuildSourceTargetName = BuiltProjectOutputGroupDependencies
OriginalItemSpec = System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL
ReferenceAssembly = C:\Users\jonas\source\repos\AzureCloudService1\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll
ReferenceSourceTarget = ResolveAssemblyReference
ResolvedFrom = {HintPathFromItem}
Version = 4.0.3.0
WorkerRole2:
C:\Users\jonas\.nuget\packages\system.valuetuple\4.5.0\ref\net461\System.ValueTuple.dll
CopyLocal = false
ExternallyResolved = true
FusionName = System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51
HintPath = C:\Users\jonas\.nuget\packages\system.valuetuple\4.5.0\ref\net461\System.ValueTuple.dll
ImageRuntime = v4.0.30319
MSBuildSourceProjectFile = C:\Users\jonas\source\repos\AzureCloudService1\WorkerRole2\WorkerRole2.csproj
MSBuildSourceTargetName = BuiltProjectOutputGroupDependencies
NuGetPackageId = System.ValueTuple
NuGetPackageVersion = 4.5.0
NuGetSourceType = Package
OriginalItemSpec = C:\Users\jonas\.nuget\packages\system.valuetuple\4.5.0\ref\net461\System.ValueTuple.dll
Private = false
ReferenceAssembly = C:\Users\jonas\.nuget\packages\system.valuetuple\4.5.0\ref\net461\System.ValueTuple.dll
ReferenceSourceTarget = ResolveAssemblyReference
ResolvedFrom = {HintPathFromItem}
Version = 4.0.3.0
After searching for other related issues on various Microsoft issue trackers, I found this one, which seems related: https://github.com/dotnet/sdk/issues/1738.

UWP - SQLite issues when compiling in native

I was developing my app using SQLite, on "Debug" mode, worked perfectly.
When I try to "Release" it (Compiling "Native"), the problem started, looks like UWP doesn't support Reflexion.
I'm currently using this packages:
SQLite.Core.UAP
SQLite.Net-PCL
For example, if I try to do this:
private void CreateDatabase()
{
var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "StoredEvents.sqlite");
SQLiteConnection SQLiteConn = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), dbPath, false);
SQLiteConn.CreateTable<StoredEvents>();
}
These are some of the error:
ILTransform_0027: Method 'CreateLambda' within 'System.Linq.Expressions.Expression' could not be found.
Error at SerializationAssemblyGenerator.Program.AddKnownContractsLists(McgCodeTypeDeclaration container, ContractTables tables)
Severity Code Description Project File Line Suppression State
Error at SerializationAssemblyGenerator.Program.GenerateDataContractSerializerHelperCode(IEnumerable`1 contracts, IEnumerable`1 jsonContracts, IEnumerable`1 wcfSerializers)
ILTransform_0000: MCG : warning MCG0006: Unresolved P/Invoke method '_TPM_Init!tpm.dll' in assembly 'TSS.UWP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it is not available in UWP applications. Please either use an another API , or use [DllImport(ExactSpelling=true)
How should I refactor the code?
Should I use a different Library?
I had the same issue when i was updating my apps from Silverlight to UWP. I read an article somewhere ( Tried to find it but was unable to ) which says SQLlite for UWP is available for Windows 10 deployment.
The above is a VS Extension. You can get there from Tools ->> Extensions & Updates
Below is how my References look like.
Also I noticed that you are not closing your db connection. Always better to use it inside a using statement. your CreateTables() will look something like below.
private void CreateDatabase()
{
var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "StoredEvents.sqlite");
using (SQLiteConnection SQLiteConn = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), dbPath, false))
{
SQLiteConn.CreateTable<StoredEvents>();
}
}

How can I list all local packages in the NuGet v3 API

For context, I'm building an application that needs to download/unpack packages and their dependencies from arbitrary package sources (including the public gallery by default) and upgrade those packages to the latest version when requested. There are no project.json files or similar, it's all code driven. It's not a particularly complicated use case and didn't require too much code in the v2 APIs.
In v3 however, I can't figure out how to correctly interact with the local package store. For example, the FolderNuGetProject class that I would have thought lists all the packages on disk at a given location in FolderNuGetProject.GetInstalledPackagesAsync() just returns an empty enumerable. To make matters more confusing, FolderNuGetProject.PackageExists() actually does return whether the package exists on disk, which means GetInstalledPackagesAsync() and PackageExists() appear to be inconsistent.
None of the other NuGetProject derivatives appear related to the file system. Is there some other way of listing the packages that have been installed into a particular folder? If I need to create my own NuGetProject (and I'm hoping I don't), are there any methods that will help with parsing NuGet-generated folder names into package IDs and versions, or is the only reliable way of getting the ID and version to open the nuspec (and are there any easy to find methods for that)?
One interpretation of why this isn't working as I expect is that NuGetProject.GetInstalledPackagesAsync() isn't actually intended to get the installed packages (I.e., those that have been downloaded and unpacked), but rather those that have been declared in whatever project system is in use. For example, the BuildIntegratedNuGetProject class appears to return package references for the packages in the project.json, regardless of their status on disk. That would also explain why FolderNuGetProject just returns an empty enumerable, because there are no "declared" packages if you're just looking at the local repository.
TL;DR: What is the best way to crawl the local package store and get the packages and versions that are present there?
(this was also issue #2664 on the NuGet GitHub project, but was moved here by request)
Introduction
I have the same question and I looked your post on GitHub, Google and here. I try a lot of things to find the local packages.
I found some solutions, but I don't know if it's the best way to do it.
I posted a question about local packages too, because I can list all local packages, but I can't have the AssemblyReferences property (dll).
Code example
var rootPath = #"pathWhereNuGetPackagesAre";
var logger = new Logger();
List<Lazy<INuGetResourceProvider>> providers = new List<Lazy<INuGetResourceProvider>>();
providers.AddRange(Repository.Provider.GetCoreV3());
FindLocalPackagesResourceV2 findLocalPackagev2 = new FindLocalPackagesResourceV2(rootPath);
var packageFound = findLocalPackagev2.GetPackages(logger, CancellationToken.None).FirstOrDefault();
//found, but missing a lot of informations...
var supportedFramework = new[] { ".NETFramework,Version=v4.6" };
var searchFilter = new SearchFilter(true)
{
SupportedFrameworks = supportedFramework,
IncludeDelisted = false
};
// The trick here is to put the local nuget path, not using the URL : https://api.nuget.org/v3/index.json
PackageSource localSource = new PackageSource(rootPath);
SourceRepository localRepository = new SourceRepository(localSource, providers);
PackageSearchResource searchLocalResource = await localRepository
.GetResourceAsync<PackageSearchResource>();
var packageFound3 = await searchLocalResource
.SearchAsync("Newtonsoft.Json", searchFilter, 0, 10, logger, CancellationToken.None);
var thePackage = packageFound3.FirstOrDefault();
// found but missing the assemblies property
public class Logger : ILogger
{
private List<string> logs = new List<string>();
public void LogDebug(string data)
{
logs.Add(data);
}
public void LogVerbose(string data)
{
logs.Add(data);
}
public void LogInformation(string data)
{
logs.Add(data);
}
public void LogMinimal(string data)
{
logs.Add(data);
}
public void LogWarning(string data)
{
logs.Add(data);
}
public void LogError(string data)
{
logs.Add(data);
}
public void LogInformationSummary(string data)
{
logs.Add(data);
}
public void LogErrorSummary(string data)
{
logs.Add(data);
}
}
Hope this will help!
In Visual Studio, Open package manager console.
List local (installed) packages use following command.
Get-Package
You can list all available packages on feed with following command
Get-Package -ListAvailable
If this commands are not working, check "Packege Manager Settings"->"Package Source" and confirm nuget feed configured correctly. (If you dont see your feed URL, You should add your feed there.) for details: Consume nuget package from VS
You can also check nuget feed configuration from this file
C:\Users{{user}}\AppData\Roaming\NuGet\NuGet.config
for more details about nuget config file: nuget config file
Also, Local nuget packages should ve stored at this path
C:\Users{{user}}.nuget\packages

ServiceStack client on a Xamarin.iOS project

I am trying to use the ServiceStack clients on a Xamarin iOS project and when debugging it I have the following exception:
“System.ArgumentException: PclExport.Instance needs to be
initialized”.
The code that produces the exception is the following:
try
{
string strReadParam = this.xmlParser.GetString("SyncUrl");
CommonStatic.SyncWSUrl = strReadParam;
var client = new JsonServiceClient(CommonStatic.SyncWSUrl);
client.Timeout = new TimeSpan(0, 0, 0, 5, 0);
var response = client.Get(new mSalesCheckConnectionRequest { DBSource = CommonStatic.DBSource, DBSourceInstance = CommonStatic.DBSourceInstance, DBName = CommonStatic.DBName, DBUsername = CommonStatic.DBUsername, DBPassword = CommonStatic.DBPassword });
return;
}
catch (System.Net.WebException wex)
{
}
I am using ServiceStack.Interfaces, ServiceStack.Client.Pcl and ServiceStack.Text.Pcl all having version 4.0.34. Additionally I referenced Newtonsoft.Json at version 6.0.7.
After some research I realized that the PCL provider for iOS is not registered automatically, so I added “IosPclExportClient.Configure();” before instantiating the new Json Service Client and a I referenced ServiceStack.Pcl.iOS.dll at version 4.0.0.0.
The result is the following error:
“Cannot include both 'monotouch.dll' and 'Xamarin.iOS.dll' in the same Xamarin.iOS project - 'Xamarin.iOS.dll' is referenced explicitly, while 'monotouch.dll' is referenced by 'ServiceStack.Pcl.iOS, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null'.”
Is there is any suggestion of resolving this problem?
Thank you in advance
You need to call IosPclExportClient.Configure(); when you application starts to initialise the PCL Export Client before use in iOS applications.
So in your Main method:
static void Main (string[] args)
{
// Configure ServiceStack Client
IosPclExportClient.Configure();
// Set AppDelegate
UIApplication.Main (args, null, "AppDelegate");
}
and a I referenced ServiceStack.Pcl.iOS.dll at version 4.0.0.0.
The PCL specific NuGet packages of ServiceStack are no longer maintained, as they have been merged into the main NuGet package using specific profile.
You should only be including the ServiceStack.Client package in your project. So remove all references to ServiceStack in your project, clean the build, and add just ServiceStack.Client.
If you reference ServiceStack.Client.Pcl was well as ServiceStack.Client you will get a conflict.

Categories

Resources