check the given date is present between fromdate to todate - c#

My dataset format looks like this
EMPNAME FRMDATE TODATE
ANU 01-10-2012 01-20-2012
HARI 01-05-2012 02-05-2012
Now get input through a textbox as 01-17-2012 for a specific employee.
My question is: how to check whether the i/p date is between these two columns (FRMDATE,TODATE) in the dataset?

Try This
DataRow []_dr= ds.Tables[0].Select( inputDate +">= FRMDATE AND "+inputDate +" <= TODATE");

I believe the method below will help you, for extra reading material on comparing dates have a look at these two threads:
Using linq or lambda to compare dates
Check if datetime instance falls in between other two datetime objects
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public bool IsDateInRange(string date, string employeeId)
{
DateTime dateToCompare = DateTime.MinValue;
bool isInRange = false;
if (!String.IsNullOrEmpty(date) && !String.IsNullOrEmpty(employeeId) &&
DateTime.TryParse(date, out dateToCompare))
{
DataTable table = new DataTable();
string connectionString = WebConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "SELECT TOP 1 * FROM EmployeeDates WHERE EMPNAME = #EmpName";
command.Parameters.AddWithValue("#EmpName", employeeId);
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
DateTime fomDate = (DateTime)table.Rows[0]["FRMDATE"];
DateTime toDate = (DateTime)table.Rows[0]["TODATE"];
//DateTime.Ticks converts a date into long
//Now you can simply compare whether the input date falls between the required range
if (dateToCompare.Ticks >= fomDate.Ticks && dateToCompare.Ticks <= toDate.Ticks)
{
isInRange = true;
}
connection.Close();
}
}
}
return isInRange;
}

db.ClubPorsant.Where(p => p.CreateDate>= _FromDate && p.CreateDate<= _ToDate).OrderByDescending(p => p.MablaghVariz).ThenByDescending(p => p.Shomarehesab).ToList();

Related

Call MySql stored procedure which take 2 parameters from asp.net core 2.2 web API controller

