ServiceStack client on a Xamarin.iOS project - c#

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.

Related

How can I migrate from In-App Billing Plugin 4.0.2 to 6.7.0? I get some errors when I try to use 6.7.0

https://github.com/jamesmontemagno/InAppBillingPlugin
I'm trying to migrate from In-App Billing Plugin 4.0.2 to 6.7.0 but I get the following errors in my Verify.cs:
using System.Threading.Tasks;
using Plugin.InAppBilling;
using AndroidProject;
using SharedCode;
[assembly: Xamarin.Forms.Dependency(typeof(Verify))]
namespace AndroidProject
{
public class Verify : IInAppBillingVerifyPurchase
{
const string key1 = #"...";
const string key2 = #"...";
const string key3 = #"...";
public string SignedDataverify = "Test", Signatureverify = "Test";
public Task<bool> VerifyPurchase(string signedData, string signature, string productId = null, string transactionId = null)
{
var key1Transform = InAppBillingImplementation.InAppBillingSecurity.TransformString(key1, 1);
var key2Transform = InAppBillingImplementation.InAppBillingSecurity.TransformString(key2, 2);
var key3Transform = InAppBillingImplementation.InAppBillingSecurity.TransformString(key3, 3);
SignedDataverify = signedData;
Signatureverify = signature;
return Task.FromResult(InAppBillingImplementation
.InAppBillingSecurity.VerifyPurchase(key1Transform + key2Transform + key3Transform, signedData, signature));
}
}
}
image
I use now Microsoft.Maui.Essentials instead of Xamarin.Essentials. I have removed the NuGet packages Xamarin.Essentials and Xamarin.Forms from my Android/iOS projects. But now I get this error:
Error CS0234: The type or namespace name 'Forms' does not exist in the namespace 'Xamarin' (are you missing an assembly reference?)
And the following error:
InAppBillingImplementation does not contain a definition for InAppBillingSecurity.
Is it still necessary to use the Xamarin.Forms NuGet package in my iOS and Android projects if I want to use In-App Billing Plugin 6.7.0 or can I use In-App Billing Plugin 6.7.0 with Microsoft.Maui.Essentials?
What is the problem with InAppBillingSecurity? Is it no more possible to use this code from version 4.0.2 to secure the purchases? Can I remove Verify.cs from my projects?
Is it still necessary to use the Xamarin.Forms NuGet package in my iOS and Android projects if I want to use In-App Billing Plugin 6.7.0 or can I use In-App Billing Plugin 6.7.0 with Microsoft.Maui.Essentials?
You used Dependency attribute. It belongs to Xamarin.Forms namespace. So it is necessary to use the Xamarin.Forms NuGet package. For more information, you can refer to Dependency Service by official. By the way, is your project Xamarin.Forms or MAUI?
What is the problem with InAppBillingSecurity? Is it no more possible to use this code from version 4.0.2 to secure the purchases? Can I remove Verify.cs from my projects?
I tested the code you provided, and also encountered this error: InAppBillingImplementation does not contain a definition for InAppBillingSecurity. But back to 4.0.2, it works well. You can refer to 'InAppBillingImplementation' does not contain a definition for 'HandleActivityResult'. Author gave
advice. I think you can continue to use 4.0.2. I also see your issue (I get some errors after migrating from 4.0.2 to 6.7.0) on GitHub, and you can follow up it to wait author's reply. In addition, you can check the README.md by author.

Roslyn compilation - how to reference a .NET Standard 2.0 class library

