Search Results

Search found 497 results on 20 pages for 'sqlconnection'.

Page 4/20 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Creating packages in code - Package Configurations

    Continuing my theme of building various types of packages in code, this example shows how to building a package with package configurations. Incidentally it shows you how to add a variable, and a connection too. It covers the five most common configurations: Configuration File Indirect Configuration File SQL Server Indirect SQL Server Environment Variable  For a general overview try the SQL Server Books Online Package Configurations topic. The sample uses a a simple helper function ApplyConfig to create or update a configuration, although in the example we will only ever create. The most useful knowledge is the configuration string (Configuration.ConfigurationString) that you need to set. Configuration Type Configuration String Description Configuration File The full path and file name of an XML configuration file. The file can contain one or more configuration and includes the target path and new value to set. Indirect Configuration File An environment variable the value of which contains full path and file name of an XML configuration file as per the Configuration File type described above. SQL Server A three part configuration string, with each part being quote delimited and separated by a semi-colon. -- The first part is the connection manager name. The connection tells you which server and database to look for the configuration table. -- The second part is the name of the configuration table. The table is of a standard format, use the Package Configuration Wizard to help create an example, or see the sample script files below. The table contains one or more rows or configuration items each with a target path and new value. -- The third and final part is the optional filter name. A configuration table can contain multiple configurations, and the filter is  literal value that can be used to group items together and act as a filter clause when configurations are being read. If you do not need a filter, just leave the value empty. Indirect SQL Server An environment variable the value of which is the three part configuration string as per the SQL Server type described above. Environment Variable An environment variable the value of which is the value to set in the package. This is slightly different to the other examples as the configuration definition in the package also includes the target information. In our ApplyConfig function this is the only example that actually supplies a target value for the Configuration.PackagePath property. The path is an XPath style path for the target property, \Package.Variables[User::Variable].Properties[Value], the equivalent of which can be seen in the screenshot below, with the object being our variable called Variable, and the property to set is the Value property of that variable object. The configurations as seen when opening the generated package in BIDS: The sample code creates the package, adds a variable and connection manager, enables configurations, and then adds our example configurations. The package is then saved to disk, useful for checking the package and testing, before finally executing, just to prove it is valid. There are some external resources used here, namely some environment variables and a table, see below for more details. namespace Konesans.Dts.Samples { using System; using Microsoft.SqlServer.Dts.Runtime; public class PackageConfigurations { public void CreatePackage() { // Create a new package Package package = new Package(); package.Name = "ConfigurationSample"; // Add a variable, the target for our configurations package.Variables.Add("Variable", false, "User", 0); // Add a connection, for SQL configurations // Add the SQL OLE-DB connection ConnectionManager connectionManagerOleDb = package.Connections.Add("OLEDB"); connectionManagerOleDb.Name = "SQLConnection"; connectionManagerOleDb.ConnectionString = "Provider=SQLOLEDB.1;Data Source=(local);Initial Catalog=master;Integrated Security=SSPI;"; // Add our example configurations, first must enable package setting package.EnableConfigurations = true; // Direct configuration file, see sample file this.ApplyConfig(package, "Configuration File", DTSConfigurationType.ConfigFile, "C:\\Temp\\XmlConfig.dtsConfig", string.Empty); // Indirect configuration file, the emvironment variable XmlConfigFileEnvironmentVariable // contains the path to the configuration file, e.g. C:\Temp\XmlConfig.dtsConfig this.ApplyConfig(package, "Indirect Configuration File", DTSConfigurationType.IConfigFile, "XmlConfigFileEnvironmentVariable", string.Empty); // Direct SQL Server configuration, uses the SQLConnection package connection to read // configurations from the [dbo].[SSIS Configurations] table, with a filter of "SampleFilter" this.ApplyConfig(package, "SQL Server", DTSConfigurationType.SqlServer, "\"SQLConnection\";\"[dbo].[SSIS Configurations]\";\"SampleFilter\";", string.Empty); // Indirect SQL Server configuration, the environment variable "SQLServerEnvironmentVariable" // contains the configuration string e.g. "SQLConnection";"[dbo].[SSIS Configurations]";"SampleFilter"; this.ApplyConfig(package, "Indirect SQL Server", DTSConfigurationType.ISqlServer, "SQLServerEnvironmentVariable", string.Empty); // Direct environment variable, the value of the EnvironmentVariable environment variable is // applied to the target property, the value of the "User::Variable" package variable this.ApplyConfig(package, "EnvironmentVariable", DTSConfigurationType.EnvVariable, "EnvironmentVariable", "\\Package.Variables[User::Variable].Properties[Value]"); #if DEBUG // Save package to disk, DEBUG only new Application().SaveToXml(String.Format(@"C:\Temp\{0}.dtsx", package.Name), package, null); Console.WriteLine(@"C:\Temp\{0}.dtsx", package.Name); #endif // Execute package package.Execute(); // Basic check for warnings foreach (DtsWarning warning in package.Warnings) { Console.WriteLine("WarningCode : {0}", warning.WarningCode); Console.WriteLine(" SubComponent : {0}", warning.SubComponent); Console.WriteLine(" Description : {0}", warning.Description); Console.WriteLine(); } // Basic check for errors foreach (DtsError error in package.Errors) { Console.WriteLine("ErrorCode : {0}", error.ErrorCode); Console.WriteLine(" SubComponent : {0}", error.SubComponent); Console.WriteLine(" Description : {0}", error.Description); Console.WriteLine(); } package.Dispose(); } /// <summary> /// Add or update an package configuration. /// </summary> /// <param name="package">The package.</param> /// <param name="name">The configuration name.</param> /// <param name="type">The type of configuration</param> /// <param name="setting">The configuration setting.</param> /// <param name="target">The target of the configuration, leave blank if not required.</param> internal void ApplyConfig(Package package, string name, DTSConfigurationType type, string setting, string target) { Configurations configurations = package.Configurations; Configuration configuration; if (configurations.Contains(name)) { configuration = configurations[name]; } else { configuration = configurations.Add(); } configuration.Name = name; configuration.ConfigurationType = type; configuration.ConfigurationString = setting; configuration.PackagePath = target; } } } The following table lists the environment variables required for the full example to work along with some sample values. Variable Sample value EnvironmentVariable 1 SQLServerEnvironmentVariable "SQLConnection";"[dbo].[SSIS Configurations]";"SampleFilter"; XmlConfigFileEnvironmentVariable C:\Temp\XmlConfig.dtsConfig Sample code, package and configuration file. ConfigurationApplication.cs ConfigurationSample.dtsx XmlConfig.dtsConfig

    Read the article

  • Help needed on an SQL configuration problem.

    - by user321048
    I have been banging my head with this one more the two weeks, and still don't know what the problem is ( I can't narrow it down). The problem is the following. I have a solution with 3 project in it all written in c# and I with LINQ. One project is the main web site, the other is the data layer (communication with the database) and the third one is a custom little CMS. The problem is the following: On a hosting provider when I publish the site it all works perfectly, but this site was needed to be hosted on the client server so I needed to do that. But the problem is that I also needed to configure the client server, because they don't have an Administrator employed (I know, I know ;) ). For the first time I some how managed, to set it up but a problem appear. My main web site is working just as it suppose to be - it reads (communicates with) the database, but My CMS is not. It shows the first log in page, but after that when I try to log in it throws the following error: 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: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.) 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: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.) 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: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4846887 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) +4860189 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.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user) +44 System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe() +45 System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode() +20 System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +57 System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +23 System.Linq.Queryable.Count(IQueryable`1 source) +240 CMS.Security.UserProfile.LoginUser() in C:\Documents and Settings\Dimitar\Desktop\New Mepso Final 08_04\CMS\Classes\UserProfile.cs:132 CMS.Default.Login1_Authenticate(Object sender, AuthenticateEventArgs e) in C:\Documents and Settings\Dimitar\Desktop\New Mepso Final 08_04\CMS\Default.aspx.cs:37 System.Web.UI.WebControls.Login.OnAuthenticate(AuthenticateEventArgs e) +108 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 Maybe this is a dumb question, but I cannot find the root of the problem, let alone the solution. So far I have tried the following: -setting time out on connection string to a higher value -configuration and after that turning off server firewall -checking the connection string over and over again (they are the same for all three projects and are saved in web.config) Important notes: I have tried executing the project from VS2008 with a connection string to the same database and the results are the same. That's why I think the problem is the SQL Server 2005 and not the IIS7. Any bit of information is more then welcomed.

    Read the article

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

    - by baeltazor
    Hi All 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

    Read the article

  • Using using to dispose of nested objects

    - by TooFat
    If I have code with nested objects like this do I need to use the nested using statements to make sure that both the SQLCommand and the SQLConnection objects are disposed of properly like shown below or am I ok if the code that instantiates the SQLCommand is within the outer using statement. using (SqlConnection conn = new SqlConnection(sqlConnString)) { using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = cmdTextHere; conn.Open(); cmd.Connection = conn; rowsAffected = cmd.ExecuteNonQuery(); } }

    Read the article

  • How to run an .exe application in another computer?

    - by ADAM
    I am working on a C# application in Visual Studio 2013. When I run the .exe file from my computer, the application runs very well and all the features work. When I tried to run the .exe on another computer, the database side doesn't work well and the connection with the database couldn't be opened. The SqlConnection is constructed as follows: SqlConnection cn = new SqlConnection("Data Source=ADAM-PC;Initial Catalog=integrationdatabase;Integrated Security=True" I don't know how to change the data source to make the connection with the database established in another computer. How can I solve this problem?

    Read the article

  • INSERT SQL in Java

    - by Pierre
    Hello. I have a Java application and I want to use SQL database. I have a class for my connection : public class SQLConnection{ private static String url = "jdbc:postgresql://localhost:5432/table"; private static String user = "postgres"; private static String passwd = "toto"; private static Connection connect; public static Connection getInstance(){ if(connect == null){ try { connect = DriverManager.getConnection(url, user, passwd); } catch (SQLException e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Connection Error", JOptionPane.ERROR_MESSAGE); } } return connect; } } And now, in another class I succeeded to print my values but when I attempt to insert a value nothing is happening ... Here's my code : try { Statement state = SQLConnection.getInstance().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); Statement state2 = SQLConnection.getInstance().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); state2.executeUpdate("INSERT INTO table(field1) VALUES (\"Value\")"); // Here's my problem ResultSet res = state.executeQuery("SELECT * FROM plateau");

    Read the article

  • Comparing LINQ to SQL vs the classic SqlCommand

    tweetmeme_url = 'http://alpascual.com/blog/comparing-linq-to-sql-vs-the-classic-sqlcommand/';tweetmeme_source = 'alpascual';When you are coming from using SqlCommand and SqlConnection is difficult to move to another library for your database needs. For those people still in the limbo to make the decision to move to another DAL, here is a comparison to help you see the light or to move away for ever.   How to do a select query using SqlCommand: 1: SqlConnection myConnection = new...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Comparing LINQ to SQL vs the classic SqlCommand

    tweetmeme_url = 'http://alpascual.com/blog/comparing-linq-to-sql-vs-the-classic-sqlcommand/';tweetmeme_source = 'alpascual';When you are coming from using SqlCommand and SqlConnection is difficult to move to another library for your database needs. For those people still in the limbo to make the decision to move to another DAL, here is a comparison to help you see the light or to move away for ever.   How to do a select query using SqlCommand: 1: SqlConnection myConnection = new...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Run a .sql script file in C#

    - by SAMIR BHOGAYTA
    using System.Data.SqlClient; using System.IO; using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.Smo; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True"; FileInfo file = new FileInfo("C:\\myscript.sql"); string script = file.OpenText().ReadToEnd(); SqlConnection conn = new SqlConnection(sqlConnectionString); Server server = new Server(new ServerConnection(conn)); server.ConnectionContext.ExecuteNonQuery(script); } } }

    Read the article

  • Unable to connect SQL Server instance from Visual Studio 2008 Version 9.0

    - by salvationishere
    I am getting the below error from VS on an 32-bit XP Professional server even though I set Tools-Options-Database Tools-Data Connections to "SIDEKICK", which is the name of my computer. In other words SIDEKICK should default to the full SQLSERVER. In other words, I want VS to use SQLSERVER instead of SQLSERVER EXPRESS. And I can clearly see my database both from VS in the Server Explorer and also in SSMS 2008. Furthermore, I can view the tables of this database in Server Explorer from VS. I do not get any build errors. And it looks like all of the naming is consistent in my web.config file. I am developing my website according to a Microsoft tutorial, so I should not be getting an error. Yet I get the following exception when I run this code below: CreateAccounts.aspx.cs file protected void CreateAccountButton_Click(object sender, EventArgs e) { MembershipCreateStatus createStatus; //This line below is where the exception occurs MembershipUser newUser = Membership.CreateUser(Username.Text, Password.Text, Email.Text, passwordQuestion, SecurityAnswer.Text, true, out createStatus); And here is what the exception looks like: System.Web.HttpException was unhandled by user code Message="Unable to connect to SQL Server database." Source="System.Web" ErrorCode=-2147467259 StackTrace: at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) at System.Web.DataAccess.SqlConnectionHelper.EnsureSqlExpressDBFile(String connectionString) at System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation) at System.Web.Security.SqlMembershipProvider.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) at System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) at System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, MembershipCreateStatus& status) at Membership_CreatingUserAccounts.CreateAccountButton_Click(Object sender, EventArgs e) in c:\Documents and Settings\Admin\My Documents\Visual Studio 2008\WebSites\WebSite2\Membership\CreatingUserAccounts.aspx.cs:line 24 at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) InnerException: System.Web.HttpException Message="Unable to connect to SQL Server database." Source="System.Web" ErrorCode=-2147467259 StackTrace: at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) at System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) at System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) InnerException: System.Data.SqlClient.SqlException Message="The user instance login flag is not supported on this version of SQL Server. The connection will be closed." Source=".Net SqlClient Data Provider" ErrorCode=-2146232060 Class=14 LineNumber=65536 Number=18493 Procedure="" Server="." State=1 StackTrace: at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) 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.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) 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.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) 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.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) InnerException: The web.config connection string looks like: <connectionStrings> <add name="SecurityTutorialsConnectionString" connectionString="data source=.;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|SecurityTutorialsDatabase3.mdf;User Instance=true" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <membership defaultProvider="SecurityTutorialsSqlMembershipProvider"> <providers> <add name="SecurityTutorialsSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="SecurityTutorialsConnectionString" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="SecurityTutorials" requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/> </providers> </membership>

    Read the article

  • using securestring for a sql connection

    - by Rick
    Hi, I want to use a SecureString to hold a connection string for a database. But as soon as I set the SqlConnection object's ConnectionString property to the value of the securestring surely it will become visible to any other application that is able to read my application's memory? I have made the following assumptions: a) I am not able to instantiate a SqlConnection object outside of managed memory b) any string within managed memory can be read by an application such as Hawkeye

    Read the article

  • i don't solve "must declare a body because it is not marked abstract, extern, or partial" problem?

    - by programmerist
    How can i solve "must declare a body because it is not marked abstract, extern, or partial". This problem. Can you show me some advices? Full Error message is about Save, Update, Delete, Select events... Full message sample : GenoTip.DAL._AccessorForSQL.Save(string, System.Collections.Specialized.ListDictionary, System.Data.CommandType)' must declare a body because it is not marked abstract, extern, or partial This error also return in Update, Delete, Select... public abstract class _AccessorForSQL { public virtual bool Save(string sp, ListDictionary ld, CommandType cmdType); public virtual bool Update(); public virtual bool Delete(); public virtual DataSet Select(); } class GenAccessor : _AccessorForSQL { DataSet ds; DataTable dt; public override bool Save(string sp, ListDictionary ld, CommandType cmdType) { SqlConnection con = null; SqlCommand cmd = null; SqlDataReader dr = null; try { con = GetConnection(); cmd = new SqlCommand(sp, con); con.Open(); cmd.CommandType = cmdType; foreach (string ky in ld.Keys) { cmd.Parameters.AddWithValue(ky, ld[ky]); } dr = cmd.ExecuteReader(); ds = new DataSet(); dt = new DataTable(); ds.Tables.Add(dt); ds.Load(dr, LoadOption.OverwriteChanges, dt); } catch (Exception exp) { HttpContext.Current.Trace.Warn("Error in GetCustomerByID()", exp.Message, exp); } finally { if (dr != null) dr.Close(); if (con != null) con.Close(); } return (ds.Tables[0].Rows.Count 0) ? true : false; } public override bool Update() { return true; } public override bool Delete() { return true; } public override DataSet Select() { DataSet dst = new DataSet(); return dst; } private static SqlConnection GetConnection() { string connStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); return conn; }

    Read the article

  • WebService doesn't read web.config

    - by phenevo
    Hi, I've got 3 connectionstrings in web.config, and I used theirs like this: using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SomeName"].ConnectionString)) Every metgod is called by winforms application. One of webmethods doesn't work properly because it reads only one connectionString: data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true It's not a connectionString from my web.config . I invoke every method in the same way. How it's impossible ??

    Read the article

  • Am I Leaking ADO.NET Connections?

    - by HardCode
    Here is an example of my code in a DAL. All calls to the database's Stored Procedures are structured this way, and there is no in-line SQL. Friend Shared Function Save(ByVal s As MyClass) As Boolean Dim cn As SqlClient.SqlConnection = Dal.Connections.MyAppConnection Dim cmd As New SqlClient.SqlCommand Try cmd.Connection = cn cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = "proc_save_my_class" cmd.Parameters.AddWithValue("@param1", s.Foo) cmd.Parameters.AddWithValue("@param2", s.Bar) Return True Finally Dal.Utility.CleanupAdoObjects(cmd, cn) End Try End Function Here is the Connection factory (if I am using the correct term): Friend Shared Function MyAppConnection() As SqlClient.SqlConnection Dim cn As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ToString) cn.Open() If cn.State <> ConnectionState.Open Then ' CriticalException is a custom object inheriting from Exception. Throw New CriticalException("Could not connect to the database.") Else Return cn End If End Function Here is the Dal.Utility.CleaupAdoObjects() function: Friend Shared Sub CleanupAdoObjects(ByVal cmd As SqlCommand, ByVal cn As SqlConnection) If cmd IsNot Nothing Then cmd.Dispose() If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then cn.Close() End Sub I am getting a lot of "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding." error messages reported by the users. The application's DAL opens a connection, reads or saves data, and closes it. No connections are ever left open - intentionally! There is nothing obvious on the Windows 2000 Server hosting the SQL Server 2000 that would indicate a problem. Nothing in the Event Logs and nothing in the SQL Server logs. The timeouts happen randomly - I cannot reproduce. It happens early in the day with only 1 to 5 users in the system. It also happens with around 50 users in the system. The most connections to SQL Server via Performance Monitor, for all databases, has been about 74. The timeouts happen in code that both saves to, and reads from, the database in different parts of the application. The stack trace does not point to one or two offending DAL functions. It's happened in many different places. Does my ADO.NET code appear to be able to leak connections? I've goolged around a bit, and I've read that if the connection pool fills up, this can happen. However, I'm not explicitly setting any connection pooling. I've even tried to increase the Connection Timeout in the connection string, but timeouts happen long before the 300 second (5 minute) value: <add name="MyConnectionString" connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=SSPI;Connection Timeout=300;"/> I'm at a total loss already as to what is causing these Timeout issues. Any ideas are appreciated.

    Read the article

  • How to call base abstract or interface from DAL into BLL?

    - by programmerist
    How can i access abstract class in BLL ? i shouldn't see GenAccessor in BLL it must be private class GenAccessor . i should access Save method over _AccessorForSQL. ok? MY BLL cs: public class AccessorForSQL: GenoTip.DAL._AccessorForSQL { public bool Save(string Name, string SurName, string Adress) { ListDictionary ld = new ListDictionary(); ld.Add("@Name", Name); ld.Add("@SurName", SurName); ld.Add("@Adress", Adress); return **base.Save("sp_InsertCustomers", ld, CommandType.StoredProcedure);** } } i can not access base.Save....???????? it is my DAL Layer: namespace GenoTip.DAL { public abstract class _AccessorForSQL { public abstract bool Save(string sp, ListDictionary ld, CommandType cmdType); public abstract bool Update(); public abstract bool Delete(); public abstract DataSet Select(); } private class GenAccessor : _AccessorForSQL { DataSet ds; DataTable dt; public override bool Save(string sp, ListDictionary ld, CommandType cmdType) { SqlConnection con = null; SqlCommand cmd = null; SqlDataReader dr = null; try { con = GetConnection(); cmd = new SqlCommand(sp, con); con.Open(); cmd.CommandType = cmdType; foreach (string ky in ld.Keys) { cmd.Parameters.AddWithValue(ky, ld[ky]); } dr = cmd.ExecuteReader(); ds = new DataSet(); dt = new DataTable(); ds.Tables.Add(dt); ds.Load(dr, LoadOption.OverwriteChanges, dt); } catch (Exception exp) { HttpContext.Current.Trace.Warn("Error in GetCustomerByID()", exp.Message, exp); } finally { if (dr != null) dr.Close(); if (con != null) con.Close(); } return (ds.Tables[0].Rows.Count 0) ? true : false; } public override bool Update() { return true; } public override bool Delete() { return true; } public override DataSet Select() { DataSet dst = new DataSet(); return dst; } private static SqlConnection GetConnection() { string connStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); return conn; }

    Read the article

  • asp.net cannot update database

    - by tom
    string ConnectionString = WebConfigurationManager.ConnectionStrings["dbnameConnectionString"].ConnectionString; SqlConnection myConnection = new SqlConnection(ConnectionString); myConnection.Open(); try { string qry = "UPDATE customers SET firstname=@firstname WHERE cid=1"; SqlCommand insertQuery = new SqlCommand(qry, myConnection); insertQuery.Parameters.Add(new SqlParameter("@firstname", txtFirstname.Text)); insertQuery.ExecuteNonQuery(); myConnection.Close(); } catch (Exception ee) { } Any suggestions?

    Read the article

  • SQL Bulkcopy using DATA Access block

    - by Sathish
    I am using the below piece of code for SQL Bulk copy using (SqlConnection con = new SqlConnection(strConString)) { con.Open(); SqlBulkCopy sqlBC = new SqlBulkCopy(con); sqlBC.DestinationTableName = "SomeTable"; sqlBC.WriteToServer(dtOppConSummary); } Can anyone provide me the equvalent code using Data access block Enterprise library

    Read the article

  • Alert on gridview edit based on permission

    - by Vicky
    I have a gridview with edit option at the start of the row. Also I maintain a seperate table called Permission where I maintain user permissions. I have three different types of permissions like Admin, Leads, Programmers. These all three will have access to the gridview. Except admin if anyone tries to edit the gridview on clicking the edit option, I need to give an alert like This row has important validation and make sure you make proper changes. When I edit, the action with happen on table called Application. The table has a column called Comments. Also the alert should happen only when they try to edit rows where the Comments column have these values in them. ManLog datas Funding Approved Exported Applications My try so far. public bool IsApplicationUser(string userName) { return CheckUser(userName); } public static bool CheckUser(string userName) { string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); DataTable dt = new DataTable(); using (SqlConnection connection = new SqlConnection(CS)) { SqlCommand command = new SqlCommand(); command.Connection = connection; string strquery = "select * from Permissions where AppCode='Nest' and UserID = '" + userName + "'"; SqlCommand cmd = new SqlCommand(strquery, connection); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); } if (dt.Rows.Count >= 1) return true; else return true; } protected void Details_RowCommand(object sender, GridViewCommandEventArgs e) { string currentUser = HttpContext.Current.Request.LogonUserIdentity.Name; string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); string[] words = currentUser.Split('\\'); currentUser = words[1]; bool appuser = IsApplicationUser(currentUser); if (appuser) { DataSet ds = new DataSet(); using (SqlConnection connection = new SqlConnection(str)) { SqlCommand command = new SqlCommand(); command.Connection = connection; string strquery = "select Role_Cd from User_Role where AppCode='PM' and UserID = '" + currentUser + "'"; SqlCommand cmd = new SqlCommand(strquery, connection); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); } if (e.CommandName.Equals("Edit") && ds.Tables[0].Rows[0]["Role_Cd"].ToString().Trim() != "ADMIN") { int index = Convert.ToInt32(e.CommandArgument); GridView gvCurrentGrid = (GridView)sender; GridViewRow row = gvCurrentGrid.Rows[index]; string strID = ((Label)row.FindControl("lblID")).Text; string strAppName = ((Label)row.FindControl("lblAppName")).Text; Response.Redirect("AddApplication.aspx?ID=" + strID + "&AppName=" + strAppName + "&Edit=True"); } } } Kindly let me know if I need to add something. Thanks for any suggestions.

    Read the article

  • Flex: Package is unexpected error

    - by soden
    import mx.controls.Alert; package dbconfig // error line here { public class DBConn { private var dbConn:SQLConnection; private var dbFile:File; public function DBConn() { this.openConnection(); } public function openConnection(){ dbFile = File.applicationStorageDirectory.resolvePath("accounting.sqlite"); dbConn = new SQLConnection(); try { dbConn.open(dbFile); Alert.show("asdf"); } catch(e:SQLError) { Alert.show("SQL Error Occured: ", e.message); } } } }

    Read the article

  • getting database connectivity issue from only one part of my ASP.net project?

    - by Greg
    Hi, Something weird has started happening to my project with Dynamic Data. Suddenly I am now getting connection errors when going to the DD navigation pages, but things work fine on the default DD main page, and also other MVC pages I've added in myself work fine to the database. Any ideas? So in summary if I go to the following web pages: custom URL for my custom controller - this works fine, including getting database data main DD page from root URL - this works fine click on a link to a table maintenance page from the main DD page - GET DATABASE CONNECTIVITY ERROR Some items: * I'm using SQL Server Express 2008 * Doesn't seem to be any debug/error info in VS2010 at all I can see * Web config entry: <add name="Model1Container" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=GREG\SQLEXPRESS_2008;Initial Catalog=greg_development;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient"/> Error: Server Error in '/' 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 39: DropDownList1.Items.Add(new ListItem("[Not Set]", NullValueString)); Line 40: } Line 41: PopulateListControl(DropDownList1); Line 42: // Set the initial value if there is one Line 43: string initialValue = DefaultValue; Source File: U:\My Dropbox\source\ToplogyLibrary\Topology_Web_Dynamic\DynamicData\Filters\ForeignKey.ascx.cs Line: 41 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) +5009598 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) +239 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) +185 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +33 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +524 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +479 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +108 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +126 System.Data.SqlClient.SqlConnection.Open() +125 System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +52 [EntityException: The underlying provider failed on Open.] System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +161 System.Data.EntityClient.EntityConnection.Open() +98 System.Data.Objects.ObjectContext.EnsureConnection() +81 System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +46 System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +44 System.Data.Objects.ObjectQuery`1.GetEnumeratorInternal() +36 System.Data.Objects.ObjectQuery.System.Collections.IEnumerable.GetEnumerator() +10 System.Web.DynamicData.Misc.FillListItemCollection(IMetaTable table, ListItemCollection listItemCollection) +50 System.Web.DynamicData.QueryableFilterUserControl.PopulateListControl(ListControl listControl) +85 Topology_Web_Dynamic.ForeignKeyFilter.Page_Init(Object sender, EventArgs e) in U:\My Dropbox\source\ToplogyLibrary\Topology_Web_Dynamic\DynamicData\Filters\ForeignKey.ascx.cs:41 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35 System.Web.UI.Control.OnInit(EventArgs e) +91 System.Web.UI.UserControl.OnInit(EventArgs e) +83 System.Web.UI.Control.InitRecursive(Control namingContainer) +140 System.Web.UI.Control.AddedControl(Control control, Int32 index) +197 System.Web.UI.ControlCollection.Add(Control child) +79 System.Web.DynamicData.DynamicFilter.EnsureInit(IQueryableDataSource dataSource) +200 System.Web.DynamicData.QueryableFilterRepeater.<Page_InitComplete>b__1(DynamicFilter f) +11 System.Collections.Generic.List`1.ForEach(Action`1 action) +145 System.Web.DynamicData.QueryableFilterRepeater.Page_InitComplete(Object sender, EventArgs e) +607 System.EventHandler.Invoke(Object sender, EventArgs e) +0 System.Web.UI.Page.OnInitComplete(EventArgs e) +8871862 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +604 Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1

    Read the article

  • SQL Exception: "Impersonate Session Security Context" cannot be called in this batch because a simul

    - by kasey
    When opening a connection to SQL Server 2005 from our web app, we occasionally see this error: "Impersonate Session Security Context" cannot be called in this batch because a simultaneous batch has called it. We use MARS and connection pooling. The exception originates from the following piece of code: protected SqlConnection Open() { SqlConnection connection = new SqlConnection(); connection.ConnectionString = m_ConnectionString; if (connection != null) { try { connection.Open(); if (m_ExecuteAsUserName != null) { string sql = Format("EXECUTE AS LOGIN = {0};", m_ExecuteAsUserName); ExecuteCommand(connection, sql); } } catch (Exception exception) { connection.Close(); connection = null; } } return connection; } I found an MS Connect article which suggests that the error is caused when a previous command has not yet terminated before the EXECUTE AS LOGIN command is sent. Yet how can this be if the connection has only just been opened? Could this be something to do with connection pooling interacting strangely with MARS? UPDATE: For the short-term we have implemented a workaround by clearing out the connection pool whenever this happens, to get rid of the bad connection, as it otherwise keeps getting handed back to various users. (Not too bad as this only happens a couple of times a day.) But if anyone has any further ideas, we are still looking out for a real solution...

    Read the article

  • What purpose does “using” serve when used the following way

    - by user287745
    What purpose does “using” serve when used the following way:- ONE EXAMPLE IS THIS, (AN ANSWERER- @richj - USED THIS CODE TO SOLVE A PROBLEM THANKS) private Method(SqlConnection connection) { using (SqlTransaction transaction = connection.BeginTransaction()) { try { // Use the connection here .... transaction.Commit(); } catch { transaction.Rollback(); throw; } } } OTHER EXAMPLE I FOUND WHILE READING ON MICROSOFT SUPPORT SITE public static void ShowSqlException(string connectionString) { string queryString = "EXECUTE NonExistantStoredProcedure"; StringBuilder errorMessages = new StringBuilder(); using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); try { command.Connection.Open(); command.ExecuteNonQuery(); } catch (SqlException ex) { for (int i = 0; i < ex.Errors.Count; i++) { errorMessages.Append("Index #" + i + "\n" + "Message: " + ex.Errors[i].Message + "\n" + "LineNumber: " + ex.Errors[i].LineNumber + "\n" + "Source: " + ex.Errors[i].Source + "\n" + "Procedure: " + ex.Errors[i].Procedure + "\n"); } Console.WriteLine(errorMessages.ToString()); } } } I AM doing at top of page as using system.data.sqlclient etc so why this using thing in middle of code, What if I omit it (I know the code will work) but what functionality will I be losing

    Read the article

  • Conversion failed when converting datetime from character string

    - by salvationishere
    I am developing a C# VS 2008 / SQL Server 2005 Express website application. I have tried some of the fixes for this problem but my call stack differs from others. And these fixes did not fix my problem. What steps can I take to troubleshoot this? Here is my error: System.Data.SqlClient.SqlException was caught Message="Conversion failed when converting datetime from character string." Source=".Net SqlClient Data Provider" ErrorCode=-2146232060 LineNumber=10 Number=241 Procedure="AppendDataCT" Server="\\\\.\\pipe\\772EF469-84F1-43\\tsql\\query" State=1 StackTrace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at ADONET_namespace.ADONET_methods.AppendDataCT(DataTable dt, Dictionary`2 dic) in c:\Documents and Settings\Admin\My Documents\Visual Studio 2008\WebSites\Jerry\App_Code\ADONET methods.cs:line 102 And here is the related code. When I debugged this code, "dic" only looped through the 3 column names, but did not look into row values which are stored in "dt", the Data Table. public static string AppendDataCT(DataTable dt, Dictionary<string, string> dic) { if (dic.Count != 3) throw new ArgumentOutOfRangeException("dic can only have 3 parameters"); string connString = ConfigurationManager.ConnectionStrings["AW3_string"].ConnectionString; string errorMsg; try { using (SqlConnection conn2 = new SqlConnection(connString)) { using (SqlCommand cmd = conn2.CreateCommand()) { cmd.CommandText = "dbo.AppendDataCT"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = conn2; foreach (string s in dic.Keys) { SqlParameter p = cmd.Parameters.AddWithValue(s, dic[s]); p.SqlDbType = SqlDbType.VarChar; } conn2.Open(); cmd.ExecuteNonQuery(); conn2.Close(); errorMsg = "The Person.ContactType table was successfully updated!"; } } }

    Read the article

  • Using block around a static/singleton resource reference

    - by byte
    This is interesting (to me anyway), and I'd like to see if anyone has a good answer and explanation for this behavior. Say you have a singleton database object (or static database object), and you have it stored in a class Foo. public class Foo { public static SqlConnection DBConn = new SqlConnection(ConfigurationManager.ConnectionStrings["BAR"].ConnectionString); } Then, lets say that you are cognizant of the usefulness of calling and disposing your connection (pretend for this example that its a one-time use for purposes of illustration). So you decide to use a 'using' block to take care of the Dispose() call. using (SqlConnection conn = Foo.DBConn) { conn.Open(); using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "SP_YOUR_PROC"; cmd.ExecuteNonQuery(); } conn.Close(); } This fails, with an error stating that the "ConnectionString property is not initialized". It's not an issue with pulling the connection string from the app.config/web.config. When you investigate in a debug session you see that Foo.DBConn is not null, but contains empty properties. Why is this?

    Read the article

  • How to load the SQL data into several ComboBox easily, am i doing the correctly or is there another way

    - by Dominic Deepan.d
    I have a Combobox to fill the data for City, State and PinCode these combobox is dopdown list and the user will pick it. and it loads once the form opens. Here is the CODE: /// CODE TO BRING A DATA FROM SQL INTO THE FORM DROP LIST /// To fill the sates from States Table cn = new SqlConnection(@"Data Source=Nick-PC\SQLEXPRESS;Initial Catalog=AutoDB;Integrated Security=True"); cmd= new SqlCommand("select * from TblState",cn); cn.Open(); SqlDataReader dr; try { dr = cmd.ExecuteReader(); while (dr.Read()) { SelectState.Items.Add(dr["State"].ToString()); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { cn.Close(); } //To fill the Cities from City Table cn1 = new SqlConnection(@"Data Source=Nick-PC\SQLEXPRESS;Initial Catalog=AutoDB;Integrated Security=True"); cmd1 = new SqlCommand("SELECT * FROM TblCity", cn); cn.Open(); SqlDataReader ds; try { ds = cmd1.ExecuteReader(); while (ds.Read()) { SelectCity.Items.Add(ds["City"].ToString()); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { cn1.Close(); } // To fill the Data in the Pincode from the City Table cn2 = new SqlConnection(@"Data Source=Nick-PC\SQLEXPRESS;Initial Catalog=AutoDB;Integrated Security=True"); cmd2 = new SqlCommand("SELECT (Pincode) FROM TblCity ", cn2); cn2.Open(); SqlDataReader dm; try { dm = cmd2.ExecuteReader(); while (dm.Read()) { SelectPinCode.Items.Add(dm["Pincode"].ToString()); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { cn2.Close(); } its kinda Big, i am doing the same steps for all the combo-box, but is there a way i can merge it in a simple way.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >