How to connect xamarin android app to Cloud Firestore db - c#

I have tried many ways as in several sites but no luck, I tried to connect it using Google.Cloud.Firestore and Google.Apis.Storage.v1 Nuget packages. The code is given below.
Google.Cloud.Firestore.FirestoreDb db = Google.Cloud.Firestore.FirestoreDb.Create("test");
CollectionReference collection = db.Collection("users");
DocumentReference document = await collection.AddAsync(new { email = "xamemail#12", name = "xamemail" });
When I tried this code one exception occurred like environment variable GOOGLE_APPLICATION_CREDENTIALS not set, then I set GOOGLE_APPLICATION_CREDENTIALS in my windows system as well as in the code as shown below.
System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", #"C:\\path-to-json", EnvironmentVariableTarget.Machine);
It's showing another error the file is not found in the path, but its there and I set the permission for the path.
If anyone there to help on this, anyone already using a xamarin - cloud firestore db in your projects?
Please note its not the firebase realtime db, I am able to connect that.

As far I have understood, you can’t use default credentials (GOOGLE_APPLICATION_CREDENTIALS) in an app on a device as it would not be able to find the path for the file located on your PC.
I have found this code, that I think should work, (But so far, I have not managed to succeed with it - I get an exeption, so I hope my answer can help to inspire someone else to find a solution for this)
using Google.Cloud.Firestore;
using Google.Cloud.Firestore.V1;
using Google.Apis.Auth.OAuth2;
using Grpc.Auth;
using Grpc.Core;
...
//First Pack your Jason fil into a Jason string.
//Fore security reasons I'm not sure this is a good idea, but it is what I could think of
string jsonCred = #”{ Your Json cred file (Replace “ with ‘) }”;
// Get you credential. As far as I have understood it must be scoped.
var credential = GoogleCredential.FromJson(jsonCred).CreateScoped(FirestoreClient.DefaultScopes);
// Create a channel and add the channel to the Firestore client
Channel channel = new Channel(FirestoreClient.DefaultEndpoint.Host, FirestoreClient.DefaultEndpoint.Port, credential.ToChannelCredentials());
FirestoreClient client = FirestoreClient.Create(channel);
// Then I think it should be possible to call.
FirestoreDb db = FirestoreDb.Create(projectId, client);
But so far, I in the line:
FirestoreClient client = FirestoreClient.Create(channel):
I get this exception:
System.TypeLoadException: VTable setup of type Google.Cloud.Firestore.V1.FirestoreClientImpl failed at Google.Cloud.Firestore.V1.FirestoreClient.Create (Grpc.Core.Channel channel, Google.Cloud.Firestore.V1.FirestoreSettings settings) [0x0000c] in T:\src\github\google-cloud-dotnet\releasebuild\apis\Google.Cloud.Firestore.V1\Google.Cloud.Firestore.V1\FirestoreClient.cs:622 at Padlelogg.DataHandler.SaveToFireStore[T] (System.String collection, System.Collections.Generic.List`1[T] Datalist) [0x00072] in C:\Users\rad\Documents\Xamarin projects\Padlelogg 2.10\Padlelogg\Data\DataHandler.cs:360 }
This exception I have not been able to resolve so far

Related

Microsoft.Azure.CognitiveServices.Language.SpellCheck NuGet not working with Bing Search API (unauthorized)

I'm using .net-core3.1 with Microsoft.Azure.CognitiveServices.Language.SpellCheck NuGet package. I've read through entire documentation around Bing/cognitive API but I still find it very confusing as there are multiple APIs doing the same thing.
I got the API key from Microsoft.BingSearch on portal.azure.com and I'm using the free subscription. My subscription should however be valid as I am already using their LUIS without problems. Azure links to https://learn.microsoft.com/en-us/bing/search-apis/bing-spell-check/quickstarts/rest/python for quick start but this does not work for me ("https://api.bing.microsoft.com/v7.0/SpellCheck" url gives me "NotFound" using the code below with my key).
code sample:
var x = new SpellCheckClient(new ApiKeyServiceClientCredentials("<API_KEY>"));
// endpoints I tried:
// x.Endpoint = "https://westeurope.api.bing.microsoft.com/v7.0/spellcheck";
// x.Endpoint = "https://cognitiveservices.azure.com/bing/v7.0";
// x.Endpoint = "https://api.bing.microsoft.com"; -- Not found
// x.Endpoint = "https://cognitiveservices.azure.com"; -- The requested name is valid, but no data of the requested type was found.
var y = await x.SpellCheckerWithHttpMessagesAsync("gona");
Using default endpoint gives me Unauthorized error code.
Anyone has any idea on how to use this API?
You are right, the endpoint seems to be wrong. As you can see in the documentation here, regarding this value:
Supported Cognitive Services endpoints (protocol and hostname, for
example: "https://westus.api.cognitive.microsoft.com",
"https://api.cognitive.microsoft.com").
So if you are using West Europe, it should be "https://westus.api.cognitive.microsoft.com"
You can also check your API key by directly testing the console here: https://westeurope.dev.cognitive.microsoft.com/docs/services/5f7d486e04d2430193e1ca8f760cd7ed/operations/57855119bca1df1c647bc358
Choose your resource region (the one selected during key creation on Azure portal)
Set your key value in "Ocp-Apim-Subscription-Key" field
Edit the "text" value in the query parameters
Run the request

Sending to Azure Event Hub Error

I'm completely brand new to C#, Microsoft Azure, and basically everything. I'm trying to set up an Azure Event Hub that I can send data to. Right now I'm just following the tutorial that can be found here.
It builds just fine, but I receive the same exception every time. The message is the following: An existing connection was forcibly closed by the remote host. This question has been asked before but never answered.
Just to be sure I'm doing this right I'm attaching pictures with where I obtained the values for the Event Hub Connection String and the Hub Name.
Where I got the Event Hub Connection String from.
This one is within the namespace - not the hub itself.
Where I got the Hub Name from.
The code goes as follows:
private const string EventHubConnectionString = "<Connection String>";
private const string EventHubName = "eventhubtest";
Does the Hub Name have to be simply that or a path? Any ideas or help would be greatly appreciated. Thanks.
#Jamie Penzien, I had been stuck with this exact same error for days and my colleague asked me to change the following part and it worked.
var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
{
EntityPath = EventHubName,
TransportType = TransportType.AmqpWebSockets
};
I am still trying to understand the reason, and it may have something to do with the company's firewall settings.
Eventhub name or Entity Path would be simply the name of EventHub found under an EventHub namespace.
You can use below code to create client:
EventHubClient eventHubClient;
var connectionStringBuilder = new EventHubsConnectionStringBuilder(EventHubConnectionString)
{
EntityPath = EventHubName
};
eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
EventHubsConnectionStringBuilder can be found under Microsoft.Azure.EventHubs package.
I answered my own questions. First, I needed to change the connection string and make sure it contained the entity path within it. Then when establishing the hub client I did this:
eventHubClient = EventHubClient.CreateFromConnectionString(EventHubConnectionString);
HOWEVER, I was getting this exception specifically because of a firewall issue. I have to open ports (working on it right now) to allow outbound communication to the event hub. I believe these are ports 5671 and 5672.
Thank you to all that answered and #RayX who nailed it on the head.

Failed To set Proxy: Wrong parameter libgit2sharp

I'm having some problems when I try to clone a repository using the library libgit2sharp.
I'm getting this error:
A first chance exception of type 'LibGit2Sharp.LibGit2SharpException' occurred in LibGit2Sharp.dll
Additional information: Failed to set proxy: Wrong parameter.
I'm trying to clone like this:
var gitServerUri = new Uri(Settings.Default.GitServerUrl);
var cred = Git.Credentials.Get(gitServerUri.Host);
string clonedRepoPath = Repository.Clone(project.GitUrl(),projectLocalPath, new CloneOptions()
{
CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
{
Username = cred.Login,
Password = cred.Password,
}
});
I tried to find in wiki of libgit2sharp where i should put the proxy config, but i didn't found.
I will be grateful if someone can help.
Regarding proxy handling, libgit2 and thus LibGit2Sharp behave a lot like the way git itself handles proxy settings.
Those can be defined in the git configuration stores (local, global, system, ...) with the following entry names...
remote.<remote_name>.proxy
http.proxy
...or set through the environment HTTPS_PROXY or HTTP_PROXY variables.
You can get a better insight about the probing strategy in the actual libgit2 code.
For more detailed information, see the following relevant issues about this topic:
Proposal to leverage Windows Proxy Auto Discovery
Using a proxy url with credentials

Acumatica Web Services API Login

I am attempting to perform some basic integration using Acumatica's web services. Unfortunatly, I'm having problems logging in. According to their documentation, this process should look something like:
apitest.Screen context = new apitest.Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.AllowAutoRedirect = true;
context.EnableDecompression = true;
context.Timeout = 1000000;
context.Url = "http://localhost/WebAPIVirtual/Soap/APITEST.asmx";
LoginResult result = context.Login("admin", "E618");
Simple enough. However, after creating and importing a WSDL file from Acumatica into Visual Studio, I found I don't have a Screen object. I do, however have a ScreenSoapClient object, which has a similar Login() method.
ScreenSoapClient context = new Acumatica.ScreenSoapClient("ScreenSoap");
LoginResult result = context.Login("username", "password");
That part works. In fact, the LoginResult give me a session ID. However, if I try to make any calls to the service, such as:
CR401000Content cr401000 = context.CR401000GetSchema();
I get an error: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> PX.Data.PXNotLoggedInException: Error #185: You are not currently logged in.
While the version of Acumatica we're using does appear to be slightly newer, I'm unsure why the Screen() object isn't available. Consequently, if I try a bad username/password, Login() does fail (as it should). From what I can the tell, the ScreenSoapClient class is using service model details from web.config, so it's getting the endpoint address and other details there.
Is there something I'm missing or doing wrong?
As i see, you use WCF to create your service reference.
So you should enable cookies in service binding:
var binding = new BasicHttpBinding()
{
AllowCookies = true
};
var address = new EndpointAddress("http://localhost/WebAPIVirtual/Soap/APITEST.asmx");
var c = new ServiceReference1.ScreenSoapClient(binding, address);
Or, you can use old asmx web service reference (http://msdn.microsoft.com/en-us/library/bb628649.aspx).
Then everything will be same as in Acumatica`s documentation.
As noted in a comment above, I was able to make contact with a representative from Acumatica. He had me remove then recreate the service references in our project and try again. That apparently did the trick and the "Error #185: You are not currently logged in" error went away.

Exchange Web Services Autodiscover non default link

I am writing a piece of software that runs on a utility device on a customers network, but not on the domain. The autodiscover service is not available off domain the same as it is either on the domain or even on the internet. None of the ways the service works by default will find it according to the docs, but the customer's IT staff tells me, supposedly :/ , it will all work if I can access Autodiscover at the link they gave me. Is there any way to override the default approach and pass it this url to autodiscover from? Hardcoding the link to /exchange.asmx is not an option nor is adding this device to the domain.
I am reusing, and now tweaking, a tried and true piece of software that has been deployed many times, but this situation is a first.
Using the EWS Managed API you may be able to do it using the AutodiscoverService class. It has a constructor that takes the URI of the Autodiscover service as a parameter.
Your code should look something like this. Note that I disable SCP lookup as you are not on a domain. I have not actually tried this code but give it a try:
AutodiscoverService ads = new AutodiscoverService(new Uri("..."));
ads.EnableScpLookup = false;
ads.Credentials = new NetworkCredential(...);
ads.RedirectionUrlValidationCallback = delegate { return true; };
GetUserSettingsResponse grResp = ads.GetUserSettings("someemail#domain.com", UserSettingName.ExternalEwsUrl);
Uri casURI = new Uri(grResp.Settings[UserSettingName.ExternalEwsUrl].ToString());
var service = new ExchangeService()
{
Url = casURI,
Credentials = ads.Credentials,
};

Categories