Problems attempting to read web.config from a Windows application - web-config

I'm writing a WPF application to help non-XML-savvy customers set up configuration files on a web server. web.config is one of these files. I have custom sections defined, but I've commented them out until I get the basics working.
In web.config, I have this:
<appSettings>
<add key="buffer" value="65536"/>
<add key="updateInterval" value=""/>
</appSettings>
Here's a snippet of how I'm reading web.config (I have already confirmed that web.config exists inside AppPath):
var vdm = new VirtualDirectoryMapping(AppPath, true);
var wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
However, WebConfigurationManager.AppSettings["buffer"] returns null. Any ideas?

Duhhhh. It's Monday morning. :-)
var config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
config.AppSettings["buffer"];
works.

Related

PetaPoco POCO generation fails with Sequence Contains More Then One Matching Element

PostgreSQL 9.5 Npgsql 3.1.9
I have been using PetaPoco with Npgsql to generate the POCO's with the Database.tt. All has worked well until today. After remaking the schema's in PostgreSQL, now running the Database.tt gives the error:
// This file was automatically generated by the PetaPoco T4 Template
// Do not make changes directly to this file - edit the template instead
// The following connection settings were used to generate this file
// Connection String Name: localconnection
// Provider: Npgsql
// Connection String: Server=127.0.0.1;Port=5432;Database=chaos;User
Id=postgres;password=**zapped**;Searchpath=nova
// Schema: ``
// Include Views: False
//
// Failed to read database schema - Sequence contains more than one matching element
I could find nothing in Google that address:
What does this mean (for PetaPoco), why did it happen, and how do I fix it?
TIA
Edit#1: If it helps any, in stepping through the T4 template, the _factory type
resolves to SQL Server CE --not NpgsqlFactory -- despite having the correct connection string.
_factory.GetType().Name == "SqlCeProviderFactory"
Edit#2: By rewriting LoadTables() in PetaPoco.Core.ttinclude by placing the
else if (_factory.GetType().Name == "NpgsqlFactory")
Edit#3: Now went back to PetaPoco v 5.1.211, still the same error???
The problem appears to be in LoadTables() which for Npgsql will load every table of every schema initially--even though a specific schema is listed in the searchpath, but then (why?) it zeroes out the table count before generating the tables.
Can anybody help with this??
Npgsql was installed from Nuget, as was PetaPoco.
For reference, all worked great before recreating and renaming the schemas.
The app.config is:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>
<system.data>
<DbProviderFactories>
<remove invariant="Npgsql" />
<add name="Npgsql Data Provider" invariant="Npgsql" support="FF"
description=".Net Framework Data Provider for Postgresql Server"
type="Npgsql.NpgsqlFactory, Npgsql" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<clear/>
<add name="localconnection" providerName="Npgsql"
connectionString="Server=127.0.0.1;Port=5432;Database=chaos;User Id=postgres;Password=password;Searchpath=nova"/>
</connectionStrings>
The Database.tt is set up with:
// Settings
ConnectionStringName = "localconnection"; // Uses last connection string in config if not specified
Namespace = "chaos";
RepoName = "chaosDB";
GenerateOperations = true;
GeneratePocos = true;
GenerateCommon = true;
ClassPrefix = "";
ClassSuffix = "";
TrackModifiedColumns = false;
ExplicitColumns = true;
ExcludePrefix = new string[] {}; // Exclude tables by prefix.
This is what worked, but points out some inherent problem with LoadTables() as it applies to Npgsql when the PostgreSQL database has multiple schemas--I'm guessing a name conflict somewhere..
I went back to my PostgreSQL database and dropped every schema except the one I needed. Now running the Database.tt template correctly and quickly produced the POCO's without error.
Additionally, the previous version of PetaPoco had no problem with multiple schemas--its the newest version that seems to have difficulties.

EF5 Code First Migration problems publishing to IIS

I've created a MVC 4 project which uses EF5 Code First with migrations.
Because I was new to this topic I used the following article.
Now that the development is finished I want to publish to IIS (I use FTP or Web deployment package). So before publishing I changed the connectionstring to the right db server.
But after publishing the site I get an exception when accessing pages which make use of the DB. The exceptions refers to the fact that he can't connect to the database.
Because of these problems I decided to try it out locally on another DB server than the default one "(LocalDB)\v11.0". BTW: "(LocalDB)\v11.0" works like a charm...
While debugging I got a better look at the error.
Here is an image of the error:
What I've already tried:
Generate a sql script by executing "Update-Database -Script
-SourceMigration:$InitialDatabase" in the Package manager console. After I ran this script on the dbserver to create the db. Tables were
created but the error was still there.
I changed my connectionstring to all kinds of combination with no
results
I already used a custom user for the app pool in ISS and gave this user full rights to the DB server and the db.
Here is the most important part of my web.config:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=LOCALHOST\MSSQLSERVER;Initial Catalog=ProjectX;Integrated Security=TRUE;MultipleActiveResultSets=True" />
</connectionStrings>
And
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=LOCALHOST\MSSQLSERVER; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
My DBCcontext class constructor looks like
public DBContext(): base("DefaultConnection")
{
}
I guess I am missing something, this is the first time I use EF Code First with migrations.
This problem is really driving me crazy. I am out of ideas.
Just found out that the problem was caused by the connectionstring.
The string was incorrect, seems like you if you have a default SQL Server you just need to use
"Data Source=LOCALHOST".
I guess because of all the problems I had that day with the deployment i overlooked the easy parts. Yust make sure you the following things are true when you have problems like I did:
Your connectionstring has the same name as your DBContext. Another sollution could be to do like i did and add the connectionstring name to the base:
public DBContext(): base("DefaultConnection")
{
}
If you also have the defaultconnectionfactory set. Make sure to also update the Data Source there. This was one of the problems I struggled with. I didn't check the bottom of my web.config ...
If the problem still persists you can use EF profiler to have a look at the connectionstring when your app of site is accessing the DB.