I created a console application project (targeting .NET Core 3.0) and a class library (targeting .NET Standard 2.0). The console application tries to use the Roslyn compiler to compile some C# code that references that previously created class library. I'm hitting some major issues though.
Here's the code for the console application (note that most of it is example code from https://github.com/joelmartinez/dotnet-core-roslyn-sample/blob/master/Program.cs):
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp; //nuget Microsoft.CodeAnalysis.CSharp
using Microsoft.CodeAnalysis.Emit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
//This is a class library I made in a separate project in the solution and added as a reference to the console application project.
//The important bit for the reproduction of the issue is that ClassLibrary1 targets .NET Standard 2.0.
using ClassLibary1;
namespace RoslynIssueRepro
{
class Program
{
static void Main(string[] args)
{
string codeToCompile =
#"
using ClassLibary1;
using System;
namespace RoslynCompileSample
{
public class Writer
{
public void Execute()
{
//1. this next line of code introduces the issue during Roslyn compilation (comment it out and everything runs fine).
//It causes the code to reference a .NET Standard 2.0 class library (and this console app targets .NET Core 3.0).
//Note: If the referenced class library targets .NET Core 3.0, everything works fine.
//The error looks like this:
// 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'.
Console.WriteLine(Class1.DoStuff());
Console.WriteLine(""Freshly compiled code execution done!"");
}
}
}";
var refPaths = new[] {
typeof(System.Object).GetTypeInfo().Assembly.Location,
typeof(Console).GetTypeInfo().Assembly.Location,
Path.Combine(Path.GetDirectoryName(typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly.Location), "System.Runtime.dll"),
typeof(Class1).GetTypeInfo().Assembly.Location,
//2. So adding a reference to netstandard.dll to alleviate the issue does not work.
//Instead it causes even more compilation errors of this form:
// CS0518: Predefined type 'System.Object' is not defined or imported
// CS0433: The type 'Console' exists in both 'System.Console, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' and 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
//Go ahead and try it by uncommenting the line below:
//Environment.ExpandEnvironmentVariables(#"C:\Users\%USERNAME%\.nuget\packages\netstandard.library\2.0.0\build\netstandard2.0\ref\netstandard.dll")
};
RoslynCompileAndExecute(codeToCompile, refPaths);
}
#region example code from https://github.com/joelmartinez/dotnet-core-roslyn-sample/blob/master/Program.cs
private static void RoslynCompileAndExecute(string codeToCompile, string[] refPaths)
{
Write("Let's compile!");
Write("Parsing the code into the SyntaxTree");
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(codeToCompile);
string assemblyName = Path.GetRandomFileName();
MetadataReference[] references = refPaths.Select(r => MetadataReference.CreateFromFile(r)).ToArray();
Write("Adding the following references");
foreach (var r in refPaths)
Write(r);
Write("Compiling ...");
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
Write("Compilation failed!");
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.Error.WriteLine("\t{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
}
else
{
Write("Compilation successful! Now instantiating and executing the code ...");
ms.Seek(0, SeekOrigin.Begin);
Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms);
var type = assembly.GetType("RoslynCompileSample.Writer");
var instance = assembly.CreateInstance("RoslynCompileSample.Writer");
var meth = type.GetMember("Execute").First() as MethodInfo;
meth.Invoke(instance, null);
}
}
}
static Action<string> Write = Console.WriteLine;
#endregion
}
}
and the code for the ClassLibrary1 is just this:
namespace ClassLibary1
{
public static class Class1
{
public static string DoStuff()
{
return "asdfjkl";
}
}
}
I've commented two places in code with //1 and //2. The first one is the line that introduces the first issue, and causes the compilation to fail. The second spot (currently commented out) is an attempt to work around the first issue by adding a reference to the netstandard.dll file (sorry if the path isn't portable, just where I happened to find it on my machine), but it does not fix anything, only introducing more cryptic errors.
Any idea on the approach I should take to get this code to work?
The first error occur because your referenced library targets netstandard and the console app compilation which references this library must reference netstandard.dll to correctly resolve all corresponding types. So you should add reference to nestandard.dll but it's not all and here you get the second error.
When you try to reference netsandard directly or by transitive you must provide the nestandard.dll corresponding by the target platform. And this netstandard will have a huge of forwarding types to the types on the current target platform. If you look at the #"C:\Users\%USERNAME%\.nuget\packages\netstandard.library\2.0.0\build\netstandard2.0\ref\netstandard.dll" you will find that this netstandard.dll doesn't contain forwards but contains all types directly and of course it contains System.Console. ( I think, it contains all types directly because it is from nuget package which doesn't depend on any target platform, but really not sure for that). And when you try to add it and System.Console.dll by typeof(Console).GetTypeInfo().Assembly.Location you actually get two System.Console in a compilation.
So to resolve this ambiguous you can add netstandard not from this nuget package, but from you current target platform which has all needed forwards. For the .netcore30, for example, you can use netstandard from path_to_dotnet_sdks\packs\Microsoft.NETCore.App.Ref\3.0.0\ref\netcoreapp3.0\ (be careful this assemblies and assemblies from nuget package above just for referencing, they doesn't contain real logic). Also you may try to remove reference on System.Console.dll and keep reference on #"C:\Users\%USERNAME%\.nuget\packages\netstandard.library\2.0.0\build\netstandard2.0\ref\netstandard.dll"
Since you're using typeof(X).Assembly to locate all other referenced assemblies, which will implicitly return the assemblies loaded into your App Domain. I would recommend locating the matching netstandard in the same way. However, since netstandard doesn't directly define any types, the best method I've found is to search for it by name;
AppDomain.CurrentDomain.GetAssemblies().Single(a => a.GetName().Name == "netstandard")
var dd = typeof(Enumerable).GetTypeInfo().Assembly.Location;
var coreDir = Directory.GetParent(dd);
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "netstandard.dll")
Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "netstandard.dll")

