ASP.NET database connection closes when launching website - c#

I have decided to start programming in ASP.NET MVC using C#
I have been following tutorials and implementing them into my own project.
What happens is that once i click Debug in Chrome/Firefox etc my database connection closes (the red cross appears)! (But when I refresh it manually it has the tick - till that point) I have a feeling it's to do with the connectionString in web.config. I don't like connection strings, to me they seem full of jargon. How many parameters do you REALLY need for a test project?
<connectionStrings>
<add name="PetsDBEntities" connectionString="metadata=res://*/MainDBModel.csdl|res://*/MainDBModel.ssdl|res://*/MainDBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|E:\Visual Studio 2013\Projects\Pets\Pets\App_Data\PetsDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
Unfortunately my knowledge of c#/asp.net mvc is VERY limited, hence following a tutorial but I know you guys at SO are really good at what you do.
The database named PetsDBEntities has the following properties.
Data Source: Microsoft SQL Server Database File (SQL Client)
Database File Name: projects/app_data/PetsDB.mdf
If i right click the database and click >Modify Connection and then click test connection I get a "This connection cannot be tested because the specified database file does not exist"
This is where the code breaks. NOTE: The values being submitted are passed through, it just seems that it is unable to connect and add the row to the database.
if (ModelState.IsValid)
{
using( var db = new PetsDBEntities())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(user.Password);
var regUser = db.Users.Create();
regUser.Email = user.Email;
regUser.Password = encrpPass;
regUser.PasswordSalt = crypto.Salt;
regUser.UserID = Guid.NewGuid();
db.Users.Add(regUser);
db.SaveChanges(); //--------THIS IS WHERE I GET AN ERROR---------
return RedirectToAction("Index", "Pictures");
}
}
else
{
ModelState.AddModelError("", "Login Data is incorrect!");
}
return View();
Hopefully this is enough information for you guys to spot where the problem is.
Thansk for anyone that can help! Again, I am new and not entirely sure what information is completely needed.

Your issue is likely with the db filename.
attachdbfilename=|DataDirectory|E:\Visual Studio 2013\Projects\Pets\Pets\App_Data\PetsDB.mdf;
Should be:
attachdbfilename=|DataDirectory|\PetsDB.mdf;

Maybe this can help?
A simple connection string for SQL Server could be Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;

You mentioned that when you click on test connection, you are getting an error. Your question title might be misleading, as i can assume that you didn't established the connection at all.
Can you go to "Server Explorer" -> "Data Connections" -> "Add Connection" -> "Microsoft SQL Server Database File", i assume you are using the .mdf file directly instead of connecting to SQL server?
Click on "Test Connection" and if everything goes well, you can retrieve the connectionstring from the properties.

Related

How to connect to a new server with similar old connection string info

