working with db using .NET c# - c#

I am in my first steps using db in an application so my goal is to build simple db with one table from scratch in order to improve and learn
I have opened new db using the visual studio :
Tolls -> connect to database
and announced him to create new data base
the next step was to populate a table with 4 columns (the all 4 are nchar(10))
and then (with no actual data inside )i tried this code:
try
{
// step 1: create a SqlConnection object to connect to the
// SQL Server my server connection string proprties database
// i think the bug should be here !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
SqlConnection mySqlConnection = new SqlConnection("Data Source=./SQLEXPRESS;AttachDbFilename=C:/Users/STERN/Documents/myDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");//"server=localhost;database=Northwind;uid=sa;pwd=sa");
// step 2: create a SqlCommand object
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
// step 3: set the CommandText property of the SqlCommand object to
// a SQL SELECT statement that retrieves a row from the Customers table
mySqlCommand.CommandText =
"SELECT type " +
"FROM Table1 " +
"WHERE type = ‘ALFKI’";
// step 4: open the database connection using the
// Open() method of the SqlConnection object
mySqlConnection.Open();
/*
some code ....
*/
catch (SqlException e)
{
Console.WriteLine("A SqlException was thrown");
Console.WriteLine("Number = " + e.Number);
Console.WriteLine("Message = " + e.Message);
Console.WriteLine("StackTrace:\n" + e.StackTrace);
}
string s = Console.ReadLine();
}
where the exception i get is throwen by
mySqlConnection.Open();
this is the error message i get :
A SqlException was thrown
Number = 3
Message = A network-related or instance-specific error occurred while establishi
ng a connection to SQL Server. The server was not found or was not accessible. V
erify that the instance name is correct and that SQL Server is configured to all
ow remote connections. (provider: Named Pipes Provider, error: 40 - Could not op
en a connection to SQL Server)
StackTrace:
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception
, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternal
ConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Bool
ean encrypt, Boolean trustServerCert, Boolean integratedSecurity)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeo
ut, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection ow
ningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnecti
on owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, St
ring newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdent
ity identity, SqlConnectionString connectionOptions, Object providerInfo, String
newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOp
tions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection
owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConn
ection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owning
Object)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection o
wningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection ownin
gObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection ow
ningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection ou
terConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at ConsoleApplication1.Program.Main(String[] args) in C:\Users\STERN\AppData\
Local\Temporary Projects\ConsoleApplication1\Program.cs:line 29
if someone knows about pdf , article ,something that would help me it would b very nice of him to write it down here...
can someone please help me....

It looks like you are unable to connect to your local instance of SQL Server Express.
Even though you are specifying a local database file, that file is going to be attached to the local instance of SQL Server Express once it connects. All data access is then done through the attached database through SQL Server Express (not directly from the file).
Make sure that is up, running, and you can connect to it using SQL Management Studio Express.
If your local instance of SQL server is up and responding or you want different behavior from your connection string, I would suggest checking out ConnectionStrings.com:
SQL Server 2008 Connection Strings

Try connecting to your database with the same connection string in SQL Server Management Studio. Does it connect? If not (and I doubt it will), you have the wrong connection string.
Edit:
Additionally, make sure the SQL Server and SQL Agent services are running.

I would have to say the application has trouble connecting to your SQL server, if the SQL connection string is correct, check with your SQL Surface Area and Configurations that piped names are allowed and remote connections allowed.
-- edit --
Microsoft documentation on how to configure SQL Express for remote connections http://support.microsoft.com/kb/914277

Related

.net + SQL + Timeout issue

I'm having an issue with a .net library connecting to an SQL Server instance.
The library is part of an application which inserts the contents of edi files into an SQL Server 2008 R2 database.
Every time the library is called, it throws an exception (#1 below) stating that the connection has timed out. There are multiple other non .net applications on the server in question which use the same connection string and work perfectly.
I have also installed the application containing the library on another networked machine and it works fine from there.
Things I have tried:
Setting .CommandTimeout = 150; - Times out way before 150 secs.
Reinstalling all .net frameworks
Rebooting app server & DB server
Switching from data context to standard data adapter queries.
Created a stand alone exe to test connection string using both data context and standard data adapter queries - Both methods fail first time, but then connect and read data on all subsequent tries until the exe is restarted. This lead me to add a retry attempt with a delay to the library when the exception is hit, but that results in exception 2.
I'm now at a loss. Any help would be appreciated.
Exception 1:
System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParserStateObject.ReadNetworkPacket()
at System.Data.SqlClient.TdsParser.ConsumePreLoginHandshake(Boolean encrypt, Boolean trustServerCert, Boolean& marsCapable)
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user)
at System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe()
at System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode()
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataContext.ExecuteMethodCall(Object instance, MethodInfo methodInfo, Object[] parameters)
at System.Data.Linq.DataContext.ExecuteQuery[TResult](String query, Object[] parameters)
<Query Execution method call>
Exception 2:
System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user)
at System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe()
at System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode()
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataContext.ExecuteMethodCall(Object instance, MethodInfo methodInfo, Object[] parameters)
at System.Data.Linq.DataContext.ExecuteQuery[TResult](String query, Object[] parameters)
<Query Execution method call>
Setting .CommandTimeout
occurs when a query can't get total data with in the specified time..
In your case,there can be many time outs which can occur ..We solved the time out approach in our case ,by following below steps
1.Changed RemoteLoginTimeout to 60
2.Change RemoteQuery timeout to 0..
Further we also disabled TCP Chimney on all of our servers
https://blogs.msdn.microsoft.com/psssql/2010/02/21/tcp-offloading-again/
Now we are 100% sure ,network is not a factor in time outs,even then if the query fails with time out,when executed though SQLagent or some thing else
1.We try to update statistics
2.We will see ,if there is a chance for optimization..
You also can refer to this blog,where OP mentioned all the time outs that can occur
When attempting to get a connection from the SqlClient connection pool
When attempting to create a new fresh connection to server (not getting one from pool)
When sending a command explicitly to the server
When sending commands with "context connection=true"
When sending commands implicitly (under the covers) to the server
When executing asynchronous commands (BeginExecute…)
When waiting for attention acknowledgement from server (special rare case)
When sending TM commands
When fetching rows
When uploading rows using bulk copy

A network-related or instance-specific error occurred while establishing .... error: 26

I am working in my asp.net project; when I run my program, it stops running and gives me this message:
A network-related or instance-specific error occurred while establishing a connection to 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 allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Server Error in '/Test2' Application.
A network-related or instance-specific error occurred while establishing a connection to 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 allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to 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 allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Source Error:
Line 27: string cmdString = "Delete from tblSessionCart";
Line 28: SqlCommand cmd = new SqlCommand(cmdString, conn);
Line 29: conn.Open();
Line 30: try
Line 31: {
Source File: c:\Users\mousa\Desktop\Test2\App_Code\clsSessionCart.cs Line: 29
Stack Trace:
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to 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 allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4876455
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject) +354
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +90
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +401
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +225
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +4889331
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +431
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
System.Data.SqlClient.SqlConnection.Open() +122
clsSessionCart.DeleteCart() in c:\Users\mousa\Desktop\Test2\App_Code\clsSessionCart.cs:29
ASP.global_asax.Session_Start(Object sender, EventArgs e) in c:\Users\mousa\Desktop\Test2\Global.asax:27
System.Web.SessionState.SessionStateModule.RaiseOnStart(EventArgs e) +8878884
System.Web.SessionState.SessionStateModule.CompleteAcquireState() +237
System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) +504
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +66
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:2.0.50727.5477; ASP.NET Version:2.0.50727.5479
This problem is related to connection string,
Check instance server
Check user and password
Connection string:
Server=YOUR_SQLSERVER_INSTANCE;Database=YOUR_DATABASE_NAME;User Id=sa;Password=YOUR_SA_PASSWORD;
If you have instance, make sure instance is specified in server, for example:
Server=.\SQL2008
This exception throws when your sqlServer service is stopped or when your TCP port is changed, so check for that one.
We added the port info to our connection string which alleviated this error. For example:
server=servername,port#;database=databasename;....
I got the error because my DataSource was named
(localdb)\v11.0
and in C# the backslash is interpreted as a special character so needs to be escaped as follows : the below lines will work! But single "\" fails.
String source = "Data Source=(localdb)" + "\\" + "v11.0;Initial Catalog=Northwind;Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(source);
conn.Open();
I got the same error, and my connection string is correct. I try to use ip address of SQL Server instead of server name. Finally, this error has gone.
I use this connection string
<add name="YourEntitiesName" connectionString="metadata=res://*/Model.SampleDatabaseModel.csdl|res://*/Model.SampleDatabaseModel.ssdl|res://*/Model.SampleDatabaseModel.msl;provider=System.Data.SqlClient;provider connection string="data source=10.123.60.12\SQLServerName;initial catalog=SampleDB;user id=sa;password=123456;MultipleActiveResultSets=True;Pooling=False;App=EntityFramework"" providerName="System.Data.EntityClient" />
instead of
<add name="YourEntitiesName" connectionString="metadata=res://*/Model.SampleDatabaseModel.csdl|res://*/Model.SampleDatabaseModel.ssdl|res://*/Model.SampleDatabaseModel.msl;provider=System.Data.SqlClient;provider connection string="data source=SERVER01\SQLServerName;initial catalog=SampleDB;user id=sa;password=123456;MultipleActiveResultSets=True;Pooling=False;App=EntityFramework"" providerName="System.Data.EntityClient" />