What is a proper way of calling a stored procedure with 2 parameters and getting result back which contain 10 columns and 403 records.
Below is the code I have written.
try
{
string startDate = procedureResource.StartDate.ToString("yyyy-MM-dd") + " 00:00:00";
string endDate = procedureResource.EndDate.ToString("yyyy-MM-dd") + " 23:59:59";
var FromDate = new MySqlParameter("#FromDate", startDate);
var ToDate = new MySqlParameter("#ToDate", endDate);
var financial = context.Query<FinancialResource>().FromSql("EXECUTE GetChargesFromToDate #FromDate,#ToDate", FromDate, ToDate).ToList();
return financial;
}
catch(Exception ex) { Console.Write(ex);throw ex; }
and here is the exception
{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''2019-09-28 00:00:00','2019-10-04 23:59:59'' at line 1"}
Try declaring the startDate and endDate variables as DateTime instead of string. You might be sending a date\time format not acceptable by your SQL provider.
You could try something like this (i assume that procedureResource.StartDate/EndDate are of DateTime types):
DatetTime startDate = procedureResource.StartDate.Date;
DateTime endDate = procedureResource.EndDate.Date.Add (new TimeSpan (23, 59, 59));
change EXECUTE to CALL in query
`try
{
var fromDate = resource.StartDate.ToString("yyyy-MM-dd") + " 00:00:00";
var toDate = resource.EndDate.ToString("yyyy-MM-dd") + " 23:59:59";
string connectionstring = "Server=dbwithriderinstance.crefat3b9j9c.ap-southeast-1.rds.amazonaws.com;Database=dborderstage;User=stagging_su_production_s;Password=85s2!892Stfe7";
using (MySqlConnection con = new MySqlConnection(connectionstring))
{
using (MySqlCommand cmd = new MySqlCommand("GetChargesFromToDateV2", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FromDate", fromDate);
cmd.Parameters.AddWithValue("#ToDate", toDate);
using (MySqlDataAdapter dbr = new MySqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
dbr.Fill(dt);
return dt;
}
}
}
}
catch (Exception ex) { Console.Write(ex); throw ex; }
}`

Comparing SQL Server DATETIME with DateTime.NOW in C# / ASP.NET

How do I compare a SQL Server DATETIME with the DateTime.Now value? As you can see I assigned it to a Session and tried comparing it with DateTime.Now.
string timestamp = #"SELECT sr.*, ud.* FROM SuspensionRecord sr, UserData ud WHERE sr.User_ID=#User_ID AND ud.User_ID=#User_ID";
using (SqlCommand cmd2 = new SqlCommand(timestamp, con))
{
cmd2.Parameters.AddWithValue("#User_ID", Session["UserID"].ToString());
using (SqlDataReader dr = cmd2.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
Session["suspensiondate"] = dr["End_Date_Suspension"].ToString();
}
if (Convert.ToDateTime(Session["supensiondate"]) >= DateTime.Now.Date)
{
lblMessage.Text = "The account's status is suspended.";
lblMessage.Visible = true;
}
}
}
}
You should pass in the date and do the comparison in the query instead of in c#. That is one less step. If you do want to do it in c# then use the appropriate types, do not convert the DateTime to a string and then convert it back again.
There is no need for the join (2nd table) in your query
You do not have to use a DataReader for this, you can use ExecuteScalar which returns 1 value instead.
Use Add so you can specify the correct schema types with SqlDbType and not AddWithValue
string timestamp = #"SELECT 1 FROM SuspensionRecord sr WHERE sr.User_ID = #User_ID AND supensiondate > #now";
using (SqlCommand cmd2 = new SqlCommand(timestamp, con))
{
cmd2.Parameters.Add("#User_ID", SqlDbType.Int).Value = Session["UserID"]; // do not convert to string
cmd2.Parameters.Add("#now", SqlDbType.DateTime).Value = DateTime.Now.Date;
var result = cmd2.ExecuteScalar();
if(result != null) // if null then there were no records so account is not suspended
{
lblMessage.Text = "The account's status is suspended.";
lblMessage.Visible = true;
}
}
First, your SQL is terrible.
You are returning way too much data, and you are using an implicit join (when explicit joins are a part of ANSI-SQL for almost 30 years now!)
Second, Can we stop using AddWithValue() already?
Instead of all this code you can do the entire test on SQL and return a single value:
string sql =
#"SELECT CASE WHEN EXISTS
(
SELECT 1
FROM SuspensionRecord
WHERE User_ID = #User_ID
AND End_Date_Suspension >= CAST(GETDATE() AS DATE)
) THEN 1 ELSE 0 END";
Then you can use ExecuteScalar instead of ExecuteReader, and you don't need to loop through all the irrelevant data:
using (SqlCommand cmd2 = new SqlCommand(timestamp, con))
{
cmd2.Parameters.Add("#User_ID", SqlDbType.Int).Value = Session["UserID"];
if ((int)cmd2.ExecuteScalar() == 1)
{
lblMessage.Text = "The account's status is suspended.";
lblMessage.Visible = true;
}
}

Sql DataReader Has Rows but Returns With Empty data

