asp.net core 2.0 Configuration.GetConnectionString doesn't seem to be reading appsetting.environment.json - asp.net-core-2.0

I can add a "ConnectionStrings" element to my appsettings.json file; however, when I copy and paste the same element in to my appsettings.Development.json file it doesn't seem to work. My var connection = Configuration.GetConnectionString("DefaultDatabase"); line of code no longer works within Startup.cs and the ConfigureServices() method.
I am using Visual Studio 2017 and when i go to the properties of the project and go to the Debug tab I can see that it is setting ASPNETCORE_ENVIRONMENT to Development so shouldn't the connection string within appsettings.Development.json work with the Conifugration.GetConnectionString() method?

Ugh ok apparently I was pasting the code in to the "Logging" section element (right after the LogLevel element. Now that I truly have ConnectionStrings as its own element instead of a property of Logging all is well now.

Related

Visual studio export template replaces original projectname with $safeprojectname$

My project is a mvc4 project in visual studio 2013 ultimate.
I tryd to send my project by following the steps :
File > Export template > (leave all the options as default)
I get a zip that i unpack. If i open the unpacked solution and run the program i get alot of errors. It looks like visual studio replaced all the text that contained the projectname with $safeprojectname$. How can i export the project without visual studio replacing all the 'projectname' spots so that i can run my program.
I tryed creating a new project (console application) with no code in it, if i export it and import it i get the same message first i get :
Warning 1 Load of property 'RootNamespace' failed. The string for the root namespace must be a valid identifier. SvenEind
and after running i get
190 errors 31 warnings
I tryd importing http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/building-the-ef5-mvc4-chapter-downloads and that worked for me.
So i guess the problem is in some kind of settings for exporting files.
replaced all the text that contained the projectname with $safeprojectname$
This is very much by design. You created a project template, a cookie-cutter for new projects. You are not supposed to do anything with the .zip archive. It should sit patiently in your "My Exported Templates" folder. Until the day arrives that you want to start a new project.
You then can pick the template instead of using one of the built-in ones that were preinstalled by the Visual Studio installer. Visual Studio prompts you for the project name. It then unzips the archive, copying the files into your new project directory. And modifies the files, $safeprojectname$ is substituted by the new project name you entered. You now have a good start for your new project, using the settings and assets that you saved earlier when you created the template.
Sounds like you had an entirely different use in mind, I can't guess at the intention from the question.
Hmmm. I got this error on Build:
The app manifest must be valid as per schema: Line 42, Column 18, Reason: '$safeprojectname$' violates pattern constraint of '([A-Za-z][A-Za-z0-9]*)(\.[A-Za-z][A-Za-z0-9]*)*'. The attribute 'Id' with value '$safeprojectname$' failed to parse.
So I grabbed the project name from the VS Configuration Manger and put it in the app manifest like this.
<Applications>
<Application
Id="CordovaApp.Windows10"
And the error went away and the project built. HTH.

VS2012 & 2013: Can't publish Services project - specified path is too long

I have a VS2012 solution, containing 10 projects, and suddenly, I can no longer publish my Services project to any folder.
When I try to publish to D:\temp, I get this error:
The expression "[System.IO.Path]::GetFullPath(obj\Release%25252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252528Prod%25252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252529\)" cannot be evaluated. The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters. C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.Publishing.targets
Huh ?
VS2012 (with update 4) seems to have taken my configuration name "Release(Prod)" and completely messed it up, causing the GetFullPath to produce too long a path name.
How the heck can I fix this ?
Out of desperation, I tried to build and publish the same project in VS2013 - and it had the same error message.
One of my colleagues said he'd seen the same thing, but had fixed it by removing the spaces from his configuration name. I tried this, which is why my configuration name is now "Release(Prod)" rather than "Release (Prod)", but it made no difference.
I did also open the file which this error is suggesting is the cause of the error:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.Publishing.targets
..and noticed that there's something in there concerning the AnyCPU platform name. I have tried getting my Services project to use "AnyCPU" and "Any CPU" (depressed sigh) but neither seems to make any difference.
<PropertyGroup Condition=" '$(IntermediateOutputPath)' == '' ">
<IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU' Or '$(PlatformName)' == ''">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
. . .
</PropertyGroup>
Has anyone else seen this issue ?
(A little bit later..)
This is so odd (and frustrating).
My Solution has 5 configurations - the default Debug and Release ones, plus extra configurations for Test, PreProduction and Production environments.
If I select any of these three configurations containing brackets, I get this ridiculous "The specified path is too long" error, as VS2012 corrupts the pathname (as shown in my first screenshot above).
I can't help wondering... is this some kind of VS2012 bug, handling spaces or brackets in the configuration name ?
I can deploy to a path directly with (, (, )) in the Target Location on tyhe Connection tab when publishing to the file system (i.e. not building a path from the configuration name) - but that is not a solution to targeting different locations based on the Configuration.
If you want to keep special characters in the configuration name, but specify a path to the deployment folder that will not cause and issue this post might help: Visual Studio: How to properly build and specify the configurations and platforms for x64 and x86
Specifically play with the settings in here:
In the project properties page, select the various permutations of
Debug/Release and x86/x64 in the solution dropdowns. Make sure the
target processor is set correctly (it should be, but I found instances
when they were not, probably because of my previous attempts). Also,
set the output directory. That should be okay and automatic
(/bin/x86/Debug, etc.). If not, fix.
Looking at what is actually seems to be going on is also potentially useful:
Looking at the numbers inserted:
%25 is an encoded %,
%28 is an encoded (
%29 is an encoded )
Looking at the path:
obj\Release%252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525***28***Prod%252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525252525***29***)
What I think is happening:
So that seems like a good clue that these are being URL or XML encoded. What appears to be happening is that the ( is being encoded as %28 and then the % is being recursively encoded as %25 - generating an infinite %252525252525252525....
A more interesting question is actually why it stops creating 25's from the %'s with this bug (both times it stops creating 25's at 214 characters including the % and the 28 / 29 - not a very interesting number).
Looking at the file C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.Publishing.targets you reference - it makes sense that these strings are being encoded for XML. I would say this is definitely a bug... I have no suggestions for a fix.
Well, I'm going to accept Matthew's answer as the "Accepted Answer".
Thank you for your help.
This is a really odd problem though, and I'm amazed no one else has reported this elsewhere.
Summary of problem (in case Microsoft is interested, or if anyone tries to Google this issue in the coming years)
With a configuration name of "Release (Prod)", I could happily build my code, run it locally, but when I tried to publish it, even to a local drive, I'd get this message:
It's an odd exception, because the Build did create the "obj\Release (Prod)" folder, without any issues. It's just the Publish which seemed to be looking in the wrong place for it.
Following the advice given in this thread, today I attempted to create a new configuration, with the same settings, but without a space in the name: "Release(SecondProd)". Look what happens:
Interestingly, despite this error, it did create a new configuration with this name.
Anyway, I recreated a new configuration, called it ReleaseProduction, and it worked fine.
Of course, I needed to create new "web.config" Transformation for this name, as this doesn't get automatically copied when you create a new configuration based on an old one.
One last thought (just to confuse matters worse !)
When I posted this plea-for-help, the Services project in my Solution refused to publish to a local drive, but my web site would publish okay.
Today, two days since I last attempted a website Publish, I found that the website also now produces the same GetFullPath exception. Nothing's changed ! We use TFS, I have done a file compare with my project files today against two days ago, and they're identical !
It's a really bizarre bug in VS2012 & VS2013.
Btw, this solution & the projects in it, were originally a VS2010 project. They were upgraded to VS2012 over a year ago, but this Publish problem only started happening recently. I'm not sure if the problem is related to using upgraded VS projects.
Again, thanks for your help.
Now I have some Test, PreProd & Production configurations to recreate !
Maybe I'll grab a beer first..
Summarizing and completing Matthew's answer:
Cause: You have configurations with chars that require URI-encoding - in your case, '(' and ')'.
Workaround: Rename those configs.
What happens: Presumably web deploy URI-encodes the path, replacing % => %25, ( => %28, ) => %29. It does so over and over:
obj\Release(Prod)
obj\Release%28Prod%29
obj\Release%2528Prod%2529
obj\Release%252528Prod%252529
...
Until the path exceeds MAX_PATH=260.
I ran into the same thing and all though it does not resolve the issue I found that if I switch the solution configuration away from a build containing "(" or ")"
Then use the appropriate build in the publish dialog it will not error out.

ANTLR4 Generating Lexer in JAVA instead of C Sharp

When doing
java -cp C:\Tools\Libraries\antlr4-csharp-complete.jar org.antlr.v4.Tool Hello.g4
I get the following files:
HelloBaseListener.cs
Hello.tokens
HelloListener.cs
HelloParser.cs
HelloLexer.tokens
HelloLexer.java
My question is about the last file. Why is it .java instead of .cs?
I'm using antlr4-csharp-4.0.1-SNAPSHOT-complete.jar
Grammar is:
grammar Hello; // Define a grammar called Hello
options
{
language=CSharp_v4_0;
}
r : 'hello' ID ; // match keyword hello followed by an identifier
ID : [a-z]+ ; // match lower-case identifiers
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines, \r (Windows)
Hello Sam! I only have visual studio express so I can't install the extension. This is the code that I'm using but it is still generating the HelloLexer.java.
AntlrClassGenerationTaskInternal a = new AntlrClassGenerationTaskInternal();
List<String> files = new List<string>();
files.Add(#"C:\Tools\Grammars\Hello.g4");
a.JavaVendor = "JavaSoft";
a.ToolPath = #"C:\Tools\Libraries\antlr4-csharp-complete.jar";
a.JavaInstallation = "Java Development Kit";
a.SourceCodeFiles = files;
a.OutputPath = #"C:\Tools\Grammars\CSharp\";
a.Execute();
By the way, visual studio complained because it was not able to find Antlr4ClassGenerationTask.IsFatalException(ex)
I appreciate your help on this.
Regards,
Omar.
I think it's a bug, I had got the same problem, but there is a solution.
1) If you want you can remove
options
{
language=CSharp_v4_0;
}
I think is ignored by the code generator
2) create a BAT file with the follow code
#echo OFF
IF "%CLASSPATH%" == "" (SET CLASSPATH=.;.\antlr4-csharp-4.0.1-SNAPSHOT-complete.jar;%CLASSPATH%)
java org.antlr.v4.Tool %* -Dlanguage=CSharp_v4_5
put antlr4-csharp-4.0.1-SNAPSHOT-complete.jar in the same path, now you can use this file to comile. To resolve the issue the magic command line argument is "-Dlanguage=CSharp_v4_5" or the version of C# you are using.
The generated files now have inside the Lexer.cs
Edit 11/20/13: Updated instructions are now available on the project wiki
https://github.com/sharwell/antlr4cs/wiki/Installation
Here are a few messages I sent over the past few months related to this issue. If you don't want to install the Visual Studio extension described below, you'll need to use the source code of Antlr4ClassGenerationTaskInternal.cs to determine a set of command line options that will work.
Also, you can remove the language=CSharp_v4_0; option because it's passed on the command line now.
The C# target wasn't designed for command line usage. You will need to integrate the code generation into your project file according to the instructions on the following page, and the parsers will be generated automatically when you build your project.
https://github.com/sharwell/antlr4cs
You do need to include the .g4 file in your project and configure a few properties of the file. If you install the following extension before adding the grammar to your project, all the other options will be configured for you automatically.
ANTLR Language Support for Visual Studio 2010-
2012
If you already have the .g4 file in your project, and want to still use the extension to automatically configure the proper settings, you can do the following:
Install the extension.
Click the project in Solution Explorer and enable Show All Files (button on the Solution Explorer toolbar). This step greatly simplifies step 4.
Right click the .g4 file in the project, and select Exclude From Project.
Right click the .g4 file again and select Include In Project.
(Optional) You can disable Show All Files when you no longer need it.

IIS 7.5 applicationHost.config file is not being updated

I'm currently playing around with the Microsoft.Web.Administration (MWA) namespace in order to adjust our application to configure IIS 7.5 with the new API.
I understood that all IIS level changes should be expressed in the following file (I'm on Win2K8-R2):
%WINDIR%\System32\inetsrv\config\applicationHost.config
So, when I use the ServerManager object to commit the configuration changes the file should be updated accordingly.
After adding a new MIME type (programmatic with MWA) I did not see any changes in the applicationHost.config file, but I do see the new MIME type in the IIS manager window and IIS recognizes this MIME type without problems. Even after restating the OS - The config file does not contain the newly added MIME type, but the IIS manager window does list it.
Because my application pools are forced to 32-bit (Enable32BitAppOnWin64 = true), I thought that the related config file should be located under %WINDIR%\SysWOW64\inetsrv\Config, but (if it exists...) - it also does not change after the code commits the updates.
Can someone please explain this? Am I missing something (looking at the wrong file maybe?)? Can someone please shed some light on the SysWOW64\inetsrv\config directory?
This is my code for adding the MIME type:
ServerManager manager = new ServerManager();
ConfigurationElementCollection staticContentCollection = manager
.GetApplicationHostConfiguration()
.GetSection("system.webServer/staticContent")
.GetCollection();
//MIMETypes is a string[] array, each object is {FileExt},{MIMETypeStr}
foreach (string pair in MIMETypes)
{
string[] mimeProps = pair.Split(',');
ConfigurationElement mimeTypeEl = staticContentCollection
.Where(a =>
(string)a.Attributes["fileExtension"].Value == mimeProps[0])
.FirstOrDefault();
if (mimeTypeEl != null)
{
staticContentCollection.Remove(mimeTypeEl);
}
ConfigurationElement mimeMapElement =
staticContentCollection.CreateElement("mimeMap");
mimeMapElement["fileExtension"] = mimeProps[0];
mimeMapElement["mimeType"] = mimeProps[1];
staticContentCollection.Add(mimeMapElement);
}
manager.CommitChanges();
//At this point all is working but the config file does not reflect the change
I just tried your code and it works fine. You are aware that this mime type is being added to the global mime type collection and not to a site?
It also gets added to the end of the <staticContent> list, this list isn't re-sorted when you do ServerManager.CommitChanges().
Also on Windows 2008-R2 the correct location for applicationHost.config is at:
C:\Windows\System32\inetsrv\config
I'm guess you're either using notepad.exe or NotePad2 to open this file (32 bit editors can't open it). Notepad won't reload the file upon a change and NotePad2 needs to be told to display a file change notification (alt-F5), out of the box it won't.
Also try adding something unusual like .xxx, run your update then open the config file and do a search. I guarantee it'll be there.
Update:
Further to your comments below, I'm not sure how you're able to open applicationHost.config using NotePad++ or any 32-bit editor, I certainly can't. Can you download NotePad2 which is a 64-bit editor:
http://www.flos-freeware.ch/notepad2.html
The release candidate works just fine.
On a default install of any 64 bit Windows 2008 or Windows 7 there shouldn't be an applicationHost.config in the C:\Windows\SysWOW64\inetsrv\Config folder. I'm not sure why you'd be seeing one there.
As a workaround to open and edit the 64-bit IIS configuration files with your favorite 32-bit editor that is 64-bit compatible (i.e. Notepad++), you can create a Windows directory symbolic link which points to C:\Windows\System32\inetsrv\Config. With this method, you are replacing the 32-bit Config directory, located at C:\Windows\SysWOW64\inetsrv\Config to point to the 64-bit version. If, for example, you have an application which requires both 32-bit and 64-bit versions, this method won't work.
For more information, I strongly encourage you to visit this MSDN Blog.

Can we change the settings of the Windows applications app.config?

I have two app.config's in my application where i have written two connectionstrings in one config file and another two in other config file .Now in .cs file i have written this
string Connect = ConfigurationManager.ConnectionStrings["con1"].ConnectionString.ToString();
string Connect = ConfigurationManager.ConnectionStrings["con3"].ConnectionString.ToString();
Now first line gives the connectionstring from app.config.But for the second line am getting an error that "object reference not set to an instance"
Can any one tell me how to use the connection from different app.config's
Per Microsoft's documentation for the ConfigurationManager class, the ConnectionStrings property operates on the current application's default configuration file.
I believe that what you probably want to do is use the OpenExeConfiguration method to read the second app.config file then use the returned Configuration class instead of the static ConfigurationManager.

Resources