multiple applications single config file

I'm trying to write a service and configuration application. VB/C++ 2010 I've had a number of hits on google but they largely seem to be obsolete. What I have so far is a project with a single form app and a service app. The single form app has an "app.config" file and I have added a section:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="settings.config">
</appSettings>
</configuration>
In the Solution I have added a "settings.config" file and its contents is:
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="Setting1" value="This is Setting 1 from settings.config" />
<add key="Setting2" value="This is Setting 2 from settings.config" />
<add key="ConnectionString" value="ConnectString from settings.confg" />
</appSettings>
I have added a reference to then C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\System.Configuration.dll
library in both the forms app and the service app
In the very simple forms app i have the following code
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim s As String = _
System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
TextBox1.Text = s
End Sub
It doesn't work! Now clearly I am missing something. Its probably very simple. But my limited understanding is that this is automatically configuered by the config files I have? MS in their usual helful fashion seem to only give samples for 2012 and net 4.5 or greater. I need this to work on a 2003 server (as well) so I'm limited to net 4.0
The problem here is that the line System.Configuration.ConfigurationManager.AppSettings("ConnectionString") is looking for the key ConnectionString in your application's app.config file.
The fact that you have included that file key in your app.config file doesn't magically tell the ConfigurationManager to load the settings from a different file. If that's what you want you will have to read the setting for the file key and then manually load the configuration from that file.
This has not changed since the early versions of .Net though so I'm not sure why you were conflicted by the examples.
Add reference on existing assembly in .Net section of your Add Reference Popup
But i suggest you to use connectionStrings section in your config file
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

Using a separate file to maintain the connection string for entity framework

I have my connection string currently in my web.config file.
Is it possible to place it in a separate file and point entity framework to it.
I found the answer here Separate ConnectionStrings and mailSettings from web.config? Possible?:
<configuration>
<connectionStrings configSource="connections.config"/>
</configuration>
With file connections.config containing
<connectionStrings>
<add name="name" connectionString="conn_string" providerName="System.Data.SqlClient" />
<add name="name2" connectionString="conn_string2" providerName="System.Data.SqlClient" />
</connectionStrings>
In case anyone stumbles upon this question. You can put the connection strings in a separate config file using configSource but DONT expect the EF designer to work happily with it.
Every time to go to edit the edmx and 'Update from Database' it will ask for a new connection string and then always want to save it back to the web.config. Not ideal and for me not workable. This is the case in EF6 and previous.

Connection Strings - MVC Entity Framework - Database First

Can anyone suggest how I could programatically switch debug and live connection strings?
I've seen other people have passed an EntityConnection to the constructor from the controller like this :
private XYZDatabase db = new XYZDatabase(ConfigurationManager.
ConnectionStrings["XYZDatabase-TEST"].ConnectionString);
but it still requires manually changing it? is there a way to use
System.Net.Dns.GetHostName() or similar
to switch it automatically?
Thanks
Ayende has a post that addresses this issue.
http://ayende.com/blog/135169/frictionless-development-web-config-and-connection-strings
In my software I just have 2 connection strings of the same name in my app.config and comment/uncomment to switch between configurations.
Another method is that you could create a static property in your solution (.asax file?) and just use that to swap between XYZDatabase-TEST and XYZDatabase when you are fetching ConnectionStrings.
Add connection string to your Web.config like:
<connectionStrings>
<add name="XYZDatabase-TEST" connectionString="Server=.\SQLEXPRESS;Database=XYZDatabase-TEST";integrated security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
Then open you Web.Release.config and add
<connectionStrings>
<add name="XYZDatabase-TEST"
connectionString="Data Source=OTHERSERVER;Initial Catalog=XYZDatabase-TEST;Persist Security Info=True;User ID=sa;Password=password" providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)"/>
</connectionStrings>
Now, everytime you will publish you application to deployment server using Release configuration it will use the connection string from web.release.config
Note that this transformation will not work locally when you debug. You must publish to run the web.config transformation.