Sybase iAnywhere.Data.SQLAnywhere.SAException : DSN database name does not exist - asp.net-mvc

My Application is in MVC 4 with Sql Anywhere 16 ODBC using Entity framework. I used Visual studio 2010. requirement is multi tenant so i created connection string dynamic on my Global.asax and once main database has been connected i create connection string of user based database on my Account controller.
Application run well when i run by visual studio. but when i publish this application on IIS 8.5 and load application on browser it shows below error.
<ErrorType>System.Data.EntityException: The underlying provider failed
on Open. ---> iAnywhere.Data.SQLAnywhere.SAException: DSN 'MainDB'
does not exist at iAnywhere.Data.SQLAnywhere.SAConnection.Open()
at
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean
openCondition, DbConnection storeConnectionToOpen, DbConnection
originalConnection, String exceptionCode, String attemptedOperation,
Boolean& closeStoreConnectionOnFailure) --- End of inner
exception stack trace --- at
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean
openCondition, DbConnection storeConnectionToOpen, DbConnection
originalConnection, String exceptionCode, String attemptedOperation,
Boolean& closeStoreConnectionOnFailure) at
System.Data.EntityClient.EntityConnection.Open() at
PDMSReporter.Controllers.AccountController.Login(LoginModel Login) in
E:\Projects\Triforce_PDM
Reporter\Latest_PDMSReporter\PDMSReporter\PDMSReporter\Controllers\AccountController.cs:line
56</ErrorType>
<ErrorDesc>The underlying provider failed on Open.</ErrorDesc>
I tried a lot to fix this issue. but didn't find any proper solution for it.
Please help me to fix this issue or suggest post where I can solve it.

The error message tells you: "DSN 'MainDB' does not exist". Your connection string is using a DSN that the client cannot find. This could be because you are creating a user DSN rather than a system DSN - if your client is running as a service (i.e. in IIS), it can't read user DSNs.
If you're creating the DSN using the dbdsn utility, make sure you use the -ws switch instead of -w.

Related

Error in Azure when a Web App tries to insert into a SQL Server database for the first time after tables created

