CloudConfigurationManager.GetSetting returning null - c#
Following instructions here I have:
var connectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");
But connectionString is null, here is my app.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="StorageConnectionString"
connectionString="DefaultEndpointsProtocol=https;AccountName=storage;AccountKey=key" />
</connectionStrings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.0.0" newVersion="5.2.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Had the same problem. Instead of using a connection string, use the configuration->appSettings->add key like this...
<configuration>
<appSettings>
<add key="StorageConnectionString" value="[ConnectionStringHere]" />
</appSettings>
</configuration>
As per documentation in MSDN http://msdn.microsoft.com/en-us/library/windowsazure/microsoft.windowsazure.cloudconfigurationmanager.aspx
Only configuration settings within the appSettings tag can be read by CloudConfigurationManager. If your configuration settings are within a different tag, calling GetSetting will return Null.
Well this works, even if the comment doesn't fit, because I do have a ref to CloudConfigManager:
If you are creating an application with no reference to Microsoft.WindowsAzure.CloudConfigurationManager, and your connection string is located in the web.config or app.config as show above, then you can use ConfigurationManager to retrieve the connection string. You will need to add a reference to System.Configuration.dll to your project and add another namespace declaration for it:
using System.Configuration;
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
I had the same problem. I had updated the project to use Azure SDK 2.0. I updated NuGet packages for my web and worker roles, but the Azure project in Visual Studio was still on the old version.
To fix this, Right-Click on your Azure project and select Properties. Under the Application tab, you'll see a button to Update your Azure SDK.
Make sure all your references are in synch. There's the 2012-06 library and 2012-10 Set them to Copy Local = true and verify SDK version. I dealt with the exact same thing, drove me nuts.
This happened to me when I upgraded the Azure SDK to version 2.2.
To fix it I changed the packages.config to use a newer version of the Azure ConfigurationManager.
<package id="Microsoft.WindowsAzure.ConfigurationManager" version="2.0.1.0" targetFramework="net45" />
Based on my understanding, I'd like to point out that CloudConfigurationManager.GetSetting will look into web.config if you're running out of a cloud service. It will look into cscfg if you're inside a cloud service.
Please refer this
link.
Following this tutorial:
You can get configuration settings like this:
RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString")
I got this after upgrading Azure SDK from 2.0 to 2.2. I was able to fix by:
Right-Clicking Azure project and selecting Properties. Update Azure SDK as per the Application tab. (Thanks to rattrick's answer).
Right click to Manage NuGet Packages. On the left click Updates and update WindowsAzure.ConfigurationManager.
I had the same problem (two times).
Even after restarting Visual Studio and after restarting the Azure emulator the CloudConfigurationManager.GetSetting("SettingName") returns null.
I was sure that it has worked before and I had the latest SDK.
So the solutions was restarting my PC and after that CloudConfigurationManager.GetSetting("SettingName") returns the right value.
I got the same issue this am after revisiting my Azure solution (Web + Worker role) to update it for Azure 2.5. Reviewing the help for CloudConfigurationManager.GetSetting, if its running under a cloud platform (Azure) it reads from the ServiceConfiguration.csfg, if running as a .net web app, reads from app or web.config.
So my fix was to simply change the start up project back to the Azure cloud project, not the Web project.
I was getting null because it was hosted in the wrong platform and reading from the .config files with no settings.
(Doh!)
It is an old thread but I wanted to share my solution if issue is not resolved by above mentioned methods then make sure that Azure Storage Emulator is running when you run the application; at least for me this happened. For me I had to create a class to handle emulator issue as mentioned here...
http://blog.simontimms.com/2013/08/28/configuration-settings-in-an-azure-worker-role/
class ConfigurationProvider
{
private static string GetStorageConnectionString(string name)
{
try
{
return RoleEnvironment.GetConfigurationSettingValue(name);
}
catch (SEHException)
{
return System.Configuration.ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
}
public static string StorageConnectionString()
{
return GetStorageConnectionString("StorageConnectionString");
}
public static string DefaultConnection()
{
return GetStorageConnectionString("DefaultConnection");
}
}
I had quite similar problems. I updated from Azure SDK 2.0 to 2.2 - during this process I used the NuGet Manager to update the Microsoft.WindowsAzure.Storage to the latest. The PackageManager automatically took Microsoft.WindowsAzure.Configuration to 1.8.0.0. I was not able to get this running (it was for .Net 2.0!?). After I manually set all References to
Microsoft.WindowsAzure.Storage 2.1.0.0
Microsoft.WindowsAzure.Configuration 2.0.0.0
everything worked.
I think this is because of the way CloudConfigurationManager.GetSetting loads the assembly and calls the funktions (via reflection).
Same here after upgrading Azure SDK from 2.2 to 2.3.:
Right-Click the Azure project select Properties. In the Application tab click "Upgrade..." (Thanks to rattrick's answer).
Then there was one more error to resolve:
Trying to run the Azure Project in the Compute Emulator threw an exception:
System.Configuration.ConfigurationErrorsException was unhandled
Message: An unhandled exception of type 'System.Configuration.ConfigurationErrorsException' occurred in Microsoft.WindowsAzure.ServiceRuntime.dll
Additional information: konnte nicht erstellt werden.
In the "Error List" Window of VS2013 there was the following Warning:
Found conflicts between different versions of the same dependent assembly. In Visual Studio, double-click this warning (or select it and press Enter) to fix the conflicts; otherwise, add the following binding redirects to the "runtime" node in the application configuration file: C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets 1635
I let VS resolve this warning and everything worked fine.
This worked for me...
using System.Configuration;
...
var connectionString = ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString;
I had the same problem. None of the advices worked for me, but the "issue" was straightforward. One simple has to understand how this class works.
It does not go into your app.config / web.config or wherever you store your application settings. CloudConfigurationManager works with ServiceConfiguration.*.cscfg and ServiceConfiguration.csdef. The .csdef must contain a definition of the setting, but not its value under the ConfigurationSettings section. The settings themselves sit in .cscfg files (under the same section but including the value; I suppose the reason for the double definition is to make sure both the cloud and the local configurations have the same settings).
You can set these either by right-clicking your role in Visual Studio and selecting Properties -> Settings (in case of StorageConnectionString, simply pick "Your subscription", if your storage account is connected to the cloud service), or by editing them manually. If you mess up the settings, you'll get an exclamation mark icon.
Simple as that.
Was getting a null value with when passing a literal string as well after installing Azure SDK 2.6 (was working before).
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureStorage"].ConnectionString);
Replaced the literal string and it worked fine.
string connectionStr = "AzureStorage";
var connectionstring = ConfigurationManager.ConnectionStrings[connectionStr].ConnectionString;
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionstring);
Related
Azure Pipeline Cant Access Azure Artefact Nuget Project Feed Even With Correct Permissions And Nuget Authenticate Task
I have a really strange issue where I have a project based nuget feed which one pipeline publishes to, which works fine, then another pipeline which needs to restore a project which uses this nuget feed. The problem is I have followed all the instructions on this such as: Make sure Build Service has permissions Make sure NuGetAuthenticate 0 or 1 is called Ensure there is a nuget.config with the feed included So for example the nuget.config looks like: <?xml version="1.0" encoding="utf-8"?> <configuration> <packageSources> <clear /> <add key="nuget" value="https://api.nuget.org/v3/index.json" /> <add key="azure-feed" value="http://pkgs.dev.azure.com/<org>/<project>/_packaging/<feed-name>/nuget/v3/index.json" /> </packageSources> </configuration> Then the pipeline section looks like: steps: - task: NuGetAuthenticate#0 - task: DotNetCoreCLI#2 displayName: dotnet restore inputs: command: restore nugetConfigPath: 'nuget.config' feedsToUse: config This all works fine in the IDE (VS and Rider) and the pipelines that publish and read the nuget package are all in the same azure devops project as the feed. When the build runs I see the authenticate step run: Setting up the credential provider to use the identity '<project> Build Service (<org>)' for feeds in your organization/collection starting with: https://pkgs.dev.azure.com/<org>/ https://<org>.pkgs.visualstudio.com/ Which is all correct and is pointing to the correct feeds, but when the restore runs the error below occurs: error NU1301: Unable to load the service index for source http://pkgs.dev.azure.com/<org>/<project>/_packaging/<feed-name>/nuget/v3/index.json. All the articles online say to try switching to NuGetAuthenticate#0 or enabling higher level settings to allow build service project scopes to not be constrained, as well as confirming all permissions are correct, none of that has solved the problem.
The issue here is that the feed in the nuget.config file is using http not https and for some reason the nuget authenticate task will ONLY authenticate the https url not the unsecure http one which the IDEs work fine with. So changing: <add key="azure-feed" value="http://pkgs.dev.azure.com/<org>/<project>/_packaging/<feed-name>/nuget/v3/index.json" /> to: <add key="azure-feed" value="https://pkgs.dev.azure.com/<org>/<project>/_packaging/<feed-name>/nuget/v3/index.json" /> Fixes it all and it works, this was never mentioned as a possible solution online so I thought it prudent to put here for any future generations who have the same issue.
How to enable EnableSqlCommandTextInstrumentation via code?
According to the documentation you need to add the following to your applicationInsights.config file to enable full SQL logging: <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector"> <EnableSqlCommandTextInstrumentation>true</EnableSqlCommandTextInstrumentation> </Add> But in my ASP.NET app running on .NET Framework 4.7.2 hosted in an Azure App Service I'm enabling/configuring Application Insights via code: TelemetryConfiguration.Active.DisableTelemetry = false; TelemetryConfiguration.Active.InstrumentationKey = setting.ApplicationInsightsInstrumentationKey; How can I enable this setting via code? P.S.: The settings in the Web App are correctly enabled.
It seems even if AI is enabled via code it picks up the settings from the config file. I added it to my applicationInsights.config and it seems to work now.
Azure Keyvault stopped working on IIS hosted site
Hi I have a question regarding Azure keyvault and IIS. So our server provider did an windows patch: 2021-04 Cumulative Update for Windows Server 2016 for x64-based Systems (KB5001347) 2021-04 Servicing Stack Update for Windows Server 2016 for x64-based Systems (KB5001402) After this windows patch and restart of server our fetch from web.config to keyvault in Azure stopped to work. When IIS is starting our app it can not find Microsoft.Configuration.ConfigurationBuilders.Azure Even if the DLL is located in the bin folder. One other important thing to mention is that our connectionStrings to the database that are located in their own file connectionstrings.config are working great with Azure Keyvault. Our windows services on the same machine are also working great with Azure Keyvault. So the issue is only affecting our appsettings section in our web.config. We have tried to add the bin folder to privatePath in the web.config, that didnt help <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="bin;modulesbin"/> This works great on our STAGING machine which has the same windows updates and uses the same configs. Does anyone have a clue what we can do next? What we are using: System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a <configBuilders> <builders> <add name="AzureKeyVault" vaultName=somevaultname" type="Microsoft.Configuration.ConfigurationBuilders.AzureKeyVaultConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Azure, Version=1.0.0.0, Culture=neutral" vaultUri="somevaulturi"/> </builders> </configBuilders> Thanks for any help Edit: We have now installed newer Azure dlls. Installed Azure CLI on server. We hare now using AZURE_TENANT_ID, AZURE_CLIENT_SECRET, AZURE_CLIENT_ID instead of AzureServicesAuthConnectionString in the environment variables. After reboot, the webapp, services, connectionstring stopped working. Error message in Event viewer: Exception message: An error occurred loading a configuration file: The specified user does not have a valid profile. Unable to load 'Microsoft.Configuration.ConfigurationBuilders.Azure Everything still work as expected on our stage server.
AZURE_TENANT_ID was added correctly under Administrator environment variables but under system environment variables it was added with AZURE_TENTANT_ID (one t too much) Such a typo. All good now.
Azure Worker Role What went wrong before OnRun() method?
I have suddenly started getting key not found error in my worker role. Configuration is missing required information. Make sure the property 'Endpoint' is defined as part of 'Microsoft.ServiceBus.ConnectionString' key within 'appSettings' section, or Windows Azure configuration settings. What I have tried: Setting name Microsoft.ServiceBus.ConnectionString is present in Cloud config. <Role name="MyWorkerRole"> <ConfigurationSettings> <Setting name="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://mysevicebus.servicebus.windows.net /> Service definition file. <ConfigurationSettings> <Setting name="Microsoft.ServiceBus.ConnectionString" /> Package.Config entry for Microsoft.WindowsAzure.ConfigurationManager points to correct version 2.0.3 App.Config: Runtime -> AssemblyBinding -> DependentAssembly for AzureServiceRuntime, ServiceBus & AzureConfiguration packages are correct. Not sure what else to look into. Can you please help? P.S. The exception is thrown after OnStart() method, just before hitting Run() method.
Have you attempted to add the SharedAccessKey and RootManagedSharedAccessKey? They are missing from you application's code demonstrated above. I have this in the app settings of my Role as well as the service configuration. <add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://yourSBname.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=KeyFromPortal" />
EF 5 Migrations cannot connect to our database even though it does just fine at runtime
We have three projects. Company.Domain (class library) Company.PublicWebsite (MVC3 Web Application) Company.InternalWebsite (MVC3 Web Application) The two website projects have reference to Company.Domain. Our EF 5 DbContext lives in Company.Domain.Data.EntityFramework and it looks like this: using System.Data.Entity; using Company.Domain.Data.EntityFramework.Entities; namespace Company.Domain.Data.EntityFramework. { public class CompanyEntities : DbContext { public DbSet<Notification> Notifications { get; set; } public DbSet<Report> Reports { get; set; } public DbSet<ReportSection> ReportSections { get; set; } public DbSet<ReportPage> ReportPages { get; set; } // brevity brevity } } We have enabled migrations and successfully used the tool in the past so I'm not sure why we are having issues now. Our migrations configuration lives in Company.Domain.Data.EntityFramework.Migrations and looks like this: namespace Company.Domain.Data.EntityFramework.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using Company.Domain.Data.EntityFramework; public class Configuration : DbMigrationsConfiguration<CompanyEntities> { public Configuration() { MigrationsDirectory = #"Data\EntityFramework\Migrations"; AutomaticMigrationsEnabled = false; } protected override void Seed(CompanyEntities context) { // empty at the moment } } } We then have an App.config file in the root of the Company.Domain project and it looks like this: <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> </configSections> <connectionStrings> <add name="CompanyEntities" providerName="System.Data.SqlClient" connectionString="Data Source=devsql;Initial Catalog=CompanyEntities;uid=XXXXX;pwd=XXXXX;MultipleActiveResultSets=True;" /> </connectionStrings> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="v11.0" /> </parameters> </defaultConnectionFactory> </entityFramework> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> </configuration> Our database lives on another server on the network. I'm able to connect to it in SQL Server Management Studio and our applications are able to connect at runtime just fine. However, when I try to run add-migration or even update-database I get the following error: http://content.screencast.com/users/Chevex/folders/Snagit/media/80fbfd6a-4956-407f-b88f-d5a53a9e5feb/03.21.2013-10.25.png System.Data.ProviderIncompatibleException: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct. ---> System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. I've even reverted my changes to the model and then ran update-database just to see if it would say 'database is on latest migration' but I still got the above error. I've poured over the connection string in App.config over and over. I cannot figure out why migrations won't connect but both of our website projects work just fine at runtime. Migrations have worked in the past. Below are the migrations in solution explorer compared with those found in the __MigrationHistory table in the database. http://content.screencast.com/users/Chevex/folders/Snagit/media/7abeaa46-ff0f-4817-a0d7-1adb086e8f0c/03.21.2013-10.30.png http://content.screencast.com/users/Chevex/folders/Snagit/media/3c6ac54d-f63d-417f-9253-39b6a8fea85d/03.21.2013-10.32.png It looks like I should be able to run update-database and have it tell me that it is up to date, but I get that error instead. As I understand it, migrations shouldn't be paying any attention to our two website projects when I'm running migrations commands, but I poured over their Web.config files as well just in case. The connection strings are identical to App.config. Edit: I've even tried completely uninstalling and removing the EF 5 package from the projects and reinstalling. Same issue >:(
Did your start project contains web.config or app.config as EF use the start project as source of the connection string
OK, so that didn't work for me at first :( Then after a cup of coffee and adding StartUPProjectName to it, it did! Try: Update-Database -StartUpProjectName MYPROJECT.NAME -Script Try to point it to a start Up project where you web.config/app.config lives
If you get the help for enable migrations in the Package Manager Console Get-Help enable-migrations -detailed You can find this documentation for the -StartupProjectName option: -StartUpProjectName Specifies the configuration file to use for named connection strings. If omitted, the specified project's configuration file is used. The doc it's a little confusing, but it means that if you use this option to specify a project name, migrations will look for the connection string in the config file of the specified project. (The config file can be web.config or app.config). If you're creating a web app, most probably the connection string will be in its web.config, so you have to specify the web app project. If it's other kind of project, the connection string will be in an app.config file of a class library or whatever, and you'll have to specify that project. Besides it's recommended that you use a constructor for your DbContext class that specifies the name of the connection string, i.e. public class CompanyEntities : DbContext { public CompanyEntities() :base("ConnectionStringName") { ... } .... } In this way you don't depend on default connection strings, which may be confusing.
You say you can connect via SQL Management Studio, but my guess is you use Windows Authentication for that, and not the uid=XXXXX;pwd=XXXXX; supplied in your connection string. Try to get Management Studio to connect using that userid and password. Also, that account might be locked out (if it is an Active Directory account).
This sounds eerily like a problem a client of mine had. It had to do with something having mucked up the DbProviders section of machine.config. He put the details here: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/f2a19487-6d38-4a79-a809-d3efe4c9d9fe (it's the Adam Scholz answer to his boss' question. :) ) Julie
May be this is solved already but i got it solved by setting the start up project in my solution to the entity dll project ( having app.config file ). I did set the "Default project" in Package Manager Console window to the correct entity dll project but that did't work. For details Entity Framework 6 with SQL Server 2012 gives System.Data.Entity.Core.ProviderIncompatibleException system-data-entity-core-providerin
If your solution has multiple projects, try setting the Startup Project for the solution to the project that contains the Web.Config or App.Config file that contains the settings for EF. I had a solution with a Web project and seperate project (Data.Models) for my models. All was well until I added a console application to the solution. As soon as I set that to be the startup project, EF Migrations would fail. Also, if multiple projects in the solution have migrations enabled, always run the Update-Database on each project after you do a Add-Migration. My web project had a pending migration, and the migrations failed weirdly on the second project because of the pending migration in the first.