trying to redirect after login

I have a complicated situation with trying to make the login.aspx to redirect you to the web form you were at before the login. I am using ASP.NET/C# to program my web application. It sounds easy to do, but I am running into all sorts of issues doing this and I tried doing this many different ways. Here is the part of the login.aspx.cs that shows the redirect:
HttpContext.Current.ApplicationInstance.CompleteRequest();
string url = HttpContext.Current.Request.Url.AbsoluteUri;
try{
int start = url.IndexOf('=');
if(url.Length > 0)
{
url = url.Substring(start, url.Length - 1 - start);
url = url.Replace("=","");
}
Response.Redirect(url, false);
}
catch(Exception i)
{}
The code above takes the url string and extracts the redirectURL variable (the address of the previous webform) and uses it for redirecting you after your login.
There is no exception within this try-catch, but the exception happens after the login tries to redirect to the previous web form. Here is a web form with directing login code:
var returnUrl = Request.Url.PathAndQuery;
Response.Redirect("~/Account/login.aspx?ReturnURL=" + returnUrl);
The problem is I get an SQL exception in the browser? I am not even using SQL during this redirect. here is what the exception says:
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to 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 allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5066458
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +234
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity) +341
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject) +129
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) +270
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +195
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +232
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +5080107
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) +31
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +76
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +126
System.Data.SqlClient.SqlConnection.Open() +125
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +82
[HttpException (0x80004005): Unable to connect to SQL Server database.]
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +137
System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +94
System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +27
System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +395
also the source error:
An unhandled exception was generated during the execution of the current web
request. Information regarding the origin and location of the exception can be
identified using the exception stack trace below (edit: above actually).
My guess is that for some reason the redirect is not finding the web form. I did try the returnURL variable string starting with and without a ~ to see if that worked and it didn't. I have also tried session variables and cookies... still didn't want to work. Thank you in advance for your help!

Annoying error on summer of nhibernate screencast

