I have below code to get data from database. It hosted in WCF Service (IIS Server).
public DataTable GetDocument(int DocumentID)
{
SqlCommand sqlCommand = null;
SqlConnection sqlConnection = null;
SqlDataAdapter sqlDataAdapter = null;
DataTable dataTable = null;
try
{
sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = "Connection_String";
sqlCommand = new SqlCommand();
sqlCommand.CommandText = "dbo.[Get_Document]";
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Connection = sqlConnection;
sqlCommand.Parameters.Add(new SqlParameter("#document_id", SqlDbType.BigInt, 8, ParameterDirection.Input, true, 19, 0, "", DataRowVersion.Proposed, DocumentID));
sqlConnection.Open();
sqlDataAdapter = new SqlDataAdapter(sqlCommand);
dataTable = new DataTable("Document");
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
catch (Exception ex)
{
ErrorLog.LogError(ex, "DocumentID = " + DocumentID);
}
finally
{
if (sqlConnection != null)
{
if(sqlConnection.State != ConnectionState.Closed)
sqlConnection.Close();
sqlConnection.Dispose();
sqlConnection = null;
}
if (sqlCommand != null)
{
sqlCommand.Dispose();
sqlCommand = null;
}
if (dataTable != null)
{
dataTable.Dispose();
dataTable = null;
}
if (sqlDataAdapter != null)
{
sqlDataAdapter.Dispose();
sqlDataAdapter = null;
}
}
return null;
}
It is working correctly but some time randomly we got the below timeout exception.
PARAMETER : DocumentID = 987456
EXCEPTION
Error Message: Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Error Source: .Net SqlClient Data Provider
Error Stack Trace: at System.Data.SqlClient.SqlConnection.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.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at 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)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
at DAL.DocumentController.GetDocument(int DocumentID)
TargetSite : Void OnError(System.Data.SqlClient.SqlException, Boolean, System.Action`1[System.Action])
INNER EXCEPTION
Error Message: The wait operation timed out
BASE EXCEPTION
Error Message: The wait operation timed out
When timeout exception is occurred at that time we logged exception with appropriate stored procedure's parameter. later on when we investigating the exception logs at that time we perform same operation with same parameter but at that time system behaves as expected (not able to replicate exception even with same parameter).
As far as I know many causes involved for timeout exception. We have already set enough timeout so we don't want to increase timeout in our application.
We just want to know the reason of timeout exception why it is occurred in particular time frame (e.g. It is because of any deadlock, connectivity issue etc.) and logged that reason so later on we can investigate in correct direction.
Is there any way to know the reason of timeout exception?
Thanks.
I think you are right. The timeout exception might due to the client request amount overtake the maximum server load or resource deadlock. Whether WCF or SQL server there is a concurrent request limitation. Here is a template to configure this.
<behaviors>
<serviceBehaviors>
<behavior>
<serviceThrottling maxConcurrentCalls="500" maxConcurrentSessions="10000" maxConcurrentInstances="100" />
</behavior>
</serviceBehaviors>
The instancing mode and the concurrency mode have an impact on the way of processing the client's request.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/sessions-instancing-and-concurrency
https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.servicebehaviorattribute.concurrencymode?view=netframework-4.8
The combination of instancing mode and concurrency mode might cause a deadlock so that results in the timeout exception.
Finally, the database connection string had better a separate username/password, because the process of IIS hosting the WCF application, it will be replaced with the IIS application pool identity.
Related
This question already has an answer here:
Error With SqlCommand not accepting Parameter Arguments
(1 answer)
Closed 6 months ago.
The following image is the code used to call MS=SQL stored procedure, as you can see, I am attempting to provide parameters in the request
using (SqlConnection connection = new SqlConnection(sqlAuth)) {
// Open database connectionS
connection.Open();
// Call upon stored procedure
SqlCommand cmd = new SqlCommand("InsertSystem", connection);
cmd.Parameters.Add("#ObjectID", SqlDbType.VarChar).Value = Request.Form["objectid"].ToString();
cmd.Parameters.Add("#SystemID", SqlDbType.VarChar).Value = Request.Form["systemid"].ToString();
cmd.Parameters.Add("#ItemID", SqlDbType.Int).Value = Request.Form["itemid"].ToString();
int records = cmd.ExecuteNonQuery();
// Close database connection
connection.Close();
}
message = "Record Saved<br /><br />";
The error which is returned from this is as follows:
System.Data.SqlClient.SqlException
HResult=0x80131904
Message=Procedure or function 'InsertSystem' expects parameter '#SystemID', which was not supplied.
Source=Core .Net SqlClient Data Provider
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
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.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
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, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at ServiceObjectsWebApp.Pages.ObjectInsertModel.OnPost() in C:\Users\rmcd\Desktop\ServiceObecjts\ServiceObjectsWebApp\Pages\ObjectInsert.cshtml.cs:line 46
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory.VoidHandlerMethod.Execute(Object receiver, Object[] arguments)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.<InvokeHandlerMethodAsync>d__29.MoveNext()
This exception was originally thrown at this call stack:
[External Code]
ServiceObjectsWebApp.Pages.ObjectInsertModel.OnPost() in ObjectInsert.cshtml.cs
[External Code]
You're calling a stored procedure so you need to tell it that:
cmd.CommandType = CommandType.StoredProcedure;
I have a simple method to execute SQL NON-QUERY statement. This works fine without any issue but when there is load or 20 thread simultaneously calling this method than sometime I get "Collection was modified; enumeration operation might no execute". Surprisingly I do not have any enumeration operation in this method.
Method:
OpenConnection();
using (SqlCommand cmd = new SqlCommand(SQLQuery, Connection))
{
cmd.CommandType = CommandType.Text;
if (QueryParam.Count() > 0)
cmd.Parameters.AddRange(QueryParam.ToArray());
SqlParameter scopeParam = cmd.Parameters.AddWithValue("#ID", 0);
scopeParam.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
uKey = (int)cmd.Parameters["#ID"].Value;
cmd.Parameters.Clear();
}
CloseConnection()
return uKey;
Exception:
Exception Found: Collection was modified; enumeration operation might not execute.
Full Exception: System.InvalidOperationException: Collection was modified; enumeration operation might not execute.
at System.Data.SqlClient.TdsParser.TdsExecuteRPC(SqlCommand cmd, _SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc, Boolean sync, TaskCompletionSource`1 completion, Int32 startRpc, Int32 startParam)
at 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)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
Just to mention I am using .Net 4.0 and SQL Server.
Any help would be highly appreciated.
The code shown by itself should be fine; the symptoms here suggest that another thread is touching the same Connection instance at the same time, so: don't do that. Connections are not thread-safe. The key give-aways here are shown in bold:
This works fine without any issue [presumably meaning by itself] but when there is load or 20 thread simultaneously calling this method than sometime I get "Collection was modified; enumeration operation might no execute".
Something that happens only sometimes and only when under concurrent load: is usually concurrency. Recommendation: scope the connection - either per thread, or even per method, i.e.
using (var conn = CreateOpenConnection())
using (var cmd = new SqlCommand(SQLQuery, conn))
{
// ...
}
MS sql 2014 backend (on same machine) - Executereader times out (native error code: 258) # second executereader() in same connection. Why is this so?
(No big data amount involved, cmd strings involved are correct)
Note: it doesn't matter if all SELECT goes into separate connection the second always times out. It also doesn't matter if I'd use DataAdapter to catch data.... times out... see below, thanks for the ideas:
using (SqlConnection c = new SqlConnection(cString))
{
c.Open();
using (SqlCommand cmd = new SqlCommand(querystringPO, c))
{
cmd.Parameters.AddWithValue("#paramRecipe", productionOrderNo);
using (SqlDataReader rd = cmd.ExecuteReader())
{
dtRecipe = new DataTable();
dtRecipe.Load(rd);
rd.Close();
}
}
if (dtRecipe.Rows.Count > 0)
{
string querystringOpDefs = "SELECT * FROM ReferencedFieldsView_OperationDefinition WHERE RecipeID=#paramOpDef";
using (SqlCommand cmd1 = new SqlCommand(querystringOpDefs, c))
{
cmd1.Parameters.AddWithValue("#paramOpDef", dtRecipe.Rows[0].Field<int>("ID"));
using (SqlDataReader rd = cmd1.ExecuteReader())
{
dtOpDefs = new DataTable();
dtOpDefs.Load(rd);
rd.Close();
}
}
string querystringBOMItems = "SELECT * FROM ReferencedFieldsView_BomItem WHERE RecipeID=#paramBOMItem";
using (SqlCommand cmd2 = new SqlCommand(querystringBOMItems, c))
{
cmd2.Parameters.AddWithValue("#paramBOMItem", dtRecipe.Rows[0].Field<int>("ID"));
using (SqlDataReader rd = cmd2.ExecuteReader())
{
dtBOMItems = new DataTable();
dtBOMItems.Load(rd);
}
}
}
}
Ex below:
Exception: System.InvalidOperationException: Server operation encountered an exception ---> System.Data.SqlClient.SqlException: Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception: The wait operation timed out
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlConnection.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.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at 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)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader()
Fact of the matter is that using SQL 2K12 the above snippet all worked (same database same etc)
However as sb suggested instead of selecting all fields (*), when explicitly added the req'd fields it started to work.
I am trying to execute a stored procedure (query) from the ASP Web API. I have developed it (command timeout is 300 seconds).
At the beginning, calling the stored procedure from Web API is very fast, but after a few days when calling the same WEB API, it gives me time out error (shown below).
Meanwhile if I try to execute the same stored procedure with the same parameter even at the same time directly from SQL Server Management Studio, it is executed within seconds.
The code :
public List<ScheduledTitles> GetScheduledTitles(CriteriaFields _criteria)
{
try
{
System.Data.DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
using (SqlConnection con = new SqlConnection(_strDBConnection))
{
con.Open();
SqlCommand comm = new SqlCommand();
comm.Connection = con;
comm.CommandText = "spQuery_1";
comm.Parameters.Add(new SqlParameter() { ParameterName = "Product_Line_ID", SqlDbType = SqlDbType.Int, Value = _criteria.ProductLineID == null ? (object)System.DBNull.Value : _criteria.ProductLineID });
comm.CommandType = CommandType.StoredProcedure;
da.SelectCommand = comm;
comm.CommandTimeout = 300;
da.Fill(ds);
}
.
.
.
return scheduledTitlesS.ToList<ScheduledTitles>();
}
catch (Exception exc)
{
throw exc;
}
}
The error message:
The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
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, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)
at HERS_SearchQuery.Data.DataAccess.SQLServer.HERSScheduleRepository.GetScheduledTitles(CriteriaFields _criteria) in C:\Users\nah\Documents\Visual Studio 2010\Projects\HERS_SchedulerSearch\HERS_SearchQuery.Data\DataAccess\SQLServer
I had a similar issue a couple of years ago, I solved it by using the option
WITH RECOMPILE
in the strored procedure. It happened that SQL SERVER was caching an execution plan that was not efficient for all parameters.
Of course I don't know whether this can solve your problem, but I think it's worth to try.
I have created a website .It is a logon page and it works fine on Debug,But when I deploy it on server I got an strange error.When I click on login I got this error:
Invalid column name 'aa'.
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: Invalid column name 'aa'.
Source Error:
Line 33:
Line 34: DataSet ds = new DataSet();
Line 35: dataAdapter.Fill(ds);
Line 36: DataTable dt = ds.Tables[0];
Line 37:
Source File: c:\inetpub\wwwroot\login.aspx.cs Line: 35
Stack Trace:
[SqlException (0x80131904): Invalid column name 'aa'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +388
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +717
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4515
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +61
System.Data.SqlClient.SqlDataReader.get_MetaData() +134
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +6557689
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +6560327
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +586
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +104
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +288
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +171
System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +15
System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +325
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +420
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) +275
login.ValidateUser(Object sender, EventArgs e) in c:\inetpub\wwwroot\login.aspx.cs:35
System.Web.UI.WebControls.Login.AttemptLogin() +160
System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +93
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +84
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.342
As I expecte it must saty wrong login but it trows this error.here is my code:
protected void ValidateUser(object sender, EventArgs e)
{
int userId = 0;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT [OBJECTID] from dbo.OWNER where [owner_id]=" + Login1.UserName;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(query, con))
{
con.Open();
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
DataTable dt = ds.Tables[0];
userId = Convert.ToInt32(dt.Rows[0][0]);
if (userId.ToString() != Login1.Password)
{
userId = -1;
}
con.Close();
}
switch (userId)
{
case -1:
Login1.FailureText = "نام کاربری یا کلمه عبور صحیح نیست";
break;
case 0:
Login1.FailureText = "نام کاربری یا کلمه عبور صحیح نیست";
break;
case -2:
//Login1.FailureText = "Account has not been activated.";
break;
default:
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
break;
}
}
and here is database connection in web.config file:
<connectionStrings>
<add name="constr" connectionString="Data Source=XXX.xxx.xxx.xxx\sqlexpress;Initial Catalog=land_gis;Persist Security Info=True;User ID=Land;Password=password"/>
Do you think problem is with database connection?I can run on my debug with this connection without problem but when I copy them to wwwroot it makes probelm.Do I should add database to IIS or sth like that?
thank you very much for your helps
Unless Login1.UserName is a number, this isn't going to work in dev either. Your query is not parameterized properly, and you don't have quotes, so the query will read SELECT [OBJECTID] from dbo.OWNER where [owner_id]=aa (assuming you're typing "aa" in the username box).
And if you attempt to run this query, it will think that aa is a column name rather than a real value.
Parameterize your query, and you should be fine.
EDIT
Somehow I'm not finding a good, short, simple tutorial for using parameterized queries in C#. Here it is in a nutshell:
When you write your query, you put variables in as placeholders for values you'll pass in later. When you execute the command in C#, you populate those variables. This makes your code safe against SQL injection (someone executing unwanted script by injecting SQL statements into your query), and it also means you don't have to worry about all the quotation marks.
In C#, using a DataSet the way you are, it looks something like:
using (var con = new SqlConnection(constr))
{
con.Open();
string query = "SELECT [OBJECTID] from dbo.OWNER where [owner_id] = #OwnerID";
using (var com = new SqlCommand(query, con))
{
com.Parameters.AddWithValue("#OwnerID", Login1.UserName);
using (var da = new SqlDataAdapter(com))
{
var ds = new DataSet();
da.Fill(ds);
Console.WriteLine(ds.Tables[0].Rows[0][0]);
}
}
}
There are dozens of ways of writing the same code (different constructors, different ways of retrieving data, etc., but the important thing is to never allow user input to go directly into a query's text, but rather attach parameters to the query instead.
Your connection seems to be working fine since it says Invalid column name 'aa' in stack trace. But your query doesn't have this column. It only has OBJECTID.
This could happen if you add column aa in your query for some reason and deployed the code with that error.