Here in the company I'm working, we have migrated the current DB table structure and the Stored Procedures to a new DB; working so far.
The problem we are facing is that there isn't any way to get our app connected to the new DB. The reason? Probably some problem with the connection strings saved in the App.config (xml) file.
It's strange, because even if we have provided a similar Data Source, User ID, Password and Server structure as we had with the old DB, it simply refuses to connect and do any with it's functions.
The Database is running on SQL Server 2017 (same as before), and our app is developed in Winforms C#, using Entity Framework 6, and the EXECSQLSERVERPROCEDURE NuGet plugin.
This plugin in particular uses a special connection string (detailed below with the others) that doesn't use a "connectionString", but a "value" instead, and it's one of the parts that's failing, as well as the TableAdapter-based, filled DataGridViews. Only the EF6 connections and functions are working correctly.
I tried, from changing the Server Instance name, according to:
https://sqldbpool.com/2008/09/03/how-to-change-sql-server-instance-name/
So I didn't have to deal with special chars in the App.config; using HTML codes and entities for the Named Server Instance in Data Source (even in password with a asterisk, which we changed later without any effect), using this as reference:
https://www.toptal.com/designers/htmlarrows/
And, changed the reference of the special Connection String for a regular one, calling by "name" instead of "key", because this one doesn't exist in regular Connection String definition (yeah, tried to add it, but didn't work).
Just to get a big amount of nothing and frustration (being on this one since Friday, just to put you all in context).
Connection Strings (in App.config):
<connectionStrings>
<add name="MYAPP.Properties.Settings.MYAPP" connectionString="Data Source=MYAPPSERVER;Initial Catalog=MYAPP;User ID=sa;Password=MYAPP2019;Server=192.168.*.*"
providerName="System.Data.SqlClient" />
<add name="MYAPPBD" connectionString="metadata=res://*/MYAPP.csdl|res://*/MYAPP.ssdl|res://*/MYAPP.msl;provider=System.Data.SqlClient;provider connection string="data source=192.168.*.*\MYAPP;initial catalog=MYAPP;user id=sa;password=MYAPP2019;multipleactiveresultsets=True;application name=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="DBSQL" value="workstation id=server;packet size=4096;data source=MYAPPSERVER;initial catalog=MYAPP;user id=sa;password=MYAPP2019;server=192.168.*.*" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
The Definition of the Function that uses this "DBSQL" special Connection String (for getting a User's Privileges):
Dictionary<string, object> param = new Dictionary<string, object>();
DataTable dt = new DataTable();
param.Add(new SqlParameter("#profile", profile));
dt = SQLSERVERPROCEDURE.SQLSERVER.Exec("DBSQL", "spRec_Privileges", param, dt);
You can see this plugin source code here, for reference:
https://www.nuget.org/packages/EXECSQLSERVERPROCEDURE/
Expecting to connect to DB with all functions and not only EF6 ones, because we can't parse DataTable / DataSet returning functions to do the same as they do with EF List's. As for the auto-filled with TableAdapters' DataGridViews, we can make SP's for loading and saving changes, but that would consume time we can't spare for it.
This is the error, even if User ID and Password are well-typed:
System.Data.SqlClient.SqlException
   HResult = 0x80131904
   Message = Network-related or instance-specific error while establishing a connection to the 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 support remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection with SQL Server)
   Source = .Net SqlClient Data Provider
   Battery Tracking:
    in SQLSERVERPROCEDURE.SQLSERVER.Exec (String ConnectionName, String Procedure, Dictionary`2 Variable and Values, DataTable dt)
    in MYAPP.Class.User.GET_Usu_Privileges (Int32 profile) in C: \ Users \ User \ source \ repos \ MYAPP - EF Integration \ MYAPP \ Class \ Users.cs: line 107
Internal Exception 1:
Win32Exception: Username or password are not correct
Edit: Queries among the DB works well. Even if using full Server-Name\Instance format, which is the original one, doesn't work. We aren't using Windows auth (this is only being used in Server); just SQL Server auth.

How to use Two SqlConnection in single TransactionScope in asp.net c#

I have installed sql server 2008 R2 in two systems, from this one system act as a server and another is client.
I need to copy product from server system database to client system database
In my web.config
<connectionStrings>
<add name="DBConnection" connectionString="Data Source=SERVER-PC\SQLEXPRESS2008;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
<add name="DBConnection1" connectionString="Data Source=CLIENT-PC\SQLEXPRESS2008;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;Connection Timeout=1;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
Here My Coding
using (TransactionScope trnsScope = new TransactionScope())
{
try
{
List<Master_ProductBLL> lstProduct = new List<Master_ProductBLL>();
//My First SQL Connection For Server
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
{
connection.Open();
//Here I can get All Products from Server Database
lstProduct = Master_ProductBLL.GetMaster_ProductBLLs(DBAction.Status.Active, "");
connection.Dispose();
}
//My Second SQL Connection For Client
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection1"].ConnectionString))
{
connection.Open();
//Here I have save my Server Product into Client SQL Server
foreach (Master_ProductBLL item in lstProduct)
{
item.Save(true);
}
connection.Dispose();
}
trnsScope.Complete();
trnsScope.Dispose();
}
catch (TransactionException ex)
{
trnsScope.Dispose();
throw ex;
}
}
It shows an Error like
MSDTC on server 'CLIENT-PC\SQLEXPRESS2008' is unavailable
Unable to get the address of the distributed transaction coordinator for the server, from the server. Is DTC enabled on the server?
I have google it and find the following details
go to Services. (START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES)
Find the service called 'Distributed Transaction Coordinator' and RIGHT CLICK (on it and select) > Start.
make this service to run Automatically for solving this issue permanently
I have done the above steps both server and client.
But Still have an error
I think for two (or more) SQL servers to be transactionnaly 'synced', you have to configure network DTC as MSDTC service is in charge of a lot of stuff about transactions... (your client should use the server's one).
To do this :
type dcomcnfg in run...
open Component services | Computers
Right click "Local Computer" and go to MSDTC tab
uncheck Use a local coordinator and type in your server name (or IP)
make sure you followed the steps mentionned in
MSDTC on server 'server is unavailable
on both the client and the server.
Not really sure it'll work, but pretty sure it won't if you don't do that.
Which database you want to use create object of that database.it is simple
SqlConnection connection1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString();
SqlConnection connection1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection1"].ConnectionString

ASP.NET Contact form - output to localhost sql server database - unable to connect

I'm working on an ASP.NET site and I am trying to write to a local instance of a SQL Server 2012. The server is (localdb)\MyInstance. The database is "cms".
In my root web.config file, I have added the connection settings:
<configuration>
<connectionStrings>
<add
name="myDBConnection"
connectionString="Server=(localdb)\MyInstance;Database=cms;User ID=sa;password=local;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
In the contact.aspx.cs file, I am using this to test the connection:
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDBConnection"].ToString());
connection.Open();
if ((connection.State & ConnectionState.Open) > 0) {
Response.Write("Connection OK!");
connection.Close();
} else {
Response.Write("No Connection!");
}
But, each time I test, I get "No connection" error. I'm not sure what I'm missing here. I've gone over the settings based on this post: ASP.NET Contact Form - output to email and access database. I also test using this code snippet: http://www.aubrett.com/InformationTechnology/SQL/TestSQLConnection.aspx
I suspect there is something not correct about the format of the connection string in the web.config file and have tried various formats from http://www.connectionstrings.com/sqlconnection/
but nothing seems to work.
Does anyone know what I'm missing here?

Windows Authentication to Oracle database

I am trying to connect to a Oracle database by using the Windows Identity Token,
it worked yesterday but today it doesn't and I dont know why.
This is my code:
string ssoConnectionString;
var user = CreateSSOConnectionString(connectionStringBuilder, out ssoConnectionString);
oracleConnectionStringBuilder = new OracleConnectionStringBuilder
{
UserID = user.Identity.Name,
ConnectionString = ssoConnectionString
};
private WindowsPrincipal CreateSSOConnectionString(IConnectionStringBuilder connectionStringBuilder, out string ssoConnectionString)
{
var user = new WindowsPrincipal(WindowsIdentity.GetCurrent());
ssoConnectionString = ConfigurationManager.AppSettings["SSOConnectionString"];
ssoConnectionString = string.Format(ssoConnectionString, connectionStringBuilder.Host);
return user;
}
Connection = new Oracle.DataAccess.Client.OracleConnection();
Connection.ConnectionString = oracleConnectionString.ConnectionString;
Connection.Open(); //Fails on this line
The Code doesn't exactly look like this, but it's the essentials.
The SSO ConnectionString is located in app.config and looks like this:
<add key="SSOConnectionString" value="DATA SOURCE={0};User Id=/;" />
Here is a link showing how Oracle them selves explain how to do it: http://docs.oracle.com/cd/E11882_01/win.112/e18754/featConnecting.htm#i1006432
This is the error message I get:
ORA-1017: invalid username/password; logon denied
I have checked with breakpoints and everything looks fine. I've also searched alot around for this error and most people say it's because of password becoming case sensitive in Oracle version 11g, but I'm not providing any password.
What caused this error was actually a mismatch between the Oracle.DataAccess.dll version and the Oracle Client installed on my machine.
So the error is actually not at all related to the code or connection string in the configuration file.
Check your Oracle Client version by writing "sqlplus" in a command window, check that the Oracle.DataAccess.dll version and target .NET framework version matches.

System Data Entity. The underlying provider failed on Open

I am creating 2 projects that have the same database (it's an MDF database). The first one is the map editor, and I use XNA 4 and Web Services to connect to it. The second one is the game itself and uses XNA 3.1 and Entity Data Model to connect database.
When I run the map editor and access the database, it runs properly. Bbut when I run the game and access the database, it shows an error "The underlying provider failed on Open"
I think the connection from the web service is not closed yet. But I don't know where I should close the connection.
Here is my code from the web service:
public Map AddNewMap(string username, string mapName, int sizeX, int sizeY)
{
using (BaseModelDataContext context = new BaseModelDataContext())
{
Map newMap = new Map()
{
Username = username,
Name = mapName,
SizeX = sizeX,
SizeY = sizeY,
Upload_Date = DateTime.Now,
Status = 0
};
context.Maps.InsertOnSubmit(newMap);
context.SubmitChanges(System.Data.Linq.ConflictMode.FailOnFirstConflict);
context.Dispose();
return newMap;
}
}
EDIT:
Here is the entity data model code :
using (MazeEntities ent = new MazeEntities())
{
ent.Connection.Open();
return (from map in ent.Map
select map).ToList<Map>();
}
This code runs properly if I did not use the web service before. If I use the web service first, it shows an error at ent.Connection.Open();
Here is the inner exception:
Cannot open user default database. Login failed.\r\nLogin failed for user 'erkape-PC\erkape'.
Connection string for web service :
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\3DMapDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Connection string for the game:
"metadata=res:///MazeDataModel.csdl|res:///MazeDataModel.ssdl|res://*/MazeDataModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\eRKaPe\DropBox\TA\Program\3D_Map_Editor\3DMapEditorServices\App_Data\3DMapDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
For a quick check, can you try adding the following line after the using:
using (BaseModelDataContext context = new BaseModelDataContext())
{
context.Connection.Open();
OR
context.Database.Connection.Open();
// your code here
Finally I found a way to solve my problem after reading some articles.
The connection from the web service doesn't close automatically after I close the map editor. That is why I can't access my database from the game.
I have to change the connection string from both application, I set the User Instance to False. The game can access the database this way.
Please check the following post
http://th2tran.blogspot.ae/2009/06/underlying-provider-failed-on-open.html
Also please Enable for 32 Bit application in the APplication Pool of that application.
This may resolve.
You are trying to return an object (Map) which is associated with the Context. This object has the context information which can't be returned to the client.
You will need to create your own DataContract (a type having necessary properties) that you want to expose to the client.
Or you can use the POCO implementation As described here

Categories