This is a question that involves Azure with SQL Server and a Web App.
Everything works fine locally. The problem exists only in Azure.
I have set up a SQL Server with a database, and published a web app. They are using the same region.
Everything has default settings, except for allowing my local ip to connect to the database server.
I can connect to Azure SQL Server from SQL Server Management Studio and I see my database there.
The first thing I do in the web app is trying to register a new user. The tech involved is ASP.NET MVC5, ASP.NET Identity, and Entity Framework with migration scripts. Normal MS stuff.
I have set the ApplicationDbContext(DefaultConnection) in the Publish/Settings/Databases dialog and checked "Execute Code First Migrations".
The migration script is running fine. All tables have been created and are showing up in SQL Server Management Studio.
But when the web app is trying to add a new user to the User table, I get the error shown below.
So.. The web app obviously has a connection and access rights to the database since all tables have been created. Any idea what I am missing?
Thanks for any help and input!
Update:
In the web.config I found a new ConnectionString:
DefaultConnection_DatabasePublish with the correct configuration.
Somehow the original DefaultConnection was changed to Data Source=localhost;Initial Catalog={catalog};Integrated Security=True after it was published.
Changing the DefaultConnection to the same as DefaultConnection_DatabasePublish resolved the issue.
I have not had this behavior before when publishing. I have not checked "Execute Code First Migrations" before. Can someone confirm if the behavior is related to that?
Server Error in '/' Application.
The system cannot find the file 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.ComponentModel.Win32Exception: The system cannot find the file specified
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:
[Win32Exception (0x80004005): The system cannot find the file specified]
[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.SqlInternalConnectionTds.. ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling) +821
System.Data.SqlClient.SqlConnectionFactory.CreateConnection (DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +332
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection (DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +38
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +699
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +89
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +426
System.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen() +343
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter. HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.SqlServer.<b__3>d__6.MoveNext() +226
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter. HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.SqlServer.d__9`1.MoveNext() +354
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
System.Runtime.CompilerServices.TaskAwaiter. HandleNonSuccessAndDebuggerNotification(Task task) +58
System.Data.Entity.Core.EntityClient.d__8.MoveNext() +594
According to your description and error message, I guess you don't set the right connection string in web.config.
So the web app couldn't access the right sql database.
I suggest you could try to use kudu console to check the web app have set the right connection string.
1.Open the kudu console.
2.Use debug console
3.Locate the site\wwwroot folder and find web.config file.
Click the modify button.
4.Then you could find the connection string.
Replace the right connection string with the old one.
The connection string format is as below:
Server=tcp:{sqlservername}.database.windows.net,1433;Initial Catalog={databasename};Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Or you could directly set the connection string in azure web app's Application settings.

TFS 2012 update failed: Sync error for identity ... No mapping between account names and security IDs was done

Upgrading our TFS 2010 to TFS 2012, I get this error on one of the collections:
[Error] Sync error for identity: System.Security.Principal.WindowsIdentity, S-1-5-21-xxxxxxx - No mapping between account names and security IDs was done
The upgrade fails. Re-running the servicing job from the admin console causes the same error.
I looked in the database, and there is an entry in ADObjects where both SamAccountName and ObjectSID have that SID. It looks like an account from an old domain. fDeleted is 1.
How do I clean this up so I can upgrade?
Added information (from the SQL trace):
declare #p3 dbo.typ_ServicingStepDetail2
insert into #p3 values(1,'ToDev11Beta1FinalConfiguration','BuildToDev11Beta1FinalConfiguration','Grant Administer Build Permissions to Project Administrators','2013-04-12 14:17:55.617',NULL,0,N'Microsoft.TeamFoundation.Framework.Server.IdentitySyncException: Sync error for identity: System.Security.Principal.WindowsIdentity, S-1-5-21-xxxxx - No mapping between account names and security IDs was done
at Microsoft.TeamFoundation.Framework.Server.TeamFoundationIdentityService.TryReadIdentityFromSourceInternal(TeamFoundationRequestContext requestContext, IdentityDescriptor descriptor, Boolean withDirectMembership, TeamFoundationIdentity& identity)
at Microsoft.TeamFoundation.Framework.Server.TeamFoundationIdentityService.AddMemberToApplicationGroup(TeamFoundationRequestContext requestContext, IdentityDescriptor groupDescriptor, IdentityDescriptor memberDescriptor, Boolean errorOnDuplicate, Boolean logSync, Boolean ensureKnown)
at Microsoft.TeamFoundation.Framework.Server.TeamFoundationIdentityService.EnsureIsMember(TeamFoundationRequestContext requestContext, IdentityDescriptor groupDescriptor, IdentityDescriptor descriptor)
at Microsoft.TeamFoundation.Framework.Server.TeamFoundationSecurityNamespace.EnsureIdentityIsKnownInternal(TeamFoundationRequestContext requestContext, IdentityDescriptor identity, Boolean throwOnFailure)
at Microsoft.TeamFoundation.Framework.Server.TeamFoundationSecurityNamespace.SetAccessControlEntries(TeamFoundationRequestContext requestContext, String token, IEnumerable1 accessControlEntries, Boolean merge, Boolean throwOnInvalidIdentity)
at Microsoft.TeamFoundation.Framework.Server.TeamFoundationSecurityNamespace.SetAccessControlEntries(TeamFoundationRequestContext requestContext, String token, IEnumerable`1 accessControlEntries, Boolean merge)
at Microsoft.TeamFoundation.Server.Servicing.TFCollection.BuildStepPerformer.GrantAdministerPermissionsToProjectAdmins(TeamFoundationRequestContext requestContext, ServicingContext servicingContext)
at Microsoft.TeamFoundation.Framework.Server.TeamFoundationStepPerformerBase.Microsoft.TeamFoundation.Framework.Server.IStepPerformer.PerformStep(String servicingOperation, String stepType, String stepData, ServicingContext servicingContext)
at Microsoft.TeamFoundation.Framework.Server.ServicingStepDriver.PerformServicingStep(ServicingStep step, ServicingContext servicingContext, ServicingStepGroup group, ServicingOperation servicingOperation, Int32 stepNumber, Int32 totalSteps)')
insert into #p3 values(2,'ToDev11Beta1FinalConfiguration','BuildToDev11Beta1FinalConfiguration','Grant Administer Build Permissions to Project Administrators','2013-04-12 14:17:55.617',5,NULL,NULL)
exec prc_AddServicingStepDetails #jobId='xxx',#queueTime='2013-04-12 14:17:50.840',#stepDetails=#p3,#hostId='xxx',#completedStepCount=419`
So it looks like I might have a project administrator who doesn't exist anymore. Any thoughts on how to remove that membership manually?
Okay, I got the upgrade to complete by doing the following.
THIS IS EXTREMELY FILTHY AND DANGEROUS. DO NOT TRY WITHOUT A GOOD BACKUP. YOUR WARRANTY HAS ALREADY EXPIRED. THIS VERY WELL MIGHT NOT WORK FOR YOU. IT MIGHT BREAK YOUR ENTIRE TFS SETUP AND GIVE DISEASES TO YOUR PUPPY.
Anyway.
Open SQL Server Management Studio. Punch up a new query window for the project collection that won't upgrade (usually Tfs_NameOfCollectionThatWontUpgrade). Execute this command:
Select TeamFoundationId From ADObjects
Where ObjectSID='S-1-xxxx'
(Obviously, insert the proper SID from your error message.)
This will give you the internal GUID for the identity that is causing the problem. The step my upgrade failed on was giving Build Administrator rights to Project Administrators, and whoop-dee-doo, I can do that myself.
Now nuke the Active Directory link from orbit (you do have that GUID copied, right?)
Delete From ADObjects
Where ObjectSID='S-1-xxxxx'
(Obviously, insert the proper SID from your error message. Also note that this step might not be strictly necessary, but it is one I performed and I'll be damned if I roll back to see if you can do without it.)
Ah, gotta love chain-saw surgery. More to do. Let's remove this identity from all groups. NOTE: if you do this to your only administrator account, you're likely to shut yourself out of the collection and/or the projects within. You have been warned.
Switch to the configuration database (usually Tfs_Configuration) and execute
Delete From tbl_GroupMembership
Where MemberId='The GUID you remembered'
At this point, the user is no longer a member of anything and the upgrade should complete. Everything should be there: builds, work items and source.
I had a very similar issue (almost identical) when my TFS Server was using TFS 2012 Update 1. I also came up with this hack in order to resolve it. When I had a TFS Server running TFS 2012 RTM or TFS 2012 Update 2 I didn't encounter the issue.
Here a link to that thread.
http://social.msdn.microsoft.com/Forums/en-US/tfsadmin/thread/238cad96-8e74-4f14-869a-3bb5e0629fd7

How do I connect to a local Microsoft Sql server 2012 Express database from a C# program?

Can someone please help me fix my connection string? I am an absolute beginner using the MS SQL Management Studio but I am an experienced C# programmer. I am trying to figure out how to connect to a local database on my PC. I just installed SQL server 2012 Express today and I created a table with one row of data. I am trying to access that table from a C# program. I've been looking for help calling a stored procedure (with no parameters) and it seems like I am doing everything right, but I get an exception error "Could not find stored procedure 'GetCustomers'." I have also tried changing my the procedure name to "dbo.GetCustomers" and also "SqlTest.dbo.GetCustomers" and also "SqlTest.GetCustomers", but nothing seems to work. Clearly I am not connecting to my database correctly. I've been working on this for 4 hours now so it's time for me to stop and find help. I think all I need is a good connection string and the proper syntax for the procedure.
Connect c = new Connect();
if(c.MakeConnection())
{
try
{
DataSet data = new DataSet();
SqlDataAdapter adaptor = new SqlDataAdapter();
//changed to use stored procedure
adaptor.SelectCommand = new SqlCommand("GetCustomers", c.MyConnect);
adaptor.SelectCommand.CommandType = CommandType.StoredProcedure;
//adaptor.SelectCommand.ExecuteNonQuery();//this throws an exception.
adaptor.Fill(data);//this throws an exception.
}
catch (Exception e)
{
Logger.WriteMessage(e.Message);
}
finally
{
c.CloseConnection();
}
My connection class contains the following:
string connection = Properties.Settings.Default.DatabaseConnectString;
sqlConnection = new SqlConnection(connection);
sqlConnection.Open();
Connection string I have tried which seem to connect OK:
Server=(localdb)\v11.0;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Integrated Security=true;
My Database name is SqlTest. I have tried several variations in my connection string, but most of them throw a logon failed exception error. I verified that my windows user ID has admin privileges for the database.
Connection strings I have tried which cive me logon errors:
Server=(localdb)\v11.0;Initial Catalog=SqlTest;User ID=Raphael\couchpotato;Integrated Security=SSPI;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Initial Catalog=dbo;User ID=Raphael\couchpotato;Integrated Security=SSPI;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Database=SqlTest;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Database=SqlTest;Integrated Security=true;
I guess all I needed was some sleep. ;-)
I needed to set all of my SQL server services to Automatic. For some reason, they were set to manual, and so they were not started.
Then, I also needed to set the correct server name in my connection string. This is the same server name that is used to logon when starting SQL Server Management Studio. Here is a connection string that connects and accesses the correct database and table:
Server=RAPHAEL\SQLEXPRESS;Database=SqlTest;Trusted_Connection=Yes;

WebSecurity.InitializeDatabaseConnection method can be called only once

I'm trying Windows Azure to host an MVC4 web application.
I've created a test app, using VS2012 MVC4 internet application template and added a custom Model and Controller to it.
I've published it on Azure and managed to get 'update-database' apply migrations to the Azure Database.
When i try the app locally, but using the Azure SQL database, it works fine.
I can login/register and use my test controller.
When i try the app online, i can use the test controller but login or register links give the following exception:
Server Error in '/' Application.
The "WebSecurity.InitializeDatabaseConnection" method can be called only once.
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.InvalidOperationException: The "WebSecurity.InitializeDatabaseConnection" method can be called only once.
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:
[InvalidOperationException: The "WebSecurity.InitializeDatabaseConnection" method can be called only once.]
WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +123
WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionStringName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +52
MembershipTest2.Filters.SimpleMembershipInitializer..ctor() +193
Do you have any idea where that comes from ?
If i debug (the local version), this method is only called once.
Thanks.
You could try encapsulating the call(s) to that method to ensure it's not called more then once
if (!WebMatrix.WebData.WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection(...);
}
in my case I had both
(in web.config)
<add key="enableSimpleMembership" value="true" />
and
(in _ViewStart.cshtml)
WebSecurity.InitializeDatabaseConnection("club", "Account", "UserID", "UserName", autoCreateTables: true);
Solution: it seems you cannot have both, so remove one
Does the following SO discussion help you?
Cannot seed Users & Roles
I did find the following article helped me lot to use newer MVC4 & EF together with Simple Membership Provider so if you haven't read it please take a look:
SimpleMembership, Membership Providers, Universal Providers and the new ASP.NET 4.5 Web Forms and ASP.NET MVC 4 templates

How to resolve database connection string problems in asp.net?

I am developing an asp.net mvc3 application using Visual Studio 2010.I need to access the database.
I wrote the connection string as
SqlConnection conn = new SqlConnection("Data Source=./App_Data/Abcd.mdf;Integrated Security=True;User Instance=True");
But, when I run the code, I get an error: 40 - Could not open a connection to SQL Server.
From the SQL Server Configuration Manager, I enabled TCP/IP but I still get the same exception.
I also tried changing the connection string to
SqlConnection conn = new SqlConnection("System.Configuration.ConfigurationManager.ConnectionStrings.ConnectionString");
But I got an exception that said "Format of the initialization string does not conform to specification starting at index 0."
How do I overcome this problem?
Thank you in advance for your help.
This will depend on the type of database you are using: SQL Express or SQL Developer/Standard. If you use SQL Express you may take a look at the following article illustrating different connection strings. For example:
Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|Abcd.mdf;Integrated Security=True;User Instance=True
If you are using the full version of SQL Server, your database is no longer stored in the App_Data folder. It is managed by SQL Server. Checkout the following site for connection strings in this case depending on your scenario.
Example:
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
SqlConnection conn = new SqlConnection("Data Source=.\sqlexpress;database=dbname;AttachDbFilename=|DataDirectory|\Abcd.mdf;Integrated Security=True;User Instance=True");
or
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("webconfigconnectionname").ConnectionString);
In VS click on server explorer and add the connection
when the connection has been setup right click on the established connection and select properties
you will get the properties window open. In that window select the connection string, which you can use in the sqlconnection

Resources