Maintaining both on-line (Azure) and off-line version of a website - c#

Note: Not sure if the question is asked the right way. This is how I perceive the issue but it's fully possible that the problem is addressable form a totally different angle, which I'm unaware of due to the ignorance.
Question
Is there a built-in database available for an out-of-the-box, MVC solution? If so, how do I find out its connection string?
Current string is for Azure and looks like this (frankly, it scares living excrement out me because I don't understand most of it).
<add name="DefaultConnection" connectionString="
Data Source=(LocalDb)\v11.0;
Initial Catalog=aspnet-Plong-20141107210818;
Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\aspnet-Plong-20141107210818.mdf"
providerName="System.Data.SqlClient" />
Background info
I'm developing a site and publish it to the Azure. It has some connections to the database and I'm using Code First and Entity Framework. Everything works great (maybe except the fact that it takes a few seconds to upload and initialize the page prior showing, which is annoying if I've only made changes to the markup of Razor).
In fact, all's been set up pretty much automagically, and I didn't have to configure much at all. Now, it's biting my in the sitting device because of the following.
I need to be able to run my site on the local host (using F5, if you will) because I'll be going off-line (or at the very least under a very lousy connection). I can do that right now, except for the page that contacts the database reference, where I'm getting the error below.
I get what the problem is - no local DB set up using code first. I wonder if there's a lazy man's solution to it (using some built in DB and code-first-able). If so, where do I set it up? I prefer to keep the reference to default connection string as intact as possible but if I need to edit it (or, most likely, add a new one and reference it), how do I learn the correct connection string?! (Yes, I know, this is the price I pay for taking an easy way out letting Azure configure everything for me. Head down in shame.)
{"Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations."}

As far as I know that's not a connection string to SQL Azure, but for a local (development) database. It will create a .mdf file in your App_Data folder. You can find connection strings to SQL Azure somewhere in the Azure dashboard. I switch between dev en production using for example:
public MyContext : DbContext
{
public MyContext()
#if DEBUG
: base("development")
#else
: base("production")
#endif
{
}
}
However, you could also use XML transformation of the web.config, web.debug.config and web.release.config. Note that web.debug.config is not really used when you run your application locally, so put your development connection strings in web.config and publish your application in release mode so the XML transformation of web.release.config takes place.
Edit: Get the SQL Azure connection string
Got to the management portal and click on SQL Databases. Click on the database and go to Dashboard. On the right side you see "Show connection strings". It looks something like this:
Server=tcp:xxx.database.windows.net,1433;Database={your_db_name};User ID={your_user_id};Password={your_password_here};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;

Related

ASP.NET and C#: connection string in web.config vs connection string stored on Azure

I have a web form developed in ASP.NET and C#. I am storing the connection string to a database in the web.config file like this:
<connectionStrings configSource="MySecrets.config" />
This points to a local file in the same directory as the solution. Debugging locally works, however it is not advisable to commit this file to source control to avoid exposing these secrets.
This article mentions that it is possible to store connection strings on Azure - in the Configurations section of an App Service. The article also says that it's possible to retrieve the connection strings in the code by doing:
dbConn = System.Configuration.ConfigurationManager.AppSettings("myConnStringName")
The article also mentions that "if the application setting(s) happen to already exist in your web.config file, Windows Azure Web Sites will automatically override them at runtime using the values associated with your website. Connection strings work in a similar fashion.
(This assumes that your connection strings are explicit in the web.config file, and if committed to source control, they would be exposed.)
However, in my code, I already have a line with:
dbConn = WebConfigurationManager.ConnectionStrings["myConnStringName"].ConnectionString
Questions:
1) How am I supposed to reconcile these two lines without declaring the same variable (dbConn) twice?
2) How can I not commit MySecrets.config to source control, but at the same time use it when I debug my app locally, while using the connection string stored on Azure when working with the published app?

Entity Framework - Database first - Intercepting DbContext

I am developing a Web API that uses Entity Framework 6. The Connection String for Entity Framework is encrypted with a company standard encryption. (sql server 2014) I can decrypt the connection string just fine, but I have not been able to figure out how to intercept DbContext to set the decrypted connection string. (Before the Web.config had an encrypted connection string, I was able to run the API just fine, and all database calls works appropriately)
The code below shows how I have circumvented the issue thus far. I have created a partial class for my context class, since the Peliquin.Context.cs class is generated code. I am decrypting the connection string, which as I've verified, looks exactly correct, then passing it into this class. The previous code was :base("name=ConnectionName")
The error message seems as if DbContext cannot have an actual connection string passed into it. But if I pass in the connection name, it runs into an issue with the connection string being encrypted.
I have searched and have been unable to find the solution to this seemingly simple problem. Any help would be appreciated.
The web.config connection string, before I decrypt it at runtime:
Side note: This website will get deployed to several client sites, each that have their own database credentials. At the time of the installer installing the API and UI web applications onto the server, another application runs that updates the web.config file to the proper client database connection. This entire process is to have no user interaction. If anybody can think of a better method of changing the web.config connection string, then encrypting it, all without human interaction, please feel free to suggest an alternate solution to me.
Well, I seemingly fixed the problem myself. In the dynamically generated code Peliquin.Context.cs, I pass in the decrypted connection string, and it all works fine. What I don't like about this solution, is that the next time the edmx file is updated with the latest database changes, this file will dynamically be generated again, wiping out my changes, which will cause havoc in the future. Having another class take the constructor, still seems like a better solution.
public PeliquinDbContext(string connection):base(connection)
{
}