I was trying to follow the summer of nhibernate screnncast series but I'm stuck at an early session. So this is the problem:
When I am trying to run the following method:
public void GetMyTestDataXMLFile()
{
SaveTestDatabase();
}
I am getting the following error:
Test Report: file:///C:/Users/pina/AppData/Local/Temp/Gallio/TDNetRunner/Report/DataAccessLayerTest.dll.html
** NO TESTS WERE RUN (No tests found) **
Test 'M:DataAccessLayerTest.Tests.GetMyTestDataXMLFile' failed: SqlDbCommandBuilder.CreateSelectCommand(DataSet, string) failed for tableName = 'Customer'
NDbUnit.Core.NDbUnitException: SqlDbCommandBuilder.CreateSelectCommand(DataSet, string) failed for tableName = 'Customer' ---> System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to 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 allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at NDbUnit.Core.SqlClient.SqlDbCommandBuilder.getSchemaTable(SqlCommand sqlSelectCommand)
at NDbUnit.Core.SqlClient.SqlDbCommandBuilder.CreateSelectCommand(DataSet ds, String tableName)
--- End of inner exception stack trace ---
at NDbUnit.Core.SqlClient.SqlDbCommandBuilder.CreateSelectCommand(DataSet ds, String tableName)
at NDbUnit.Core.DbCommandBuilder.BuildCommands(Stream xmlSchema)
at NDbUnit.Core.NDbUnitTest.ReadXmlSchema(Stream xmlSchema)
at NDbUnit.Core.NDbUnitTest.ReadXmlSchema(String xmlSchemaFile)
at Microdesk.Utility.UnitTest.DatabaseUnitTestBase.SaveDatabase(String connectionString, String schemaFilePathName, String datasetFilePathName, DatabaseClientType clientType)
at Microdesk.Utility.UnitTest.DatabaseUnitTestBase.SaveTestDatabase()
TestClass1.cs(291,0): at DataAccessLayerTest.Tests.GetMyTestDataXMLFile()
The only difference is that I am using a local Database (.sdf file). I'm sure that it has to be related with the connection string but I can't seem fix this.
This is my app.config file:
<?xml version="1.0"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="testDatabase"
connectionString="Data Source=H:\Code\NHibernateSample\DataAccessLayer\FirstSample.sdf"
providerName="Microsoft.SqlServerCe.Client.3.5"/>
</connectionStrings>
</configuration>
I am using VS 2010.
Can anybody help?
I've manage to figure it out. It appears that the Test Driven framework doesn't fully support to work with the .sdf files & the SQLServerCe. I've installed a new SQL Server local instance and created a new DB and everything was fixed.
Later on I'll post the new app.config file.

Server Error in '/' Application (ASP.NET)

