At the moment I am trying to use the code first approach of the entity framework 6 to create / connect to different databases on an SQL Express 2012 instance. The connection string to the database needs to be created in code and if the database does not exist it should be created on the SQL Express instance. Below is my class structure:
public class TestContext : DbContext
{
public TestContext()
{}
public TestContext(string connectionString)
: base(connectionString)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<TestContext, Configuration>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ChildItem>().HasRequired(s => s.Parent)
.WithMany(s => s.ChildItems);
base.OnModelCreating(modelBuilder);
}
public DbSet<ParentItem> Parents { get; set; }
public DbSet<ChildItem> Childs { get; set; }
}
[Table("Parents")]
public class ParentItem
{
public ParentItem()
{
Childs = new List<ChildItem>();
}
[Key]
public int ParentId {get; set;}
public string ParentName { get; set; }
public virtual List<ChildItem> Childs { get; set; }
}
[Table("Childs")]
public class ChildItem
{
[Key]
public int ChildId { get; set; }
public string Name { get; set; }
public virtual ParentItem Parent { get; set; }
}
When I now try to add Data for a new database or add data to an existing one I receive the following exception.
> System.Data.DataException was unhandled by user code
> HResult=-2146233087 Message=An exception occurred while initializing
> the database. See the InnerException for details.
> Source=EntityFramework StackTrace:
> at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action
> action)
> at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
> at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext
> c)
> at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
> at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1
> action)
> at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
> at System.Data.Entity.Internal.InternalContext.Initialize()
> at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type
> entityType)
> at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
> at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
> at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action,
> EntityState newState, Object entity, String methodName)
> at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
> at System.Data.Entity.DbSet`1.Add(TEntity entity)
> at UnitTestProject.TestContextTest.InsertManyMeasurmentsDirectlyWithSql()
> in MSSQLTest.cs:line 123 InnerException:
> System.Data.Entity.Core.ProviderIncompatibleException
> HResult=-2146233087
> Message=An error occurred while getting provider information from the database. This can be caused by Entity Framework using an
> incorrect connection string. Check the inner exceptions for details
> and ensure that the connection string is correct.
> Source=EntityFramework
> StackTrace:
> at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices
> providerServices, DbConnection connection)
> at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.<>c__DisplayClass1.<ResolveManifestToken>b__0(Tuple`3
> k)
> at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey
> key, Func`2 valueFactory)
> at System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken(DbConnection
> connection)
> at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection
> connection, DbProviderManifest& providerManifest)
> at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
> at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext
> context, XmlWriter writer)
> at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter
> w)
> at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action`1
> writeXml)
> at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext
> context)
> at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration
> configuration, DbContext usersContext)
> at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration
> configuration)
> at System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext
> context)
> at System.Data.Entity.Internal.InternalContext.<>c__DisplayClasse`1.<CreateInitializationAction>b__d()
> at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action
> action)
> InnerException: System.Data.Entity.Core.ProviderIncompatibleException
> HResult=-2146233087
> Message=The provider did not return a ProviderManifestToken string.
> Source=EntityFramework
> StackTrace:
> at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection
> connection)
> at System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices
> providerServices, DbConnection connection)
> InnerException: System.Data.SqlClient.SqlException
> HResult=-2146232060
> 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)
> Source=.Net SqlClient Data Provider
> ErrorCode=-2146232060
> Class=20
> LineNumber=0
> Number=-1
> Server=""
> State=0
> StackTrace:
> at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
> exception, Boolean breakConnection, Action`1 wrapCloseInAction)
> at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
> stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
> at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo,
> SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout,
> Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean
> integratedSecurity, Boolean withFailover)
> at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
> serverInfo, String newPassword, SecureString newSecurePassword,
> Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean
> withFailover)
> at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
> serverInfo, String newPassword, SecureString newSecurePassword,
> Boolean redirectedUserInstance, SqlConnectionString connectionOptions,
> SqlCredential credential, TimeoutTimer timeout)
> at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer
> timeout, SqlConnectionString connectionOptions, SqlCredential
> credential, String newPassword, SecureString newSecurePassword,
> Boolean redirectedUserInstance)
> at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
> identity, SqlConnectionString connectionOptions, SqlCredential
> credential, Object providerInfo, String newPassword, SecureString
> newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString
> userConnectionOptions, SessionData reconnectSessionData)
> at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
> options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo,
> DbConnectionPool pool, DbConnection owningConnection,
> DbConnectionOptions userOptions)
> at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool
> pool, DbConnection owningObject, DbConnectionOptions options,
> DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
> at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection
> owningObject, DbConnectionOptions userOptions, DbConnectionInternal
> oldConnection)
> at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection
> owningObject, DbConnectionOptions userOptions, DbConnectionInternal
> oldConnection)
> at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
> owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
> allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
> userOptions, DbConnectionInternal& connection)
> at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
> owningObject, TaskCompletionSource`1 retry, DbConnectionOptions
> userOptions, DbConnectionInternal& connection)
> at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
> owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions
> userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&
> connection)
> at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection
> outerConnection, DbConnectionFactory connectionFactory,
> TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
> at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
> outerConnection, DbConnectionFactory connectionFactory,
> TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
> at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1
> retry)
> at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1
> retry)
> at System.Data.SqlClient.SqlConnection.Open()
> at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass2f.<UsingConnection>b__2d()
> at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
> at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1
> operation)
> at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action
> operation)
> at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection
> sqlConnection, Action`1 act)
> at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection
> sqlConnection, Action`1 act)
> at System.Data.Entity.SqlServer.SqlProviderServices.GetDbProviderManifestToken(DbConnection
> connection)
> at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection
> connection)
> InnerException:
I have found out that the reason for this is that the TestContext.Parents.Add(..) calls the default constructor of my TestContext and that one does not call a base constructor. I have found a very dirty workaround for this which looks like the following.
public class TestContext : DbContext
{
private static string dbname = "TestDB";
public TestContext() : base(dbname)
{
}
public TestContext(string connectionString)
: base(connectionString)
{
dbname = connectionString;
Database.SetInitializer(new MigrateDatabaseToLatestVersion<TestContext, Configuration>());
}
After this every things works fine but I do not like this solution. Especially when I will work with multiple threads supporting multiple database I will ran into a problem with the static variable.
If have already tried the solutions from the following sites but nothing had worked.
Entity Framework code first custom connection string and migrations
Changing connection string at runtime
So has anyone else some suggestions how this could be solved?
--- Edit: 24.03 ----
further investigations has shown that the described problem and the second call of the default constructor only occurs when the migration is enabled.
I have found a solution or better a workaround I can live with.
To solve the problem I use multiple database context to access the database. I will have on database context which reflects the complete database structure. For this database context the migration feature will be enabled. This database context will be used to create the database. With this limitation I can use the following code for the first database creation. But I need to be sure that only one thread at the time creates a new database.
public class TestContext : DbContext
{
private static string connection = "TestDb";
public TestContext() : this(connection)
{}
public TestContext (string newConnection) : base(connection)
{
connection = newConnection;
Database.SetInitializer(new MigrateDatabaseToLatestVersion<TestContext, Configuration>());
}
…
The other database contexts are accessing only a part of the database system but set the database initializer to null. With this I can access multiple databases with dynamic strings and do not have the problems with the default constructor. I also can access the databases with different threads without worring about the static variable.
public class SecondTestContext : DbContext
{
public SecondTestContext (string dbName) : base(dbName)
{
Database.SetInitializer<SecondTestContext>(null);
}
…
Related
I don't understand why I'm getting a syntax error when this line of code executes:
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<Kitti_getProductGroupDetail_Result>("Kitti_getProductGroupDetail #ProductGroupId", #params);
Here is the whole method:
public virtual ObjectResult<Kitti_getProductGroupDetail_Result> Kitti_getProductGroupDetail(Guid ProductGroupId)
{
var #params = new SqlParameter[]
{
new SqlParameter("ProductGroupId", ProductGroupId)
};
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<Kitti_getProductGroupDetail_Result>("Kitti_getProductGroupDetail #ProductGroupId", #params);
}
Here is the calling method:
public System.Collections.Generic.IEnumerable<ProductDetail> getProductDetailsFromSP(Guid ProductGroupId)
{
System.Collections.Generic.List<ProductDetail> productDetailList = new System.Collections.Generic.List<ProductDetail>();
using (var context = new EFDbContext())
{
var result = context.Kitti_getProductGroupDetail(ProductGroupId);
foreach (Kitti_getProductGroupDetail_Result res in result)
{
ProductDetail productDetail = new ProductDetail();
productDetail.ProductId = res.productid;
productDetail.SizeId = res.sizeid;
productDetail.SizeDescription = res.sizedescription;
productDetail.SizeRank = res.sizerank;
productDetail.ColorId = res.colorid;
productDetail.ColorDescription = res.colordescription;
productDetail.ColorRank = res.colorrank;
productDetail.QuantityRemainingInStock = res.quantityremaininginstock;
productDetail.ProductGroupId = res.productgroupid;
productDetail.ProductGroupName = "ProductGroupName is currently not in the stored procedure or in EF";
productDetail.Description = res.description;
productDetailList.Add(productDetail);
}
}
return productDetailList;
}
The result object:
public partial class Kitti_getProductGroupDetail_Result
{
public System.Guid productid { get; set; }
public System.Guid productgroupid { get; set; }
public string description { get; set; }
public decimal price { get; set; }
public Nullable<System.Guid> colorid { get; set; }
public string colordescription { get; set; }
public int colorrank { get; set; }
public Nullable<System.Guid> sizeid { get; set; }
public string sizedescription { get; set; }
public int sizerank { get; set; }
public int quantityremaininginstock { get; set; }
public string productname { get; set; }
public string imagesrc { get; set; }
}
Finally here is my stored procedure:
ALTER PROCEDURE [dbo].[Kitti_getProductGroupDetail]
#ProductGroupId uniqueidentifier
-- Insert statements for procedure here
SELECT product.ProductId as 'productid', product.ProductGroupId as 'productgroupid', product.[Description] as 'description'
, product.Price as 'price', product.ColorId as 'colorid', color.ColorDescription as 'colordescription', color.ColorRank as 'colorrank',
product.SizeId as 'sizeid', size.SizeDescription as 'sizedescription', size.SizeRank as 'sizerank', product.QuantityRemainingInStock as 'quantityremaininginstock',
product.Name as 'productname', product.ProductImageSrc as 'imagesrc'
FROM dbo.Product product
INNER JOIN dbo.Color color
on color.ColorId = product.ColorId
INNER JOIN dbo.Size size
on size.SizeId = product.SizeId
INNER JOIN dbo.ProductGroup productgroup
on productgroup.ProductGroupId = product.ProductGroupId
WHERE product.ProductGroupId = #ProductGroupId
AND product.QuantityRemainingInStock > 0
ProductGroupId is definitely getting populated. What doesn't EF like about my code? I have a similar method that does not require a parameter to execute the stored procedure - it works fine
// this works just fine
public virtual ObjectResult<Kitti_getProductDetailsAndCategory_Result> Kitti_getProductDetailsAndCategory()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<Kitti_getProductDetailsAndCategory_Result>("Kitti_getProductDetailsAndCategory");
//ExecuteFunction changed to ExecuteStoreQuery
}
stack trace:
Incorrect syntax near 'Kitti_getProductGroupDetail'.
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: Incorrect syntax near 'Kitti_getProductGroupDetail'.
Source Error:
Line 40: };
Line 41:
Line 42: return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery("Kitti_getProductGroupDetail #ProductGroupId", #params);
Line 43: }
Line 44:
Source File: C:\Concrete\EFDbContext.cs Line: 42
Stack Trace:
[SqlException (0x80131904): Incorrect syntax near 'Kitti_getProductGroupDetail'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +2444082
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5775560
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4169
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +89
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption) +409
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) +2127
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) +911
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +64
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +240
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext1 c) +14
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +402
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +166
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal(String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) +266
System.Data.Entity.Core.Objects.<>c__DisplayClass691.<ExecuteStoreQueryReliably>b__68() +44
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
System.Data.Entity.Core.Objects.<>c__DisplayClass691.<ExecuteStoreQueryReliably>b__67() +167
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1 operation) +190
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably(String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) +462
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery(String commandText, Object[] parameters) +83
KittiCutieFashion.Domain.Concrete.EFDbContext.Kitti_getProductGroupDetail(Guid ProductGroupId) in C:\KittiCutieFashion\KittiCutieFashion.Domain\Concrete\EFDbContext.cs:42
KittiCutieFashion.Domain.Concrete.EFDbContext.getProductDetailsFromSP(Guid ProductGroupId) in C:\KittiCutieFashion\KittiCutieFashion.Domain\Concrete\EFDbContext.cs:82
KittiCutieFashion.Domain.Concrete.EFProductDetailRepository.get_ProductDetail() in C:\KittiCutieFashion\KittiCutieFashion.Domain\Concrete\EFProductDetailRepository.cs:33
KittiCutieFashion.WebUI.Controllers.ProductDetailController.ProductDetailView(String returnUrl) in C:\KittiCutieFashion\KittiCutieFashion.WebUI\Controllers\ProductDetailController.cs:43
lambda_method(Closure , ControllerBase , Object[] ) +103
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c.b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.b__11_0() +50
System.Web.Mvc.Async.<>c__DisplayClass11_1.b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.b__3() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.b__5(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9748493
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2558.0
The version of sql server I am using happens to be 2005 not sure if that has anything to do with it.
I have some deployed windows forms applications that stopped working on a specific machine. A fresh reinstall redeploying all .exes and .dlls have no effect on resolving the error.
On the very first database access on the application, the error is such as:
Microsoft .NET Framework
Consulte o final desta mensagem para obter detalhes sobre como chamar a
depuração just-in-time (JIT) em vez desta caixa de diálogo.
************** Texto de Exceção **************
System.Data.SqlClient.SqlException (0x80131904): Erro de rede ou específico à instância ao estabelecer conexão com o SQL Server. O servidor não foi encontrado ou não estava acessível. Verifique se o nome da instância está correto e se o SQL Server está configurado para permitir conexões remotas. (provider: Named Pipes Provider, error: 40 - Não foi possível abrir uma conexão com o SQL Server) ---> System.ComponentModel.Win32Exception (0x80004005): O sistema não pode encontrar o arquivo especificado
em System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
em System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
em System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
em System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
em System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
em System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
em System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions)
em System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
em System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
em System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions)
em System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions)
em System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
em System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
em System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
em System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
em System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
em System.Data.SqlClient.SqlConnection.Open()
em CodeFluent.Runtime.CodeFluentPersistence.OpenConnection()
em CodeFluent.Runtime.CodeFluentPersistence.InternalExecuteReader(CommandBehavior behavior, Boolean firstTry)
em CodeFluent.Runtime.CodeFluentPersistence.ExecuteReader(CommandBehavior behavior)
em CodeFluent.Runtime.CodeFluentPersistence.ExecuteReader()
My app.config file has a
<configSections>
<section name="MyApp" type="CodeFluent.Runtime.CodeFluentConfigurationSectionHandler, CodeFluent.Runtime" />
</configSections>
and then a tag like:
<MyApp persistenceTypeName="MySQL"
I understand that this makes codefluent look for MySql.Data instead of the default System.Data (Sql Server)...
What may be causing this specific deployment of the winforms application on a specific machine, to be overriding that?
The key point on the error stack trace is:
em System.Data.SqlClient.SqlConnection.Open()
em CodeFluent.Runtime.CodeFluentPersistence.OpenConnection()
OpenConnection transitions to System.Data, instead of MySql....
What should I check on the Windows 7 OS of this machine that could cause such strange behavior, as opposed to other Windows 7 OS with the same application working just fine?
The following code:
private void IsolateIssue()
{
using (var context = new SomeName.Models.MobileServiceContext())
{
System.Diagnostics.Debug.WriteLine(context.Database.Connection.ConnectionString);
var numberOfItems = context.TodoItems.Count();
}
}
results in an error (when calling var numberOfItems):
An exception of type 'System.Data.SqlClient.SqlException' occurred in
EntityFramework.dll but was not handled in user code Additional
information: Cannot open database "master" requested by the login. The
login failed. Login failed for user 'SomeLoginName'.
This is my connectionString:
"Data Source=ServerName.database.windows.net;Initial
Catalog=SomeDataBaseName;User
ID=SomeLoginName;Password=SomePassword};Asynchronous
Processing=True;TrustServerCertificate=False;"
It is obvious that it can not connect to the master database. Given the username and password, I also cannot connect to the master database with LinqPad (when I try I get a similar error). However, it should not connect at all to the master database. When I try to login on SomeDataBaseName with Linqpad, I succeed in getting the number of todoItems (17). This proves that there is no need to access the master database at all for the given purpose.
First, I have to make sure I can get the number of items in my mobile service. How do I do that? The initial Catalog shows that it should connect to SomeDataBaseName and there is no need to connect to the master database to get the number of items. How do I avoid that it tries to do so?
In case it helps, here is the stacktrace:
StackTrace " at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)\r\n at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)\r\n at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)\r\n at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)\r\n at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)\r\n at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)\r\n at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)\r\n at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)\r\n at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)\r\n at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)\r\n at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)\r\n at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)\r\n at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)\r\n at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)\r\n at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)\r\n at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry)\r\n at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry)\r\n at System.Data.SqlClient.SqlConnection.Open()\r\n at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c)\r\n at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action2 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed)\r\n at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)\r\n at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass34.<UsingConnection>b__32()\r\n at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()\r\n at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)\r\n at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)\r\n at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action1 act)\r\n at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act)\r\n at System.Data.Entity.SqlServer.SqlProviderServices.DropDatabase(SqlConnection sqlConnection, Nullable1 commandTimeout, String databaseName)\r\n at System.Data.Entity.SqlServer.SqlProviderServices.DbDeleteDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection)\r\n at System.Data.Entity.Core.Common.DbProviderServices.DeleteDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection)\r\n at System.Data.Entity.Core.Objects.ObjectContext.DeleteDatabase()\r\n at System.Data.Entity.Internal.DatabaseOperations.Delete(ObjectContext objectContext)\r\n at System.Data.Entity.Database.Delete()\r\n at System.Data.Entity.DropCreateDatabaseIfModelChanges1.InitializeDatabase(TContext context)\r\n at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf1.<CreateInitializationAction>b__e()\r\n at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)\r\n at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()\r\n at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)\r\n at System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input)\r\n at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action)\r\n at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()\r\n at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)\r\n at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()\r\n at System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()\r\n at System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider()\r\n at System.Linq.Queryable.Count[TSource](IQueryable`1 source)\r\n
I see this in your stack: System.Data.Entity.DropCreateDatabaseIfModelChanges. I believe that EF needs access to the master database in order to drop and recreate your database.
This blog post mentions the ClearDatabaseSchemaIfModelChanges initializer, which may do what you want: http://blogs.msdn.com/b/azuremobile/archive/2014/06/07/fresh-updates-to-azure-mobile-services-net.aspx
Currently working with codefirst v5 on .net 4.5
I have 1 'master' context which includes a locations table called 'Geonames' (snippet below)
public class CoreContext : DbContext
: base("Conn")
{
public DbSet<GeoName> GeoNames { get; set; }
}
The reference here is simply to be able to manage migrations on the table.
Site will have the ability to 'plug-in' different location providers and the geonames table is there to provide a local provider implementation.
The provider is set in the configuration of the website simply setting the classname and namespace of the actual implementation.
It uses an interface like this (simplified)
public interface ILocationProvider
{
IEnumerable<Location> LocationsByName(String Name);
}
The concrete implementation is instantiated as below (simplified)
public static ILocationProvider GetLocationProvider()
{
ILocationProvider Provider = null;
Provider = Activator.CreateInstance(Type.GetType("{selected namespace.classname}")) as ILocationProvider;
}
catch (Exception ex)
{
throw ex;
}
if (Provider == null)
{
throw new NullReferenceException("Could not create an instance of the location Provider");
}
return Provider;
}
The concrete implementation is as follows(simplified)
public class LocalLocationProvider : ILocationProvider
{
public IEnumerable<Location> LocationsByName(string Name)
{
List<Location> locations = new List<Location>();
using (var db = new LocalLocationContext())
{
foreach (var item in db.GeoNames.Where(X => X.Name.Contains(Name)))
{
locations.Add(
new Location { Id = item.Id, Name = item.Name, GeoLocation = item.GeoLocation }
);
}
}
return locations;
}
private class LocalLocationContext : DbContext
{
public LocalLocationContext()
: base("Conn")
{
Database.SetInitializer<LocalLocationContext>(null);
}
public DbSet<GeoName> GeoNames { get; set; }
}
}
The concrete implementation instantiates just fine and I call the method 'LocationsByName' .. but here the trouble starts. When the code line below executes
foreach (var item in db.GeoNames.Where(X => X.Name.Contains(Name)))
{
..
}
I get the following error.
Exception Details: System.ComponentModel.Win32Exception: The wait operation timed out
[Win32Exception (0x80004005): The wait operation timed out]
[SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1753986
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5296058
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +365
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +1379
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +175
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +134
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +437
I have tried to instantiate 'LocalLocationContext' without using the 'Activator.CreateInstance()' method I can query the data just fine.
To me it seems obvious that it has got something to do with how I get my actual implemention of the location provider just can't spot what the error or issue is.
Thanks in advance.
I'm trying to execute an SQL Job using a CRM Workflow by making a custom activity. In my code, an online tutorial had me construct it like this (in c#):
[CrmWorkflowActivity("A test activity to run SQL Jobs")]
public sealed class ExecuteSQLJob : System.Activities.CodeActivity
{
#region Inputs
[Input("Job Name")]
[Default("BMS_ExtractTransformLoad")]
public InArgument<String> JobName { get; set; }
[Input("Server Connection")]
[Default("HBSSQL2008/MSSQLSERVER")] //<--This String
public InArgument<String> ServerName { get; set; }
[Input("User Name")]
[Default("-----")]
public InArgument<String> UserName { get; set; }
[Input("Password")]
[Default("-----")]
public InArgument<String> Password { get; set; }
#endregion
protected override void Execute(CodeActivityContext context)
{
Server server = new Server(ServerName.Get(context)); //<--Is used here
try
{
server.ConnectionContext.LoginSecure = false;
server.ConnectionContext.Login = UserName.Get(context);
server.ConnectionContext.Password = Password.Get(context);
server.ConnectionContext.Connect();
Job job = server.JobServer.Jobs[JobName.Get(context)];
job.Start();
}
finally
{
if (server.ConnectionContext.IsOpen)
{
server.ConnectionContext.Disconnect();
}
}
}
}
However, when I try to run this workflow, it throws an error saying it couldn't connect to the server. (Specifically, the error is thrown on the server.ConnectionContext.Connect() method call).
Is the problem the serverName String? If so, how can I find out the correct serverName to use?
Thanks for any help!
EDIT:
Here's some additional info...
This is how I got the server and instance name the first time:
And here's the error on the CRM Workflow:
Workflow suspended temporarily due to error: Unhandled Exception: Microsoft.SqlServer.Management.Common.ConnectionFailureException: Failed to connect to server HBSSQL2008.
at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
at ExecuteSQLJob.ExecuteSQLJob.Execute(CodeActivityContext context)
at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)
Inner Exception: System.Data.SqlClient.SqlException: Login failed for user 'rnkelch'.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
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 Microsoft.SqlServer.Management.Common.ConnectionManager.InternalConnect(WindowsIdentity impersonatedIdentity)
at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
Sorry I didn't include this originally, thanks for your help so far
Although not entirely relevant to the question but nonetheless, a useful site to bookmark to aid in your getting the connection string right.
For SQL Server 2008, see this linky here, on the same site
Portion of the server string is this:
Server=myServerName\theInstanceName
You have used the forward slash in your declarative above
[Input("Server Connection")]
[Default("HBSSQL2008/MSSQLSERVER")] //<--This String
public InArgument<String> ServerName { get; set; }
Change it to this:
[Input("Server Connection")]
[Default("HBSSQL2008\\MSSQLSERVER")] //<--This String
public InArgument<String> ServerName { get; set; }
Might need to double-slash it to escape it..
Ok, I think I figured it out now.
Because there is only one instance of SQL running on our server, I don't actually need to use the ServerName\InstanceName format. Both hbssql2008 and HBSSQL2008 allow me to connect. In addition, the IP works as well.
Also, another issue I came across was the the user name and password I was using was from Windows Integrated Security, not the sql server's security. Therefore, I created a new account on the server with appropriate permissions and sql security info and it allowed me to connect.
Thank you all for your help!