Azure Mobile Services - Connection string not found after publishing

After I deployed my mobile service to Azure, calls to the service fails because of this error:
No connection string named 'ApplicationEntities' could be found in the application config file.
The error only occurs on Azure side. When I test the service locally, the connection to the remote database works without a problem.
I separated my solution into several projects:
Web Api
Business Logic
Data Access (contains the DbContext, database first)
Common (contains the entities generated by EF)
As I always do, I copied the connection string generated in my app.config of the DataAccess Assembly into the connectionStrings-Element of my web.config (Web Api project).
<connectionStrings>
<add name="ApplicationEntities" connectionString="<the connection string>" providerName="System.Data.EntityClient" />
</connectionStrings>
In the web deploy settings, I selected the connection string for "ApplicationEntities". I tested it with and without the option "Use this connection string at runtime (update destination web.config). I always get the same error.
Then I got curious and logged the connection strings available via the ConfigurationManager with something like this:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
{
sb.AppendLine(ConfigurationManager.ConnectionStrings[i].ConnectionString);
}
trace.Info(sb.ToString());
I got two connection strings:
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
Data Source=theserver.database.windows.net;Initial Catalog=thedb_db;User ID=theuser;Password=thepassword;Asynchronous Processing=True;TrustServerCertificate=False;
The username and password is strangely different from the username and password stated in the management portal.
Also the EF-Metadata information get lost.
I get this connection strings when testing locally:
data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
metadata=res://*/DataContext.ApplicationEntities.csdl|res://*/DataContext.ApplicationEntities.ssdl|res://*/DataContext.ApplicationEntities.msl;provider=System.Data.SqlClient;provider connection string=\"data source=theserveraddress,1433;initial catalog=thedb_db;persist security info=True;user id=theusername;password=thepassword;MultipleActiveResultSets=True;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;App=EntityFramework\"
I expect to get the same connection strings when running on Azure. Any idea what's going wrong?
Update:
I just went for remote debugging the service (see here). As I opened the downloaded publish-profile in my text editor, I discovered that there is an attribute SQLServerDBConnectionString - containing the connection string that always gets forced when deployed - with the same username and password I'm not aware of that it exists.
I tried to overrwite this connection string but it did not help. That connection remains the active.
Update 2 / May 29th 2014:
Seems that in the meantime the error has been fixed by the azure mobile team. Still running the same code using the database first approach and it's working now. Thanks a lot!
I have myself tried using DB first approach with dot net backend mobile services & ran into same sort of problems as you. Digging around further, following is my observation :
The azure mobile service with dot net backend must use code first approach only. This generates a specialised connection string with metadata (starting with res:)
The name of the connection string has to be the same as it is when you download the default sample todo app I.e. Ms_TableConnectionString.
There is an option in azure websites to select custom SQL provider to help make a custom connection string, this option, however, is not available for dot net backend mobile service in Azure Management portal.
P.s. Posting as answer because I don't have a enough points to comment..
Just wanted to give an update that I have been looking at this for some time and think I for the first time see it too. I don't know what is going on but wanted to let you know that we are indeed looking at it.
Henrik
(I don't have enough points to comment so having to do this as an answer)
Henrik, I have this same problem. If I ftp on to the box I can see that the web.config has the correct connection string but it fails as trying to use the username in the SQLServerDBConnectionString property (OoWUqr****Login). Is it possible you could let me know in what order it is looking for connection strings and where?
And if it can't stop it using the other user is there a way I can permission them for the correct database through mobile services?
Thanks
F

Using WCF Service to access SQL Server in Entity Framework -- Why does it seem like it's using Integrated Security?

Quick Background
I received code from a third party (contracted software) that I have to move onto my servers. When I run the code using their connections and service references, everything works well. When I debug locally, everything works well. My problem only occurs when I try to run the application/service(s) after I move them onto my server.
The services (or their respective references) are at the heart of what's causing the issues. I created a test client to try to debug the services, and it's accessing the service, but erroring when it tries to connect to the SQL Server inside the service. The code appears to use the Entity Framework which I am admittedly not familiar with yet.
Errors/Issues
When I use my test client to call a function inside the service reference, it errors out when it tries to connect to my SQL database:
using (ApplicationDefinitionDBEntities appDefDb = new ApplicationDefinitionDBEntities()) //ERROR
Here's the error I receive (domain and server names have been made generic):
System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'MYDOMAIN\APPSERVERNAME$'.
I found the app.config that is referenced by the .edmx file (ApplicationDefinitionDB.edmx) and its accompanying files. Here is the connection string (made generic):
<add name="ApplicationDefinitionDBEntities"
connectionString="metadata=res://*/Data.ApplicationDefinitionDB.csdl|res://*/Data.ApplicationDefinitionDB.ssdl|res://*/Data.ApplicationDefinitionDB.msl;
provider=System.Data.SqlClient;
provider connection string="data source=MYDBSERVERNAME;initial catalog=myDBcatalog;
User ID=myUserID;Password=myPassword;integrated security=false;
multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
There is also an old connection string that the third party used which had integrated security set to true and reference SQLExpress, but I commented it out.
Note that I am specifying integrated security to be false (I know it's by default but I wanted to be explicit), and also supplying a username and password to the SQL Server. So why is the error message in the service ref test client saying that it's trying to connect using DOMAIN\APPSERVER$ as though it's using integrated security?
I am using IIS to host my app and SQL Server for database work. I think I have updated and re-generated all Entity Framework stuff for the database reference, but I could be missing something. Can anyone suggest anything that I may be missing to make sure the service reference uses the connection string supplied in it, and NOT the app server domain login? Thanks!
Turns out that connection string conflicted with one above the project level of the service. The project that housed the service uses Silverlight, so I thought the ClientConfig files were the only other configs being used, but there was another one hiding in the project that I published. When I rooted around in that web.config file, I found that there was a connection string with Integrated Security turned on. Once I turned that off it worked fine. That's annoying.

Connection string when database (*.mdf) is copied on the web hosting server

I am continuing my previous question, as the reply lead to further doubts/points/concerns. I need help with the connection string on the web host server.
My connection string in the local computer is:
string connectionString = "Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\data.mdf;Integrated
Security=True;User Instance=True";
Now, I simply used the website copy tool with the VS 2010, and the entire website is copied as it is on the web host, with the database being at domainName/httpdocs/Experiment/App_Data/data.mdf
Now, I don't know how the complete connection string on the web hosting server look like. Some of the things which I learned, on the basis of those, I guess it should be:
string connectionString = "Data
Source=IP_Address_Of_WebHostingServer;AttachDbFilename=|DataDirectory|\data.mdf;User
ID=XXXX;Password=XXXX;User Instance=True";
Is it right (or COMPLETE?)? Also, I have no clue what the user id or password is? So on local computer, with the help of Integrated Security=True the windows authentication was being made. How to do it on the remote web host?
In the webhosting console, I see features such as create database, create database users, I can see the username and password aspects there. If those are required then how do I connect that with the database I just copied? It seems like those are the one's where database is created from scratch, while I already have the *.mdf (database) uploaded/copied.
I am stuck at this stage, and have no clue on how to proceed further. I know its something trivial, but out of scope of my knowledge. Please help me in completing the connection string. How do I make the database (data.mdf) file reachable/accessible?
I came across some articles which told to import the database and such (but where/why?), but I don't get it. When the database is in the App_Data folder, then why/how do I do that?
I am confused, please help.I'll highly appreciate step-by-step approach to fix it.Thanks.
EDIT (solution):
The solution given below is perfect. Apart from that this website/blog is worth checking.
-- http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/asp-net-hosting-options-cs
And if you don't have SQL Management Studio, best way to install is instructed here:
-- http://blogs.msdn.com/b/bethmassi/archive/2011/02/18/step-by-step-installing-sql-server-management-studio-2008-express-after-visual-studio-2010.aspx
Step 1 - Create a DB Script from SQL Management Studio
You will need to firstly script off you database schema and data (not as scary as it sounds - follow the steps here http://blog.sqlauthority.com/2011/05/07/sql-server-2008-2008-r2-create-script-to-copy-database-schema-and-all-the-objects-data-schema-stored-procedure-functions-triggers-tables-views-constraints-and-all-other-database-objects/ ) .
Step 2 - Create your DB at HostGator and Import your DB Script
Create your database at HostGator and import your script file (Follow this guide here http://support.hostgator.com/articles/plesk/plesk-9/how-to-create-or-import-databases-plesk-9 ).
Step 3 - Update your connection string and deploy!
You'll need to update your connection string to be something like this (you will need to add your details).
<add name=”CRMConnectionString” connectionString=”Data Source=Server IP;Initial Catalog=DBName;User ID=UserName;Password=Pwd;” providerName=”System.Data.SqlClient”/>
This connection string was cribbed from this resource here http://asoftwaredeveloper.wordpress.com/2012/01/06/hostgator-web-hosting-and-mssql-db-access/
Then publish your website and upload your files. Its worth noting that you won't need to update your App_Data folder and its contents when you publish because you'll be pointing at the DB on their server not the one in your directory.

Categories