I'm trying to connect my Azure Web App to my AzureSQL database.
In the Kudu Env (https://{my-app-name}.scm.azurewebsites.net/env) there is some kind of default connection string:
LocalSqlServer
- ConnectionString = data source=.\SQLEXPRESS;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
- ProviderName = System.Data.SqlClient
I have set the connection string in the App configuration, it looks like this:
Data Source=tcp:myapp.database.windows.net,1433;Initial Catalog=databaseName;User ID=databaseSA;Password=password;
But no matter what I try, the connection string in the Kudu environment never changes.
This connection string is also set no where by me, neither in the code base nor in any Azure settings I found.
It's very similar to this SO, which never got resolved: Azure Web App Not Showing Connectionstring in Kudu Env
This is the error message that throws when the app tries to access the database, which makes sense since the connection string tries to connect to .\SQLEXPRESS which doesn't exist anywhere (locally I use .\SQL2019 as connection string):
I would appreciate any help or hint.
So after 3 days I finally managed to get it to work.
First I got it running locally, be sure to white list your IP in the Azure database firewall settings.
Then I got it running in Azure and checking all the names and settings again.
I used the first connection string from my Azure database (SQL Authentication) with the database SA user.
I set that connection string in the connection string of the Azure Web App.
Also make sure that the connection string in your code is the same as the one in the Azure Web app configuration.
Also during some point my App didn't run anymore due to errors in the .Net code, so beware of that.
I thought I had tried this already before posting here, but I guess there were some wrong settings in all these tests.
I am currently working on an ASP.NET MVC project with Entity Framework. The solution includes the ASP.NET MVC application and a DataProvider project. The project only includes an EF model, as I have a partner who shares a database with me.
The problem is in that, that we don't actually share the same database. What I mean is that the actual server of the database is not the same. We have the same tables. But the connection string has to be changed every single time we pull from our git repository. The string changes in the web.config file of the ASP.NET MVC project and in the app.config file of the EF library.
My question is - if there is a way for our system to detect which PC it is running on and modify the connection string dynamically? Now I do it manually.
<!--PC NICO CEI-->
<!--
<connectionStrings>
<add name="dbShubertEntities"
connectionString="metadata=res://*/ModelDbShubert.csdl|res://*/ModelDbShubert.ssdl|res://*/ModelDbShubert.msl;provider=System.Data.SqlClient;provider connection string="data source=E04\SQLEXPRESS;initial catalog=dbShubert;user id=gereisma17;password=12321;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
-->
<!--PC NICO Laptop-->
<!--
<connectionStrings>
<add name="dbShubertEntities"
connectionString="metadata=res://*/ModelDbShubert.csdl|res://*/ModelDbShubert.ssdl|res://*/ModelDbShubert.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-I62BLOC;initial catalog=dbShubert;user id=user;password=1234;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
-->
This is what I do now. I am commenting the connection string. I want to automate the whole thing.
You could overload the DbContext's constructor with the dynamic connection string
public class MasterDal : DbContext
{
public MasterDal(string nameOrConnectionString) : base(nameOrConnectionString)
{
}
// DbSet & OnModelCreating etc
}
& then invoke dal in Controller as required
if (logicToGetPc.equal("CEI"))
{
MasterDal dal = new MasterDal("dbShubertEntitiesCEI");
// do mumbai related whatever
}
else if (logicToGetPc.equal("Laptop"))
{
MasterDal dal = new MasterDal("dbShubertEntitiesCEILaptop");
}
if you are using aspnet core there is a way to configure environment variable as override for the app settings
this way you'll have a "default" appsettings.json that contains all the common settings, then on the different machine you can configure environmnet variables that replaces (override) the connection string in different way for each machine
i suppose a similar approach is possible for aspnet for the full framework as well
as your connection string have already a quite specific name "dbShubertEntities" it sould be quite effective to override and you should not risk to have connection string collisions in case you work on different projects.
as reference see https://joonasw.net/view/asp-net-core-1-configuration-deep-dive the part where it uses .AddEnvironmentVariables()
Store the connection string as an environment variable on each PC.
When creating the connection to the database, retrieve the connection string using Environment.GetEnvironmentVariable method instead.
(at time of writing, there's no code)
This is what appsettings.json, (or it's counterparts), was made for.
As i perceive your predicament, (you need more whitespace in your writing to make it easier to read), you are basically working in two different environments, (similar to dev versus test). A simple configuration change would be the simplest way.
As an aside:
Reading between the lines, it seems like you are hard-coding connection strings, and I have a two-word advice for you: STOP IT! (I used to do that, and It's a bad habit that can be hard to shake off)
I have developed a website application under visual studio using the MVC Pattern and Entity Framework 6.
This web app was linked to a local database.
I've published the application on my azure acc. I also exported the database on Azure following this tutorial.
However, I can't find a way to link the online app to the migrated database.
No data is displayed on the app and when I try to check for the connexion string I get an error , the connexion string hasn't been updated and therefore the app is still trying to target my local database.
I would like to know if anyone might know how to solve this.
EDIT : The problem may be somewhere else, I apparently have two connexions , one for my migrated DB and one for my local db. Perhaps I need to remove the connexion string targetting my local DB but I don't know how to do that
Also, since the Migrated database is a copy from the local one I was using before, do I need to change anything in my Model,views or controller ?
EDIT2 : Thanks to the comment below I was able to override the false Connexion String. However my datas are still not displayed on my application and I haven't found yet what could have happend.
I suspect that my model is still the same model as the one used by the local database as it has the same name. Does anybody know how to change the model to the current model of the online database ?
Thanks.
Because you created your app with entity framework there should be a connection string defined in the web.config file pointing to the local database.
<connectionStrings>
<add name="MyContext" connectionString="..."
providerName="System.Data.SqlClient" />
</connectionStrings>
If you have published your Website as WebApp (App Service) then you can change the connection string for the database under the Application Settings pane on the WebApp Page.
You can override your connection string by creating a connection string settings entry with the name of the connection string in the web.config file.
(For the snippet above - MyContext)
I just created a desktop Winforms application with localhost database.
The connect string I am using is this:
SqlConnection connect = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Administrator\Desktop\learningsystem\LearningSystem\LearningSystem\LearningSystem.mdf;Integrated Security=True");
If I want to run my application on other computers, how should I make it work?
EDIT:SOLUTION
Thank for all the help! I tried the following steps. I think it is working now. But please correct me if I did something tricky.
1. add a new setting item in project property setting. App.config will automatically update:
<connectionStrings>
<add name="LearningSystem.Properties.Settings.LearningConn" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\LearningSystem.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient" />
</connectionStrings>
2. In my program, just add the following statement to connect to the sql server
SqlConnection connect = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\LearningSystem.mdf;Integrated Security = True; Connect Timeout = 30");
Further question
If others will run this application on their computer(not in the same network), they just go into the project setting and change the value by selecting the database file I provide to them,the connectionString will automatically change, right?
Thanks!
It's generally a bad idea to hard code such stuff in your application. Normally, application settings and connection strings are placed in the application's configuration file (in the ConnectionStrings section).
Just like with all strings, you could build your connectionstring from dynamic parts (variables, settings, etc.) and then pass that generated connectionstring to the SqlConnection constructor. Again, to make those separate parts configurable without hard coding them in your application, you might want to add them to your application's configuration file (in the AppSettings section). But IMHO this is an overly complex solution in most scenarios. Putting the entire connectionstring in the ConnectionStrings section is more straightforward (and more flexible).
Anyway, again, to make your application configurable, you might use your application's configuration file (App.config or Web.config), you need to add a reference to System.Configuration in your project's .NET Framework dependencies and use the AppSettings and ConnectionStrings properties of the System.Configuration.ConfigurationManager class.
(Of course, there are more ways to make your application configurable. But using the application configuration file is one of the most straightforward solutions.)
Edit:
When deploying your app to another computer, you need to copy its database over too. If you want to use the application on multiple machines and let them connect to the same database, you might want to leave LocalDB and migrate the data to a SQL Server (Express) instance and make it accessible over the (local) network.
Edit 2 (regarding the recent edits in your post):
I see in step 1 that you are using an application setting (called LearningConn) in your solution now. That's fine. However, it is important that you also use that setting in step 2, like this:
SqlConnection connect = new SqlConnection(Properties.Settings.Default.LearningConn);
If you change the setting in Visual Studio, it will update the connection string. Since the setting will probably have application scope, it will not be possible to update the setting/connection string within your application in runtime (by the user).
I'm not sure if your connection string using |DataDirectory| will always work as expected in all scenarios. I have only been using it in ASP.NET webapplications. If it does work in WinForms applications, you might read this document to learn how to set it up. But personally I am somewhat sceptical about this approach.
I personally would opt for a solution where you use a placeholder in your connection string, which you replace with the full path to the .mdf file before you pass it to your SqlConnection constructor.
When you use "{DBFILE}" as the placeholder, for example, the value of your LearningConn setting would look like this:
Data
Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={DBFILE};Integrated
Security=True;Connect Timeout=30
(Note that this value should be a single line without any line breaks!)
You might create a separate setting in your application called DbFile (of type string) to store the actual value that should be put in place of {DBFILE} in your connection string. When you use scope "user" for that setting, the value might be changed from within the application by the user. When saved, it might not be saved directly in the application's configuration file, however, but in an additional configuration file hidden somewhere in the user's Windows user profile. You might read this document to learn more about application settings.
Your code in step 2 might eventually look something like this:
string connectString = Properties.Settings.Default.LearningConn;
string dbFile = Properties.Settings.Default.LearningSystemDb;
connectString = connectString.Replace("{DBFILE}", dbFile);
SqlConnection connect = new SqlConnection(connectString);
To let your application's users select and store the database .mdf file to use, you might include (a variation of) the following code in your application somewhere:
using (var dlg = new System.Windows.Forms.OpenFileDialog())
{
dlg.Title = "Select database file to use";
dlg.Filter = "Database Files (*.mdf)|*.mdf";
dlg.CheckFileExists = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Properties.Settings.Default.DbFile = dlg.FileName;
Properties.Settings.Default.Save();
}
}
Your question is not clear!
you need work with one Database on 2 or more PC?!
OR
you need work with 2 separate programs?
if you need 2 separate programs :
you must copy .mdf file to other PC at same address or keep mdf address in app.config and read it before connect to SQL.
How to Read From app.config
if you need work with one Db you must connect to dataBase Server such as SQL Server and keep connection string in app.config in connectionStrings tag.
Get connection string from App.config
If you want to work on other PCs, rather than building it dynamically make the connection string more generic:
Server=(localdb)\\mssqllocaldb;Database=LearningSystem;Trusted_Connection=True;MultipleActiveResultSets=true
This should create the mdf file under 'mssqllocaldb' in %appdata% for each user. You might need LocalDb installed (which you tick during SQL Server installation)
I have an ASP.NET application which runs fine on my local development machine.
When I run this application online, it shows the following error:
Format of the initialization string does not conform to specification starting at index 0
Why is this appearing, and how can I fix it?
Check your connection string. If you need help with it check Connection Strings, which has a list of commonly used ones.
Commonly used Connection Strings:
SQL Server 2012
Standard Security
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Connection to a SQL Server instance
The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;
Password=myPassword;
SQL Server 2005
Standard Security
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Connection to a SQL Server instance
The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;Password=myPassword;
MySQL
Standard
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Specifying TCP port
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Oracle
Using TNS
Data Source=TORCL;User Id=myUsername;Password=myPassword;
Using integrated security
Data Source=TORCL;Integrated Security=SSPI;
Using ODP.NET without tnsnames.ora
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;
This might help someone..
My password contained a semicolon so was facing this issue.So added the password in quotes. It was really a silly mistake.
I changed the following :
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password=pass;word" providerName="System.Data.SqlClient" />
to
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='pass;word'" providerName="System.Data.SqlClient" />
Set the project containing your DbContext class as the startup project.
I was getting this error while calling enable-migrations.
Even if in the Package Manager Console I selected the right Default project, it was still looking at the web.config file of that startup project, where the connection string wasn't present.
Check your connection string like I forget to add services.AddDbContext<dbsContext>(options => options.UseSqlServer("Default"));
It causes the error and here when I add Configuration.GetConnectionString, then it solves the issue
like now the connection is:
services.AddDbContext<dbsContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
works fine (This problem is solved for .net core)
Make sure that your connection string is in this format:
server=FOOSERVER;database=BLAH_DB;pooling=false;Connect Timeout=60;Integrated Security=SSPI;
If your string is missing the server tag then the method would return back with this error.
I had the same problem. Locally the site ran fine, but on azure it would fail with the message above.
turns out the problem was setting the connectionstring in the ctor, like this:
public DatabaseContext()
{
Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
}
Does NOT work, this will:
public DatabaseContext() : base("db")
{
}
Beats me..
Referencing the full sp path resolved this issue for me:
var command = new SqlCommand("DatabaseName.dbo.StoredProcedureName", conn)
I removed " at the end of the connection string and it worked
Instead of
App=EntityFramework"
Used
App=EntityFramework;
Set DefaultConnection as below
<add name="DefaultConnection" connectionString="data source=(local);initial catalog=NamSdb;persist security info=True;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework;" providerName="System.Data.SqlClient" />
Note : In connectionString Do not include :
|x| Metadata info : "metadata=res://*/"
|x| Encoded Quotes : """
I solved this by changing the connection string on the publish settings of my ASP.NET Web Api.
Check my answer on this post: How to fix error ::Format of the initialization string does not conform to specification starting at index 0::
I had the same error. In my case, this was because I was missing an closing quote for the password in the connection string.
Changed from this
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password" providerName="System.Data.SqlClient" />
To
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password'" providerName="System.Data.SqlClient" />
In my case, I got a similar error:
An unhandled exception was thrown by the application. System.ArgumentException: Format of the initialization string does not conform to specification starting at index 91.
I change my connection string from:
Server=.;Database=dbname;User Id=myuserid;Password=mypassword"
to:
Server=.;Database=dbname;User Id=myuserid;Password='mypassword'"
and it works, I added single quotes to the password.
In my case the problem was in the encoding of the connection string.
In local it worked without problems, but when installing it in a production environment it showed this error.
My application allows to set the connection string using a form and when the connection string was copied from local to production, invisible characters were introduced and although the connection string was visually identical at the byte level it was not.
You can check if this is your problem by following these steps:
Copy your connection string to Notepad++.
Change the codification to ANSI. In Menu Encoding>Encode to ANSI.
Check if additional characters are included.
If these characters have been included, delete them and paste the connection string again.
Got this problem with SQLite in aspnetcore. I wrote
"DefaultSQLiteConnection": "MyBlog.db"
instead of
"DefaultSQLiteConnection": "Data Source = MyBlog.db"
My generated password contained few characters that were valid in AWS RDS, but for some reason my .NET app could not handle it. The solutions that worked for me, was to generate new password without characters like ` (backtick).
In my case, it was...
index: 58
but what ended up happening was the password generated had a single quote in it. SQL Server accepted that, but my connection string had trouble parsing it. Hope this saves someone at least a few minutes, because it cost me an hour to two before I relized what was going on. cheers
Hope this helps someone in the future. My connection string had blank values wrapped in double quotes, e.g. User ID="". So to resolve it I had to escape the double quotes.
Dim ConString = "Data Source=MYSERVER;User ID="";Initial Catalog=Northwinds..."
ConString = ConString.Replace("""", """""")
This also happens when you copy a web page from one solution to another, then you run your solution and find out that it has a different connection string name in the webconfig. Then you carelessly change the name of the connection string in the properties panel in the design view of the page.
Better to just change it in the code portion instead of the design.
My problem was I added database logging code to my constructor for a DB object, and this seemed to cause havoc on my azure deployment profile.
FYI - I simplified this example, in the real code this was turned off in production (but still in the code)
public class MyDB : DbContext
{
public MyDB()
{
this.Database.Log = x => { Debug.WriteLine(x); };
}
}
I had typo in my connection strings "Database==PESitecore1_master"
<add name="master" connectionString="user id=sa;password=xxxxx;Data Source=APR9038KBD\SQL2014;Database==PESitecore1_master"/>
I had the same problem and finally I managed to resolve it in the following way:
The problem was in the connection string definition in my web.config.
<add name="DefaultConnection" connectionString="DefaultConnection_ConnectionString" providerName="System.Data.SqlClient"/>
The above worked perfect locally because I used a local Database when I managed users and roles. When I transfered my application to IIS the local DB was not longer accessible, in addition I would like to use my DB in SQL Server. So I change the above connection string the following SQL Server DB equivalent:
<add name="DefaultConnection" connectionString="data source=MY_SQL_SERVER; Initial Catalog=MY_DATABASE_NAME; Persist Security Info=true; User Id=sa;Password=Mybl00dyPa$$" providerName="System.Data.SqlClient"/>
NOTE: The above, also, suppose that you are going to use the same SQL Server from your local box (in case that you incorporate it into your local web.config - that is what exactly I did in my case).
I had the same issue, came to find out that the deployment to IIS did not set the connection strings correctly. they were '$(ReplacableToken_devConnection-Web.config Connection String_0)' when viewing the connection strings of the site in IIS, instead of the actual connection string. I updated them there, and all worked as expected
I copied and pasted my connection string configuration into my test project and started running into this error. The connection string worked fine in my WebAPI project. Here is my fix.
var connection = ConfigurationManager.ConnectionStrings["MyConnectionString"];
var unitOfWork = new UnitOfWork(new SqlConnection(connection.ConnectionString));
My problem wasn't that the connection string I was providing was wrong, or that the connection string in the app.config I thought I was using was wrong, but that I was using the wrong app.config.
For the one other unfortunate soul that is managing a legacy webforms application that uses an inline sqldatasource, along with connection strings stored in web.config, then you may get this error if you access your connection string like <%APSDataConnectionString%> instead of
<%$ ConnectionStrings:MyConnectionString %>. This happened to us when upgrading .NET from 3.5 to 4.x.
<asp:DropDownList ID="ddl" runat="server" DataSourceID="SqlDataSource1"
DataTextField="value" DataValueField="id"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="select id, value from a_table">
</asp:SqlDataSource>
In my case the problem was that on the server, a different appsettings.json file was used by the application.
I had this error too and was able to solve it as follows:
I previously wrote the connectionstring to the appsettings.json into a section that I created (ConnectionsStrings (notice the extra "s") and tried to connect to my database which caused the error. It was an ASP.NET CORE application and so I wanted to connect to it with the .GetConnectionString Method (details on that here). It seems that this method implicitly searches for a connectionstring in the "ConnectionStrings"-section, which didn't exist. When I changed/corrected it to "ConnectionStrings" it worked as expected.
I had the same problem spent an entire day. The error indicates Connection string issue for sure as index 0 is connection string. My issue was in the Startup class. I used:
var connection = Configuration["ConnectionStrings:DefaultConnection"];
services.AddControllersWithViews();
services.AddApplicationInsightsTelemetry();
services.AddDbContextPool<Models.PicTickContext>(options => options.UseSqlServer("connection"));`
which is wrong instead use this:
services.AddControllersWithViews();
services.AddApplicationInsightsTelemetry();
services.AddDbContextPool<Models.PicTickContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
and my problem was solved.
I had this error and it turned out that the cause was that I had surrounded a (new) tableadapter with a Using/End Using. Just changing the tableadapter to stay live for longer (duration of class in my instance) fixed this for me. Maybe this will help someone.
Sometimes the Sql Server service has not been started. This may generate the error. Go to Services and start Sql Server. This should make it work.
As I Know, whenever you have more than 1 connection string in your solution(your current project, startup project,...), you may confront with this error
this link may help you
click