I am using a query to select data from sql database. It has rows but data raader.Read() function returns false and rows are empty as I have checked in debugging
Code that i have been using is
public void getSale()
{
DB db = new DB();
try
{
db.cmd.CommandText = "select * from Sale where date is not null and (date between '"+StartDate+"' and '"+EndDate+"') order by date";
db.cmd.Connection = db.con;
db.con.Open();
if(db.con.State == System.Data.ConnectionState.Open)
{
db.dataReader = db.cmd.ExecuteReader();
if(db.dataReader.HasRows)
{
while(db.dataReader.Read())
{
SaleModel sm = new SaleModel();
sm.SaleId = long.Parse(db.dataReader["Id"].ToString());
sm.UserName = db.dataReader["UserName"].ToString();
sm.ItemsQuantity = int.Parse(db.dataReader["ItemsQuantity"].ToString());
sm.TotalAmount = double.Parse(db.dataReader["TotalAmount"].ToString());
sm.SubTotal = double.Parse(db.dataReader["SubTotal"].ToString());
sm.Discount = double.Parse(db.dataReader["Discount"].ToString());
sm.Completed = bool.Parse(db.dataReader["Completed"].ToString());
sm.Date = DateTime.Parse(db.dataReader["Date"].ToString());
sm.CustomerPhone = long.Parse(db.dataReader["CustomerPhone"].ToString());
SalesList.Add(sm);
}
db.con.Close();
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
}
}
And When I tested this query on Query editor in Visual studio rows were returned
If Anyone can help?
Why you concatenate strings to build your sql query? NEVER do that. It is a source for sql-injection and can cause issues like this. Instead use parameterized queries.
Also don't use SqlConnection wrappers like your DB class. That can cause several other issues. Instead create, open, close and dispose them where you need them, best by using the using-statament. The connection-pooling will manage the rest for you.
public List<SaleModel> GetSale(DateTime startDate, DateTime endDate)
{
string sql = #"select * from Sale
where date is not null
and date between #StartDate and #EndDate
order by date";
var salesList = new List<SaleModel>();
try
{
using (var con = new SqlConnection("insert your connection string"))
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = endDate;
con.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
SaleModel sm = new SaleModel();
sm.SaleId = long.Parse(reader["Id"].ToString());
sm.UserName = reader["UserName"].ToString();
sm.ItemsQuantity = int.Parse(reader["ItemsQuantity"].ToString());
sm.TotalAmount = double.Parse(reader["TotalAmount"].ToString());
sm.SubTotal = double.Parse(reader["SubTotal"].ToString());
sm.Discount = double.Parse(reader["Discount"].ToString());
sm.Completed = bool.Parse(reader["Completed"].ToString());
sm.Date = DateTime.Parse(reader["Date"].ToString());
sm.CustomerPhone = long.Parse(reader["CustomerPhone"].ToString());
salesList.Add(sm);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
}
return salesList;
}
I'm pretty sure that this works(f.e. can be a localization issue).
Side-note: a method GetSale should return a List<SaleModel> but not fill one. You should also pass the parameters as DateTime to the method. I've changed it in my code sample.
This is a much better way to structure you code, and there's a good chance it will fix your issue, too:
//accept the date values as parameter arguments, return the result.
// Do NOT mess about with variables at the global or class scope.
public IEnumerable<SalesModel> getSale(DateTime StartDate, DateTime EndDate)
{
string sql = "select * from Sale where date is not null and (date between #StartDate and #EndDate) order by date";
//DON'T abstract SqlCommand/SqlConnection. DO abstract your connection string.
//Also, don't bother with the try/catch at this level. You can't really do anything with it here, so worry about the exception in calling code.
using (var cn = new SqlConnection(DB.ConnectionString))
using (var cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = StartDate
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = EndDate
cn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
var sm = new SaleModel();
//If you have good schema design, these values are **already** in the correct type.
// The old code forces an expensive conversion to string, following by an expensive parse back to the type it already had.
// We can do MUCH better.
sm.SaleId = (long)rdr["Id"];
//but it is okay for types that are *already* strings
sm.UserName = rdr["UserName"].ToString();
sm.ItemsQuantity = (int)rdr["ItemsQuantity"];
sm.TotalAmount = (double)rdr["TotalAmount"]);
sm.SubTotal = (double)rdr["SubTotal"];
sm.Discount = (double)rdr["Discount"];
sm.Completed = (bool)rdr["Completed"];
sm.Date = (DateTime)rdr["Date"];
sm.CustomerPhone = (long).rdr["CustomerPhone"];
yield return sm;
}
}
}
}
Here it is again without all the extra comments. The point here is this is still less code than the original that used string concatenation, and it took less than 10 minutes to write. Good code doesn't necessarily take longer.
public IEnumerable<SalesModel> getSale(DateTime StartDate, DateTime EndDate)
{
string sql = "select * from Sale where date is not null and (date between #StartDate and #EndDate) order by date";
using (var cn = new SqlConnection(DB.ConnectionString))
using (var cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = StartDate
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = EndDate
cn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
var sm = new SaleModel();
sm.SaleId = (long)rdr["Id"];
sm.UserName = rdr["UserName"].ToString();
sm.ItemsQuantity = (int)rdr["ItemsQuantity"];
sm.TotalAmount = (double)rdr["TotalAmount"]);
sm.SubTotal = (double)rdr["SubTotal"];
sm.Discount = (double)rdr["Discount"];
sm.Completed = (bool)rdr["Completed"];
sm.Date = (DateTime)rdr["Date"];
sm.CustomerPhone = (long).rdr["CustomerPhone"];
yield return sm;
}
}
}
}
Note that I return an IEnumerable rather than a List. If you really need a List (tip: you probably don't, and sticking with IEnumerable is faster), you can just call ToList() on the result.
don't see any issue except that you are using date which is a reserve word and not your actual column name. Change your query to be
db.cmd.CommandText = "select * from Sale where [date] is not null and ([date] between '"+StartDate+"' and '"+EndDate+"') order by [date]";

How to store date as 1 and month as 1 to mysql database by using c#

How to store date as "1" and month as "1" to mysql database by using c#,(for example 1-1-1987),i can get year from the variable frdt,so i need to store for example 1-1-frdt.
string frdt = drow1["release_year"].ToString();
i would pass it into a DateTime object and insert that one into your database
string frdt = drow1["release_year"].ToString();
DateTime Result = new DateTime(int.Parse(frdt), 1, 1);
string Command = "INSERT INTO TABLENAME (COLUMNNAME) VALUES (#DATEVALUE);"; // TODO
using (MySqlConnection mConnection = new MySqlConnection(ConnectionString))
{
mConnection.Open();
using (MySqlCommand myCmd = new MySqlCommand(Command, mConnection))
{
myCmd.Parameters.AddWithValue("#DATEVALUE", Result);
int RowsAffected = myCmd.ExecuteNonQuery();
}
}
If you're storing a date then it should be stored as a binary date, not as text. It's hard to tell whether you're doing that or not but you absolutely should. The fact that you're storing a year, which is a number, in a string variable is not encouraging. You should be storing the year in an int and then creating a DateTime like so:
var myDate = new DateTime(year, 1, 1);
where year is the int containing the year. You then save that to your database as you would any other data, using a parameter one would hope, e.g.
var command = new MySqlCommand("UPDATE MyTable SET MyDate = #MyDate WHERE ID = #ID", connection);
command.Parameters.AddWithValue("#MyDate", myDate);

How to convert a string Date from database into Integer?

I have a string date in database. I did like below mentioned format but it shows error like
input string was not in a correct format
But when I referred with internet this method is correct but it does not work for me. Let me know the reason?
string str1 = "select todate from Employee where EmpCode='" + code + "'";
SqlDataReader dr1 = conn.query(str1);
if (dr1.Read())
{
string todate1 = dr1[0].ToString();
int todate2 =Convert.ToInt32(todate1);
}
It sounds like you should be using a DateTime column in the database, at which point there's no need for integers or strings:
var today = DateTime.Today; // Or maybe use DateTime.Now
// Use parameterized SQL rather than string concatenations
string sql = "select todate from Employee where EmpCode=#EmpCode";
using (var conn = new SqlConnection(...))
{
conn.Open();
using (var command = new SqlCommand(sql, conn))
{
command.Parameters.Add("#EmpCode", SqlDbType.VarChar).Value = code;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
DateTime date = reader.GetDateTime(0);
if (today > date)
{
// Do something
}
}
}
}
}
If your date really is being stored as a string and you can't change that (and if you can, then definitely do so), you can use DateTime.ParseExact instead:
// Other code as before
while (reader.Read())
{
DateTime date = DateTime.ParseExact(reader.GetString(0),
"yyyy-MM-dd", // Or whatever the format is
CultureInfo.InvariantCulture);
if (today > date)
{
// Do something
}
}
Note that in both cases, this uses the system local time zone. You may want to consider storing all values in UTC, and performing all calculations that was as well - in which case you can use DateTime.UtcNow.

Categories