i am trying to connect to the google firestore. i was able to connect, giving me key.json file as param:
FirestoreDb db = new FirestoreDbBuilder { ProjectId = "interiorcircle", CredentialsPath = "/Users/juliustolksdorf/Projects/Interior_Circle/keys/interiorcircle-4f70f209e160.json" }.Build()
But i heard its more common to do this via env variable. I tried setting it up wth terminal in .zshenv and also in .bash_profile (both).
Then i also went into terminal and set the variable.
Now, when I set "env" into terminal I am getting this line:
So it does look like the file is set correctly. But when I try to run my application with:
var credential = GoogleCredential.GetApplicationDefault();
(which is the recommended way)
my debugger hangs for about 5 minutes until it thorws an exception:
One or more errors occurred. (The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.)
So what am I doing wrong here? Im stuck at this for hours now.
EDIT:
I am working with xamarin.forms application. I set the variable in terminal from mac OS, not in console of xamarin.
I tried:
var x = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
But im being returned "null"
Related
I'm trying to create a Twilio app in C#, I took the code on the official documentation. I installed all the packages that the doc ask, for and try to run the app, but the following message error appears:
Code:
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
TwilioClient.Init(
Environment.GetEnvironmentVariable("********"),
Environment.GetEnvironmentVariable("********")
);
var message = MessageResource.Create(
from: new PhoneNumber("whatsapp:********"),
to: new PhoneNumber("Whatsapp:********"),
body: "Test"
);
Console.WriteLine("Message SID: ", message.Sid);
Error:
Unhandled exception. Twilio.Exceptions.AuthenticationException: Username can not be null
at Twilio.TwilioClient.SetUsername(String username)
at Twilio.TwilioClient.Init(String username, String password)
at Program.<Main>$(String[] args) in
line 5
I tried to implement the code line that appears in the error message, but the error is still there
Code:
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
TwilioClient.Init(
Environment.GetEnvironmentVariable("*********"),
Environment.GetEnvironmentVariable("*********")
);
Twilio.TwilioClient.SetUsername(
username: "*********#gmail.com"
);
Twilio.TwilioClient.Init(
username: "*********#gmail.com",
password: "*********"
);
var message = MessageResource.Create(
from: new PhoneNumber("whatsapp:*********"),
to: new PhoneNumber("Whatsapp:*********"),
body: "Teste"
);
Console.WriteLine("Message SID: ", message.Sid);
Something important to mention is that I create and set my account on Twilio, so everything is all right
This happens when I debug:
Debug
Please try the following code snippet:
Set Twilio Account SID (String Identifiers at Twilio) as username twilio.com/docs/glossary/what-is-a-sid and
Set Twilio Auth Token as a password
var sid = "34digitSID";
var authToken = "authToken";
TwilioClient.Init(sid, authToken);
For security reasons we can save this in appsettings.json file in asp.net MVC and read it as follows:
var sid = Configuration.GetValue<string>("AppSettings:Twilio:AccountSID");
var authToken = Configuration.GetValue<string>("AppSettings:Twilio:AuthToken");
TwilioClient.Init(sid, authToken);
Twilio tutorials and samples will usually use environment variables, but you have to make sure you set the environment variables first.
This is to avoid hard coding sensitive information like Account SID and Auth Token, which could then be accidentally committed to source control.
You're currently passing null to the first parameter of TwilioClient.Init which is why the error occurs. The reason that you're passing null is that the environment variable you're trying to pull isn't configured yet.
If you're running your .NET project from the .NET CLI, before running the project, configure the environment variables like this:
If you're using a bash or bash-like shell (mac/linux/unix):
export TwilioAccountSid=[TWILIO_ACCOUNT_SID]
export TwilioAuthToken=[TWILIO_AUTH_TOKEN]
If you're using PowerShell:
export TwilioAccountSid=[TWILIO_ACCOUNT_SID]
export TwilioAuthToken=[TWILIO_AUTH_TOKEN]
If you're using CMD:
set "TwilioAccountSid=[TWILIO_ACCOUNT_SID]"
set "TwilioAuthToken=[TWILIO_AUTH_TOKEN]"
Once you close your shell, the environment variables are lost and you'll need to set them again next time.
If you're not running the project from the CLI, but from an IDE, the IDE may also let you configure environment variables, but depending on the IDE, it may be stored in a plain text file inside of your project, which introduces the same risk of accidentally putting it into source control and leaking the sensitive tokens.
You can also set environment on Windows, profile or system wide using their built-in UI.
Lastly, the samples use Environment Variables because they are universally available (on all OS's and infrastructure) and are the simplest way to safely get started, but .NET has a much better way of configuring applications.
Here's an article that will take you from using environment variables to the .NET Configuration Builder and some of its features.
PS, let us know how you're running your project, like what IDE, what shell, etc. and also what Operating System you're using, so we can provide more specific instructions.
I have been using c# code to get blob items for the past few days, however, with no changes to the way the program gets the blob data, it stopped working. I run into the same error every time I run now:
"EnvironmentCredential authentication unavailable. Environment variables are not fully configured"
Here is the code I am using to connect to Azure:
Uri accountUri = new Uri(mystorageurl);
BlobServiceClient client = new BlobServiceClient(accountUri, new DefaultAzureCredential(true));
BlobContainerClient container = client.GetBlobContainerClient(blobname);
BlobClient bundle = container.GetBlobClient(itemname);
What I've been confused by is that if I run this same code in a separate vs solution, I get no error getting the files from Azure. I've also tried sending the same solution that's getting the error to another person and they were able to run it without issue. I know it isn't an issue with environment variables, since it used to work up until now and they haven't been modified in any way.
This unresolved issue on github is most similar to what I've encountered:
https://github.com/Azure/azure-sdk-for-net/issues/16079
It worked fine when you never set Environment variables, it means that you didn't use EnvironmentCredential. The DefaultAzureCredential will attempt to authenticate via the following mechanisms in order, and Environment is the first one.
If you just use Environment to authenticate, it's better to use EnvironmentCredential instead of DefaultAzureCredential. And it's necessary to set the following variables.
AZURE_CLIENT_ID: id of an Azure Active Directory application
AZURE_TENANT_ID: id of the application's Azure Active Directory tenant
AZURE_CLIENT_SECRET: one of the application's client secrets
I'm currently trying to access the cloud API and I am receiving this error:
The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials.
I have already gone onto my google cloud platform account, enabled billing, created a service account, downloaded a JSON key and set GOOGLE_APPLICATION_CREDENTIALS in my environment variables and have checked that it's pointing to the correct JSON key. It is pointing to my API key
'C:\Users\jade.wilson\source\repos\CloudApi\CloudApi\Services\Keys\CloudAPIKey.json'
This is the code:
var credential = GoogleCredential.GetApplicationDefault();
var channel = new Grpc.Core.Channel(SpeechClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());
var client = SpeechClient.Create(channel);
response = await client.RecognizeAsync(new RecognitionConfig()
{
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRateHertz = 16000,
LanguageCode = "en",
}, RecognitionAudio.FromStream(audio));
It is not getting past the first line. Is there something else I am missing?
If you are using Visual Studio, just close and reopen it.
It seems that if you create/alter environment variables while Visual Studio is open, the programs that you'll run/debug won't be able to see them. You have to exit Visual Studio and reenter (happened to me: VS 2019 ver. 16.7.2, Win 10 ver. 2004 - OS Build 19041.450)
This is my first crack at creating an Azure App Function. I've got it working when running on my local dev machine. Now I've deployed it into Azure, and I'm attaching the debugger to it (very cool, btw!).
When running on my localhost, I can use the local.settngs.json file for all of the app settings. That works fine. But I seem to be hitting a roadblock on the simple process of accessing application settings when running the function remotely in Azure.
First (and this is a battle I will fight later) I'm sure there is a way to auto-populate the settings in the Azure Function based on what's in local.settngs.json, but for now, I added them all manually.
For now, let's just take a look at the setting StorageConnectionString who's value looks like this:
DefaultEndpointsProtocol=https; AccountName=[redacted]; AccountKey=[redacted]; EndpointSuffix=core.windows.net
All three of these attempts to get the value work on my localhost, but all three also fail when debugging in the remote Azure function:
string storageConString = ConfigurationManager.AppSettings["StorageConnectionString"];
string storageConString = CloudConfigurationManager.GetSetting("StorageConnectionString");
string storageConString = Environment.GetEnvironmentVariable("StorageConnectionString");
In all cases, I get this this error:
Error message:
Value cannot be null. Parameter name: itemName
Stack Trace:
at Microsoft.WindowsAzure.Storage.Core.Util.CommonUtility.AssertNotNullOrEmpty(String paramName, String value) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\Common\Core\Util\CommonUtility.cs:line 143 at Microsoft.WindowsAzure.Storage.File.CloudFileDirectory.GetDirectoryReference(String itemName) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\Common\File\CloudFileDirectory.Common.cs:line 224 at XXXXXXX.Common.AzureFunctions.ProcessInbound.DoBooksExist(BookSource bookSource) at XXXXXXX.Common.AzureFunctions.ProcessInbound.Run(TimerInfo myTimer, TraceWriter log)
The error has me kind of stumped, as it doesn't even seem to apply. Why, for example, is it calling GetDirectoryReference(String itemName)?
To get an environment variable or an app setting value, use System.Environment.GetEnvironmentVariable, as shown in the following code example:
public static string GetEnvironmentVariable(string name)
{
return System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}
App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the Values collection in the local.settings.json file. In both environments, local and Azure, GetEnvironmentVariable("<app setting name>") retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }.
Or you can use System.Environment.GetEnvironmentVariable:
Taken from Azure Functions C# developer reference - Environment variables
Ok, finally got this figured out. The core of the issue is some strange behavior on how the debugger works when attached remotely. I finally figured out the real issue by setting the Publish Configuration to Debug before publishing:
The problem had been that when I had it set to "Release", the debugger would break on the first line of the method that had the error in it, and NOT on the actual line with the error. This lead me to think I was getting the error on a line that was not, actually, throwing the error.
Once I knew the true line that was throwing the error, solving it was a snap.
I have an ASP.NET web application that uses System.Speech to transform text to a WAV file. It works fine locally but when I deploy it to the server, I get the below error message. This is using Windows Server 2012, ASP.NET 4.5, and IIS 8.5:
Object reference not set to an instance of an object.
System.Speech
at System.Speech.Internal.ObjectTokens.RegistryDataKey..ctor(String fullPath, RegistryDataKey copyKey)
at System.Speech.Internal.ObjectTokens.SAPICategories.DefaultDeviceOut()
at System.Speech.Internal.Synthesis.VoiceSynthesis..ctor(WeakReference speechSynthesizer)
at System.Speech.Synthesis.SpeechSynthesizer.get_VoiceSynthesizer()
at QuinnSDS.handlerTransform.<>c__DisplayClass6.<ProcessRequest>b__1()
The code which is generating this error message runs on the server:
if (context.Request.ContentLength > 0)
{
string line = new StreamReader(context.Request.InputStream).ReadToEnd();
// ********* generate wav file voicing the response *****************
// Using Microsoft voices
// initiate new instance of speech synthesizer
Thread t = new Thread(() =>
{
try
{
// The object creation works fine
System.Speech.Synthesis.SpeechSynthesizer synth = new System.Speech.Synthesis.SpeechSynthesizer();
if (synth != null)
{
// The code breaks at synth.GetInstalledVoices() below. It will break any time I try to do anything with the synth object
foreach (System.Speech.Synthesis.InstalledVoice voice in synth.GetInstalledVoices())
{
System.Speech.Synthesis.VoiceInfo info = voice.VoiceInfo;
string voiceName = info.Name;
ws.WriteLine(voiceName);
}
}
}
catch (Exception e)
{
ws.WriteLine(e.Message);
ws.WriteLine(e.Source);
ws.WriteLine(e.StackTrace);
}
//... code continues...
It does not break when the Speech Synthesis object is created; it breaks whenever I try to use that object in any way.
I'm not sure if it's an access issue but I'm pretty new to ASP.NET and IIS and I can't figure out how to give the web app access to the GAC or if that's even what the problem is. I tried changing the property Local Copy for the System.Speech reference to True in Visual Studio, before I deploy the app, but that hasn't worked. I searched online and while the "object reference not set to an instance of an object" seems fairly common, I cannot find any similar issues where it is because of a .NET framework class library...I have run the text-to-speech code locally on the server and it ran fine. I have not run the entire app locally on the server because the web app requires speech input and there is not a microphone on the server.
Any ideas of anything to try would be most welcome!
What user account is the code running under when executed from ASP.NET? If the Speech API is touching the registry like the call stack suggests, it possibly has different permissions than the account you used to run the code manually.
If you can't just make the application pool for your site run with the same account you log into the machine with, I've had some success using Process Monitor to track down this kind of problem before. Basically, execute the code that fails while Process Monitor is running and look for 'ACCESS DENIED' in the 'Result' column (or anything else that looks suspicious). Quickly switching the application pool to use your standard user account will be the fastest way to rule out security or permission related problems though.