Sharp.XMPP with Xamarin Forms

I am using Xamarin forms to create a chat application and to achieve that i am using Sharp.XMPP library from Nuget but i ran into issues.
It was stated that it doesn't support in PCL at here
So i converted the project into shared .net standard library following this blog
After adding following code
using Sharp.Xmpp.Client;
async void OnLoginButtonClicked(object sender, EventArgs e)
{
var user = new User
{
Username = usernameEntry.Text,
Password = passwordEntry.Text
};
string hostname = "localhost";
string username = user.Username;
string password = user.Password;
using (var client = new XmppClient(hostname, username, password))
{
client.Connect();
messageLabel.Text = "Login Success";
client.SendMessage("axcl#localhost", "juyugygyg");
}
}
Error Recieved :
Severity Code Description Project File Line Suppression State
Error Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'Sharp.Xmpp, Version=1.0.2.2, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'Sharp.Xmpp.dll'
at Java.Int rop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
at Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences(DirectoryAssemblyResolver resolver, ICollection`1 assemblies, AssemblyDefinition assembly, Boolean topLevel)
at Xamarin.Android.Tasks.ResolveAssemblies.Execute(DirectoryAssemblyResolver resolver) app.Android
Can anyone help me out to how to bind a .net library dll into the project so that it can be used in xamarin forms.
Another alternative is agsXMPP .NET SDK but am not sure much of it.
If i missed something. Sorry for that
First remove sharp nuget and clone this.
https://github.com/pgstath/Sharp.Xmpp .
Open the solution of sharp and build it.
You will get Sharp.Xmpp.dll under bin\debug.
Add reference of this .dll to your project.

Error CS0433: The type 'JsonValue' exists in both 'System.Json, Version=2.0.5.0' and 'Xamarin.Auth' (CS0433)

I'm trying to create an app in Visual studio for mac with Xamarin.Forms. In this app I'm using Xamarin.Auth to store some user details. Now I want to add a connection with an API by using JSON. I added System.Json and added my code. But the problem is I get the error:
Error CS0433: The type 'JsonValue' exists in both 'System.Json,
Version=2.0.5.0' and 'Xamarin.Auth' (CS0433).
I removed and added Xamarin.Auth to the project. I removed the OBJ and BIN folders while visual studio was closed, started VS, cleaned the solution, rebuild the solution and tried it again but still the same error. I can't seem to find out what the problem is.
I'm not quite sure if it will help but here is one snippet of code where the error occurs, I know the function does not return anything at the moment but I'm just trying to figure out how to do JSON/API calls and get the code to compile without errors:
public class DBhandler
{
public async Task<List<Object>> GetItemsFromApiASync(Type callingClass, string apiDir, string apiFile)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(ApiAddress + apiDir + apiFile));
request.ContentType = "application/json";
request.Method = "Get";
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream stream = response.GetResponseStream())
{
System.Json.JsonValue jsonDoc = await Task.Run(() => System.Json.JsonObject.Load(stream));
object[] parametersArray = new object[] { jsonDoc };
MethodInfo methodInfo = callingClass.GetMethod("ConvertApiResultToObject");
methodInfo.Invoke(methodInfo, parametersArray);
}
}
return null;
}
I encountered the same problem when creating a Xamarin Android project that referenced Xamarin.Auth and a few other NuGet packages and the Facebook Xamarin component. I was able to simply remove System.Json from my project's references, and then my project was able to compile and run.
All of a sudden I did remember how to solve this: I was helped by the comments on the question(thanks #Tcraft, #DiegoRafaelSouza). I added System.Json to the references on the different platforms(I use a shared project, so on project.IOS and project.Android). Right clicked on properties and ticked Local Copy. Then I added an alias SystemJsonAlias. And used using SystemJsonAlias = System.Json in all my .cs files where needed.
Perhaps this helps someone else.

Could not load file or assembly 'Microsoft.Azure.Graphs'

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

Categories

Resources