I just setup up member ship roles and registration on my website with visual web developer using the tutorial on msdn. It works perfectly locally, but when i uploaded it to my server, I get the following page:
"Server Error in '/' Application.
--------------------------------------------------------------------------------
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: The connection name 'LocalSqlServer' was not found in the applications configuration or the connection string is empty.
Source Error:
[No relevant source lines]
Source File: machine.config Line: 160
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4200; ASP.NET Version:2.0.50727.4016 "
Does anybody know why I'm seeing this and how I may go about fixinf this? Any help is greatly appreciated.
Thank you
Bael.
EDIT:
I have just looked at my web.config file after reading the following line in the error message: "The connection name 'LocalSqlServer' was not found in the applications configuration or the connection string is empty." ... And have noticed that the following element is completely empty:
<connectionStrings/> // Is this one supposed to be empty? if not what should go here? In the error it implies it shouldn't be empty. Also, I don't know where I should place LocalSqlServer
LATEST EDIT
After changing DataSource to LocalHost i get the following error:
Server Error in '/JTS' Application.
--------------------------------------------------------------------------------
A network-related or instance-specific error occurred while establishing a connection to 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 allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to 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 allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to 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 allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4849015
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject) +4862333
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +90
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +342
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +221
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +185
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +433
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
System.Data.SqlClient.SqlConnection.Open() +122
System.Web.DataAccess.SqlConnectionHolder.Open(HttpContext context, Boolean revertImpersonate) +87
System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) +221
System.Web.Security.SqlMembershipProvider.GetPasswordWithFormat(String username, Boolean updateLastLoginActivityDate, Int32& status, String& password, Int32& passwordFormat, String& passwordSalt, Int32& failedPasswordAttemptCount, Int32& failedPasswordAnswerAttemptCount, Boolean& isApproved, DateTime& lastLoginDate, DateTime& lastActivityDate) +815
System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved, String& salt, Int32& passwordFormat) +105
System.Web.Security.SqlMembershipProvider.CheckPassword(String username, String password, Boolean updateLastLoginActivityDate, Boolean failIfNotApproved) +42
System.Web.Security.SqlMembershipProvider.ValidateUser(String username, String password) +78
System.Web.UI.WebControls.Login.AuthenticateUsingMembershipProvider(AuthenticateEventArgs e) +60
System.Web.UI.WebControls.Login.OnAuthenticate(AuthenticateEventArgs e) +119
System.Web.UI.WebControls.Login.AttemptLogin() +115
System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +101
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +166
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927
Ensure you have connection string named LocalSqlServer added connectionStrings element of your Web.config.
If you're using standard ASP.NET Membership/Role providers, by default they are declared as this:
<membership>
<providers>
<add
name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, ..."
connectionStringName="LocalSqlServer" ...
It's the connectionStringName which is likely to be causing this error. If you plan on using Membership/Role API, you'll have to either add a connection string named LocalSqlServer to <connectionString> secion of your Web.config, or change connectionStringAttribute so that its value will be a valid (and existing) connection string name.
LocalSqlServer is a default connection string entry in machine.config. It is always present although not in the app/web config file.
It points to your local instance of sqlexpress that was installed with visual studio.
By default the membership provider, upon configuration, creates a local .mdf file in your app_data folder (click show all files). This database has been provisioned.
If for some reason you want to use a different database you must provision it with aspnet_regsql.exe . You will find it in your windows/microsoft.net/framework/2.0.xxxx directory.
from the commandline run aspnet_regsql.exe /? to get instructions.
So.. this may be why you are getting these errors. If you DO want to use a different database and do not want to edit the membership section to point to the new db you must remove localSqlServer and then re-add
OR, again, configure your membership element to point to a different connection.
EITHER WAY you need a PROVISIONED database other than the local user instance that was provisioned by VS that you are using during development and a connection string that points to it.
<connectionStrings>
<remove name='LocalSqlServer' />
<add name='LocalSqlServer' connectionString='Data Source=DBServerName;
Integrated Security=false;Initial Catalog=DBName;
User ID=DBLogin;Password=DBPassword' providerName='System.Data.SqlClient' />
</connectionStrings>
EDIT: reread your question:
The problem is that the host does not have sql or does not allow user instances. Typically in a hosted site, you will request a database and upon getting the credentials, use aspnet_regsql.exe to provision that database. In this case you MUST modify the membership section in web.config to point to your new database.
hth
If you have .Net membership roles provider see this link first.
Some explanation since you said you did not understand
Net membership roles provider is setup to look for 'LocalSQLServer'. This means that we have to supply the details for a connection named LocalSQLServer or say it isnt needed. What you can do is in you web.config file find the <connectionstrings> part and add a line:
<add name='LocalSqlServer' connectionString='Data Source=DBServerName;
Integrated Security=false;Initial Catalog=DBName;
User ID=DBLogin;Password=DBPassword' providerName='System.Data.SqlClient' />
Replace the DBServerName with your SQL db server addon, DBName with the database name that came with your addon, DBLogin and Password should be replaced with what came with your SQL addon.
If you don't want to use LocalSQLSever you can remove it by
<remove name='LocalSqlServer' />
in your web.config file under the properties. Then change the connection string name on your roles provider to the connection string name you will be using. So change your exisiting connection string to name='LocalSQLServer'.
It may be that you're getting a connection string from the machine.config.
The easiest way to get rid of these, rather than using remove is to use a self closed clear element in the connectionstrings section.
The out of the box membership provider should have had a local connection string entry (new projects get this by default). You could create a new project and swipe it from there.
On the server you'll need to check SQL is installed correctly, and to update the connection string to match the server details.
I've often seen this message when the ASPNET user does not have read access to the config directory for the framework in question. It looks to me like you have a file directive in one of your keys, and the framework does not have access (either through permissions or because the file is not there) to read it.
Enable Named Pipes and TCP/IP for Microsoft SQL Server

Categories

Resources