use session variables as parameters in asp.net - c#

I have to following parameters that are necessary to execute a stored procedure in sql server 2008 r2
da.SelectCommand.Parameters.AddWithValue("#StartDate", sessionStartDate.ToString());
da.SelectCommand.Parameters.AddWithValue("#EndDate", sessionEndDate.ToString());
da.SelectCommand.Parameters.AddWithValue("#PaymentType", payment.ToString());
These are necessary to execute a stored procedure. All of the session variables are passed correctly. However when the gridview renders it shows no data. I know there is data because I can run the stored procedure on SSMS and it runs perfectly with the parameters that are passing to the proc (when I input them).
I am pretty confused at this point so any help would be helpful.
grdDenialDetail.DataSource = ds.Tables["DetailDenial"].DefaultView;
grdDenialDetail.DataBind();
ENTIRE ROUTINE: (maybe this will help)
public void ExecuteDetailReport()
{
string sessionConnection = Session["Company"].ToString();
string sessionStartDate = Session["StartDate"].ToString();
string sessionEndDate = Session["EndDate"].ToString();
string payment = Session["payment"].ToString();
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings[sessionConnection].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("dbo.cusGenDenialReportPivotStylePType", conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
/*da.SelectCommand.Parameters.Add(new SqlParameter("#StartDate", SqlDbType.VarChar, 11)).Value = sessionStartDate.ToString();
da.SelectCommand.Parameters.Add(new SqlParameter("#EndDate", SqlDbType.VarChar, 11)).Value = sessionEndDate.ToString();
da.SelectCommand.Parameters.Add(new SqlParameter("#PaymentType", SqlDbType.VarChar, 100)).Value = payment.ToString();*/
da.SelectCommand.Parameters.AddWithValue("#StartDate", sessionStartDate);
da.SelectCommand.Parameters.AddWithValue("#EndDate", sessionEndDate);
da.SelectCommand.Parameters.AddWithValue("#PaymentType", payment);
lblTest.Visible = true;
lblTest.Text = "You selected " + payment + ".";
DataSet ds = new DataSet();
da.Fill(ds, "DetailDenial");
grdDenialDetail.DataSource = ds.Tables["DetailDenial"].DefaultView;
grdDenialDetail.DataBind();
da.Dispose();
conn.Close();
}

I think your issue is related to the fact that you are using and comparing dates as strings and not dates. Your result set is empty because your query is trying to compare date strings alphabetically instead of chronologically. To refactor your code, I would make sure that you address the following areas:
Setting the session variables
Carefully parse the dates out of your text fields.
DateTime startDate;
if (DateTime.TryParseExact(txtStartDate.Text, "MM/dd/yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out startDate))
{
Session["StartDate"] = startDate;
}
DateTime endDate;
if (DateTime.TryParseExact(txtEndDate.Text, "MM/dd/yyyy",
CultureInfo.CurrentCulture, DateTimeStyles.None, out endDate))
{
Session["EndDate"] = endDate;
}
You may want to handle the case when the TryParseExact methods return false (parse failure).
Retrieving session variables
We set the session variables as DateTime objects, so cast them back upon retrieval:
var sessionStartDate = (DateTime)Session["StartDate"];
var sessionEndDate = (DateTime)Session["EndDate"];
Notice we're still using native .NET types here.
Setting up your query parameters
Use the .Date property of the DateTime struct to drop the time component:
da.SelectCommand.Parameters.AddWithValue("#StartDate", sessionStartDate.Date);
da.SelectCommand.Parameters.AddWithValue("#EndDate", sessionEndDate.Date);
...
And lastly, update your stored procedure so that its parameters are of type date:
CREATE PROCEDURE dbo.cusGenDenialReportPivotStylePType
(
#StartDate date = null,
#EndDate date = null,
...
)
AS
...
SELECT
*
FROM
Somewhere
WHERE
TheDate BETWEEN #StartDate AND #EndDate
Keeping everything in its native data format will make your life a lot easier.

Remove .ToString() calls from your code.

Related

Compare datetime column with datetime variable in asp.net sql where clause

I have a column named compare_time(datatype: DateTime) in database. Its value is inserted as 3/8/2017 12:09:08 AM. Now in c# I want to write a query to compare if this column value is equal to Singapore's current date time.(Only need to compare the date.). Current Singapore date time is get as 08-03-2017 PM 03:35:11.
TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);
DateTime dt = Convert.ToDateTime(singaporetime); //08-03-2017 PM 03:35:11.
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM time_details where compare_time='"+dt+"' ", con1);
Please help to correct the where clause.
The first step is to not compare the dates using automatic string conversion but use a parameter.
Still this is not enough because your DateTime variable contains also the time part as well the database column. So you need to isolate the date part both on the database data and in the variable
DateTime dt = Convert.ToDateTime(singaporetime); //08-03-2017 PM 03:35:11.
SqlDataAdapter adapter = new SqlDataAdapter(#"SELECT * FROM time_details
where Convert('Date',compare_time) = #date", con1);
adapter.SelectCommand.Parameters.Add("#date", SqlDbType.DateTime).Value = dt.Date;
....
In this way you don't let the compiler decide which is the right string 'format' that is correct for Sql Server to understand your query.
Instead you pass the DateTime variable as a Date (using the Today property which doesn't have a meaningful time part) to the database engine that now has all the info to make the correct comparison.
Notice that this approach could not be the most efficient one. That CONVERT inside the WHERE clause could wreak havoc with your indexes. Probably you could use a different approach
string cmdText = #"SELECT * FROM time_details
where compare_time >= #init AND
compare_time < #end";
SqlDataAdapter adapter = new SqlDataAdapter(cmdText, con1);
adapter.SelectCommand.Parameters.Add("#init", SqlDbType.DateTime).Value = dt.Date;
adapter.SelectCommand.Parameters.Add("#end", SqlDbType.DateTime).Value = dt.Date.AddDays(1);

Passing C# datetime value to Oracle DB Query

I have a SQL query that I am passing a C# variable into my Oracle DB.
I am having trouble passing a C# datetime variable, "PROCESS_DATE", into my query in my application. I do not get any records back. If I copy the query into my oracle developer tool, TOAD, it works fine and I get multiple records.
Here is the query I am using in my application:
String SelectAllSQL = "SELECT * FROM REALMS_AUDIT.R2_GROUP_QUERY_RPT WHERE PROCESS_DATE = :pPROCESS_DATE";
I also tried converting the datetime variable into a shortDateString() so it matches the database exactly I then used the TO_DATE function, which I have to use if I query dates directly in TOAD, without any luck. The shortDateString() changes my date into: 1/16/2016, which is what I need, but the OracleDataReader does not like it. Here it the query with the TO_DATE function:
String SelectAllSQL = "SELECT * FROM REALMS_AUDIT.R2_GROUP_QUERY_RPT WHERE PROCESS_DATE = TO_DATE(:pPROCESS_DATE, 'MM-DD-YYYY'";
:pROCESS_DATE is a datetime variable that is passed in.
There must be a breakdown between C# and Oracle in relation to handling a datetime variable. I am using Oracle DataReader to handle the processing of the query.
OracleDataReader dataReader = mDataAccess.SelectSqlRows ( oracleConnection, oracleCommand, sqlCommand, parameters );
while ( dataReader.Read ( ) )
{
groupEntityFacilityRptList.Add ( ReadRecord ( dataReader ) );
}
If I use the TO_DATE function, the application will not step into the while loop. If I use the original query, it does but returns no data.
The datetime variable PROCESSDATE looks like this:
1/16/2016 12:00:00 AM
I notice it has a timestamp on it, so I'm not sure if that is the problem or not.
The data in Oracle is like this:
1/16/2016
Unless I've totally misunderstood your issue, I think you might be making this harder than it needs to be. ODP.net handles all of that dirty work for you. If PROCESS_DATE is an actual DATE datatype in Oracle, then you just need to pass an actual C# DateTime variable to it and let ODP.net do the heavy lifting. There is no need to do conversion of any type, provided you are passing an actual date:
DateTime testDate = new DateTime(2015, 7, 16);
OracleCommand cmd = new OracleCommand(
"SELECT * FROM REALMS_AUDIT.R2_GROUP_QUERY_RPT WHERE PROCESS_DATE = :pPROCESS_DATE",
conn);
cmd.Parameters.Add(new OracleParameter("pPROCESS_DATE", OracleDbType.Date));
cmd.Parameters[0].Value = testDate;
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
object o = reader.IsDBNull(0) ? null : reader.GetValue(0);
}
reader.Close();
If your data in C# is not a date, I'd recommend making it one before even trying:
DateTime testDate;
if (DateTime.TryParse(testDateString, out testDate))
{
// run your query
}
As per my comment, please try below and see this resolves.
TRUNC(TO_DATE(:pPROCESS_DATE,'MM-DD-YYYY HH:MI:SS AM')) if pROCESS_DATE format is 1/16/2016 12:00:00 AM.
TRUNC(TO_DATE(:pPROCESS_DATE,'DD-MM-YYYY HH:MI:SS AM')) if pROCESS_DATE format is 16/1/2016 12:00:00 AM.
First, I learned that my code will not go into the code below unless I actually have records returned to me.
OracleDataReader dataReader = mDataAccess.SelectSqlRows ( oracleConnection, oracleCommand, sqlCommand, parameters );
while ( dataReader.Read ( ) )
{
groupEntityFacilityRptList.Add ( ReadRecord ( dataReader ) );
}
Second, to get ProcessDate to work, I needed to take the string that was coming from my View, convert it to a datetime, and then I formatted it back as a string. It may not be best practices but it worked.
public JsonResult GetGroupReportData ( String reportDate )
{
DateTime processDate = DateTime.Parse ( reportDate );
var monthlyReport = SelectAllGroupRprt (processDate.ToString("MM/dd/yyyy");
return new JsonResult ( )
{
Data = monthly,
MaxJsonLength = Int32.MaxValue
};
}

If Textbox is empty set datetime field to NULL in SQL

Trying to set a datetime field in a SQL table to NULL if the textbox is empty, I can't seem to get this to work.
string EndDate = "";
if (String.IsNullOrEmpty(EndDateTxtBox.Text.Trim()))
{
EndDate = null;
}
else
{
EndDate = EndDateTxtBox.Text;
}
var sql = String.Format(#"UPDATE Test SET StartDate='{0}',
EndDate='{1}' WHERE ID = '{2}'",
StartDateTxtBox.Text, EndDate, id);
When I do this and put in a break point I get this for "var sql':
"UPDATE Test SET StartDate='5/23/2013', EndDate=" WHERE ID = '19'"
I tried removing the ' from the sql string but that didn't work either. Any suggestions?
Edit: I understand the importance of preventing against SQL injection but this a page on my internal web server for my use only and not projected to the public. It's to help me keep track of personal things.
Parameterize.
First, you should move the UI code away from the database code, so that by the time it gets anywhere near the DB we have correctly typed data. For example:
void UpdateDates(int id, DateTime startDate, DateTime? endDate) {...}
and put whatever Parse etc code you want at the caller - not near the db. Now we need to implement that:
void UpdateDates(int id, DateTime startDate, DateTime? endDate) {
//... where-ever cmd comes from, etc
cmd.CommandText =
"update Test set StartDate=#start, EndDate=#end where ID = #id";
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters.AddWithValue("start", startDate);
cmd.Parameters.AddWithValue("end", (object)endDate ?? DBNull.Value);
cmd.ExecuteNonQuery();
// ... cleanup etc
}
Or with a tool like "dapper":
void UpdateDates(int id, DateTime startDate, EndDate? endDate) {
//... where-ever connection comes from, etc
connection.Execute(
"update Test set StartDate=#start, EndDate=#end where ID = #id",
new { id, start = startDate, end = endDate}); // painfully easy
// ... cleanup etc
}
It sounds like the problem is the single quotes. If it is NULL then you shouldn't have them.
Also, you probably want to be using a parameterized query (for safety reasons and pass in the values). In that case the quotes shouldn't be necessary either.
Notwithstanding the issues in your code that are not regarded as SQL best practices within C# code, you have several issues:
You're setting EndDate to a C# null. That is not the same as an SQL NULL, which is denoted as DBNull.Value
You have no regard for the fact that NULL doesn't need quotes in SQL, so your SQL would need to be different anyway in order to work even if you fix #1.
I suggest to write a Stored Procedure; if the end date textbox is null, just don't pass that parameter, and make it have a default value of NULL in the stored proc.
Create Procedure usp_TestDateRange_Update
( #ID int -- or whatever type your ID is
#StartDate DateTime,
#EndDate DateTime = NULL)
As
Update Test
Set StartDate = #StartDate,
EndDate = #EndDate
Where ID = #ID
Something like that. Now what you need to do is make your C# code call the stored procedure and add the parameters to the call from your textboxes.
I think the error is in the string.format line. you cannot include a line break in the string portion. Try one of the following.
var sql = String.Format(
#"UPDATE Test SET StartDate='{0}', EndDate='{1}' WHERE ID = '{2}'",
StartDateTxtBox.Text, EndDate, id);
or,
var sql = String.Format(#"UPDATE Test SET StartDate='{0}', " +
"EndDate='{1}' WHERE ID = '{2}'",
StartDateTxtBox.Text, EndDate, id);
but, as other answers here mention, you should learn about SQL injection and consider another approach.
You can try this way:
string sql = String.Format(#"UPDATE Test SET StartDate={0},
EndDate={1} WHERE ID = {2}",
(StartDateTxtBox.Text.Trim().Equals(string.Empty) ? StartDateTxtBox.Text:"NULL"), EndDate, id);

how to insert a datepicker datetime value into sql database

My SQL Server 2008 database has a table with a column of datatype datetime.
When I try to insert values into the datetime column I am getting error.
Incorrect syntax near '-'
My datetime picker has custom format yyyy-MM-dd e.g (2012-11-01)
Following is the code sample I used to insert datetime.
System.DateTime myDate = default(System.DateTime);
myDate = DateTimePickerPrint.Value;
string query = string.Format("EXEC Save_Quotation_Bookshop '" + txt_QutationNo.Text + "','" + txt_CusCode.Text + "',#" + myDate + "#,");
Please any one have an idea ?
First off: STOP concatenating together your SQL code! This is an invitation for SQL injection attacks, and it's really bad for performance, too - use parametrized queries instead.
If you do - you won't have the problem of datetime/string conversion issues, either.....
Secondly: the "safe" format for a date-only DateTime in SQL Server is YYYYMMDD - without any dashes - only this format guarantees that it'll run on any SQL Server, regardless of your language, regional and dateformat settings.
Thirdly. if you want to execute a stored procedure - I would recommend using this approach:
System.DateTime myDate = default(System.DateTime);
myDate = DateTimePickerPrint.Value;
using (SqlConnection con = new SqlConnection(your-connection-string-here))
using (SqlCommand cmd = new SqlCommand("dbo.Save_Quotation_Bookshop", con))
{
// tell ADO.NET it's a stored procedure (not inline SQL statements)
cmd.CommandType = CommandType.StoredProcedure;
// define parameters
cmd.Parameters.Add("#QuotationNo", SqlDbType.VarChar, 50).Value = txt_QutationNo.Text;
cmd.Parameters.Add("#CustomerCode", SqlDbtype.VarChar, 25).Value = txt_CusCode.Text;
cmd.Parameters.Add("#SaleDate", SqlDbType.DataTime).Value = myDate;
// open connection, execute stored procedure, close connection again
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Don't use EXEC ...... as an inline SQL statement - tell ADO.NET that you're executing a stored procedure, supply the parameters - and you're done!
Wrap the date in single quotes instead of #.
This string concatenation is a SQL injection waiting to happen. Use SqlCommand with parameters instead, then you don't have to worry about string conversion issues
Try this
string query = String.Format("EXEC Save_Quotation_Bookshop '{0}','{1}','{2}'",txt_QutationNo.Text,txt_CusCode.Text, myDate);
OR
string query = string.Format("EXEC Save_Quotation_Bookshop #QutationNo,#CusCode,#myDate");
...
comm.Parameters.AddWithValue("#QutationNo", txt_QutationNo.Text);
comm.Parameters.AddWithValue("#CusCode", txt_CusCode.Text);
comm.Parameters.AddWithValue("#myDate", myDate);

How to run query on date time colomn

Trying to retrieve records by passing date in where condition, i am sending date by using date time picker but at the end reader not showing any record.
I did conversion of date time as Convert(char(10),ext_date,101) still facing the same problem.
string str=#"select * from extra_expense where CONVERT(char(10),ext_date,101) = #date";
sqlcommand = new SqlCommand(str,sqlconnection );
sqlcommand.Parameters.Add("#date", SqlDbType.DateTime).Value = datetimepicker1.value);
datareader = sqlcommand.ExecuteReader();
List<Projects> projects = new List<Projects>();
while (datareader.Read())
{
Projects proj = new Projects();
proj.expenseid = Convert.ToInt32(datareader.GetValue(0));
proj.ProjectDate = Convert.ToDateTime(datareader.GetValue(1));
projects.Add(proj);
}
datareader.Close();
return projects;
You can specify dates as strings in T-SQL, like so:
SELECT MyFields FROM MyTable
WHERE StartDate >= '01-01-00' AND StartDate <= '12-31-00'
You shouldn't cast the field in the table, you should cast the parameter to the correct type. In fact, you are already casting it because the parameter is declared as datetime, but on your query you are forcing ext_date to char(10).
Try this:
string str=#"select * from extra_expense where ext_date = #date";
along with
sqlcommand.Parameters.Add("#date", SqlDbType.DateTime).Value = datetime.Parse( datetimepicker1.value);

Categories

Resources