ASP.NET Comparing data from Database - c#

I'm currently working on a project which needs to check for the day and time, then compare these with values in my database.
This needs to be done for an Live Chat, while we have opened.
I'm new to ASP.Net and this is giving me an headache.
I Have a table which contains these Rows:
- weekday
- starttime
- endtime
In my Controller for the Chat I have tried this so far
private Model1Container db = new Model1Container();
public ActionResult Index(Openinghours openinghours)
{
ViewBag.Opening = db.OpeninghoursSatz.ToList();
string CurrentDay = DateTime.Now.DayOfWeek.ToString();
string CurrentTime = DateTime.Now.TimeOfDay.ToString();
bool IsWeekDay= db.OpeninghoursSatz.Where(i => i.weekday == CurrentDay).Any();
var Starttime = db.OpeninghoursSatz.Find(CurrentDay);
Debug.Write("!!++" + Starttime);
My exact Problem is to compare the time with the two rows from my table.
I thought about putting the values in a variable and then compare them, but there must be a cleaner way for this.
I hope I was able to point out what my problem is, if not please ask.
With regards,
Nico
EDIT:
Maybe I should say that the database holds the hour it opens and the hour it closes (e.g. 9 and 17). I need to check if the current time is between these two.

int getStartHour = DateTime.Now.Hour;
int weekDay= (int)DateTime.Now.DayOfWeek;
bool value = db.OpeninghoursSatz.Where(m => getStartHour >= m.Starttime && getStartHour <= m.EndTime && m.weekday == weekDay).Any()
/// if everything is in int. or if in string
string getStartHour = DateTime.Now.Hour.ToString();
string weekDay= DateTime.Now.DayOfWeek.ToString();
bool value = db.OpeninghoursSatz.Where(m => getStartHour >= m.Starttime && getStartHour <= m.EndTime && m.weekday == weekDay).Any();
But in this case for Thursday , we will get Thursday, but in Int we will get 4.

The line looks odd to me:
var Starttime = db.OpeninghoursSatz.Find(CurrentDay);
I guess you should change it to something like:
if (IsWeekDay){
var Starttime = db.OpeninghoursSatz.Where(i => i.weekday == CurrentDay).First().StartTime;
Debug.Write("!!++" + Starttime);
}

Related

How to compare the database field and datetime in asp.net

NET and I working on a program where I take some data from database and try to compare with the DateTime field.
For Example I have certain documents in the SEIBEL database and I want expiration date of those documents and compare the with current date and time and fire message accordingly. But somehow I an unable to compare them.
This is the sql query in asp.net that I am running
private static readonly string GET_PROVIDER_DOCUMENTS = #"
select sc.row_id,
doc.created as created_date,
doc.attrib_04 as document_type,
doc.attrib_47 as exipration_date,
att.row_id as document_row_id,
att.file_name || '.' || att.file_ext as file_name
from siebel.s_org_ext sc
join siebel.s_org_ext_xm doc
on doc.par_row_id = sc.row_id
and doc.type = 'SCLicenseInfo'
and doc.attrib_35 = 'Expiration Date'
and doc.attrib_04 in ('Certificate of Insurance', 'Master Service Agreement')
left join siebel.s_accnt_att att on att.comments = doc.row_id
where sc.row_id = :sc_row_id
";
and this where I trying to get expiration date from database
ExpirationDate = ConvertExpirationDate(dr["exipration_date"].ToString()),
If anybody has any idea about it it would great. Thanks in advance
Have you looked at the TryParse method on a DateTime object?
https://msdn.microsoft.com/en-us/library/system.datetime.tryparse(v=vs.110).aspx
May be suitable for your needs though I believe it will depend on the format your date is stored in.
Assuming you are successfully getting the datetime from the datebase and storing it as a string called ExpirationDate:
DateTime date1 = Convert.ToDateTime(ExpirationDate);
Datetime date2 = new Datetime(---)//desired date to compare with.
if(DateTime.Compare(date1,date2)==0)
{
// They're equal.
}
else
{
// Not equal.
}
Converting:
https://msdn.microsoft.com/en-us/library/system.convert.todatetime(v=vs.110).aspx
Comparing:
https://msdn.microsoft.com/en-us/library/system.datetime.compare(v=vs.110).aspx
Alternatively you could compare the day / month / year components of the date like this :
DateTime today = DateTime.Today;
if(ExpirationDate.Year == today.Year &&
ExpirationDate.Month = today.Month && ExpirationDate.Day = today.Day )

Check if month is in interval in c# (asp.net)

I am developping an application where a user can download various reports. There is one report per month and each report is called "YYYY-MM.txt". An user can only download files of the last 18 months.
I have written a function that takes in parameter a list of filespath and then downloading them to the client. My problem is how to add files in this list, basically how can I check if a file is in the last 18 months, knowing that I have his year and month, and the current year and month.
This is what I have :
//just for test, supposed that theses values were extracted from the report of august 2014.
string fileYear = "2014";
string fileMonth = "08";
string currentYear = DateTime.Now.Year.ToString();
string currentMonth = DateTime.Now.Month.ToString();
How can I compare fileYear and fileMonth with currentYear and currentMonth to know if the report correspond to a month of the last 18.
Thanks in advance for your help
Here's how I would do it.
int fileYear = int.Parse(fileName.Substring(0,4));
int fileMonth = int.Parse(fileName.Substring(5,2));
DateTime oldestDate = DateTime.Now.AddMonths(-18);
int oldestYear = oldestDate.Year;
int oldestMonth = oldestDate.Month;
if(fileYear > oldestYear || (fileYear == oldestYear && fileMonth >= oldestMonth))
{
// This file is within 18 months.
}
This means that if today is 12-31-2014 it will include files back to 2013-06.txt. If needed you can also put an upper bounds check in case you could have files with future dates.
EDIT
The other alternative is to create a DateTime from the file name to compare. Here's how I would do that to ensure I'm comparing the last day of the file's month
int fileYear = int.Parse(fileName.Substring(0,4));
int fileMonth = int.Parse(fileName.Substring(5,2));
DateTime fileDate = new DateTime(fileYear, fileMonth, 1).AddMonths(1).AddDays(-1);
DateTime oldestDate = DateTime.Now.AddMonths(-18);
if(fileDate.Date >= oldestDate.Date)
{
// This file is within 18 months.
}
You could do something like this:
https://dotnetfiddle.net/VORvZr
using System;
public class Program
{
public static void Main()
{
DateTime fileDate = new DateTime(2013, 5, 1);
DateTime fileDateNewer = new DateTime(2014, 1, 1);
GetMonthDifference(fileDate);
GetMonthDifference(fileDateNewer);
}
public static void GetMonthDifference(DateTime fileDate)
{
DateTime currentDate = DateTime.Now;
DateTime eighteenMonthsAgo = currentDate.AddMonths(-18);
if (eighteenMonthsAgo > fileDate)
Console.WriteLine("{0} is greater than or equal to 18 months ago", fileDate);
else
Console.WriteLine("{0} is less than 18 months ago", fileDate);
}
}
Note that if you can, you always want to try to work with objects that most closely represent your data. E.g. if working with years you should work with a numeric type rather than string type. In this case, working with dates.
EDIT:
as comments posted on the other answers pointed out, you would have some room for error depending on the day the file was uploaded/created if it's right around the 18 month mark. Something you could potentially do is get the actual file creation date (assuming you are the system creating the file and the date of the file creation coincides with the month the data belongs. You can get a files creation date as such:
string fullFilePathAndName = #""; // wherever your file is located
FileInfo fi = new FileInfo(fullFilePathAndName);
DateTime fileCreateDate = fi.CreationTime

Compare dates with deferent formats framework 4.5 c# web forms

A part of my project is to write a function that will generate an increasing number for every day for every record I have to store in a database table. My problem is that when I try to compare the DateTime.Now with the column I have in my database, I try to compare Datetime with Date so I never have equality on the days. My code explains better than me my issue:
var r = (from i in context.vehicles
where i.InsertionDate == DateTime.Now
select i); // In this query i cant compare the two dates. The one is datetime and the other is date format
int result3 = 0;
if (r.Any())
{
var result = r.OrderByDescending(ii => ii.IncreasingNumberOfTheDay).FirstOrDefault();
int myint = Convert.ToInt32(result.IncreasingNumberOfTheDay);
result3 = myint + 1;
}
else
result3 = 1;
I suspect you just want:
DateTime today = DateTime.Today; // Just fetch the date part.
var query = context.vehicles.Where(v => v.InsertionDate == today);
Avoid string conversions if you possibly can.
If your InsertionDate includes times, then either you need to try to get the SQL query to truncate that to a date, or you could use:
DateTime today = DateTime.Today;
DateTime tomorrow = today.AddDays(1);
var query = context.vehicles.Where(v => v.InsertionDate >= today &&
v.InsertionDate < tomorrow);

C# Linq to Entities get records where date range contains dates in the current month

I have Holiday EF Entity:
public class Holiday {
public int HolidayId {
get;
set;
}
public DateTime StartDate {
get;
set;
}
public DateTime EndDate {
get;
set;
}
public bool IsActive {
get;
set;
}
}
I need to get all records that has at least one day within the current month.
For example:
StartDate = "2014-06-29"
EndDate = "2014-07-03"
If current month is July then I should get that record, because after that I will have to create a List<int> of all the days affecting current month. So in the last sample I will have to create a List<int> of:
1,2 and 3 of July.
For example:
StartDate = "2014-07-23"
EndDate = "2014-08-01"
I should get that record also.
I was doing:
var holidays = Holidays.Where(h=> h.IsActive == true && h.StartDate < currentDate && h.EndDate > currentDate).ToList();
But, the query is not doing what I need.
Any clue?
What about this:
.Where(h => h.IsActive == true && (h.StartDate.Month == currentDate.Month || h.EndDate.Month == currentDate.Month)).ToList();
UPDATED:
This won't work when I have a date range where it's month is not equal to currentDate.Month. Like:
StartDate = "2014-06-29"
EndDate = "2014-08-03"
The solution that worked is:
Maybe is not the cleanest.
var holidays = Uow.HolidayRepository.GetAllReadOnly().Where(h => h.IsActive == true && (h.StartDate.Month == currentDate.Month || h.EndDate.Month == currentDate.Month) || (currentDate.Month > h.StartDate.Month && currentDate.Month < h.EndDate.Month)).ToList();
Neither test is sufficient: if the current date is today in then the first test will miss any date ranges that don't include the current date so if today is the first of the month any date range starting on the second although valid won't be caught. In addition single day ranges - unless you are including times won't be caught because the start and end dates could be equal to the current date but can never be greater than and less than - depends how you spec your date range.
The second test fails firstly because every year has months 1- 12 so not only will you be picking records for this year but for all years and secondly you miss any periods that start and end outside of the month.
Creating a list of days to compare doesn't sound efficient minimum number of runs 28 max 31.
So you need to test for ranges that either start in the current month or end in the current month as per Daniels code but in addition you need to test where the start date is before the current month and the end date is after the current month I think that should cover all cases?
I think this will do,please try it out:
int month = DateTime.Now.Month;
var result = Holidays.AsEnumerable().Where(h => Enumerable.Range(h.StartDate.Month, (h.EndDate.Month - h.StartDate.Month) + 1).Contains(month));

How can I check if current day is working day

I have application that needs to be run on working days, and within working hours.
In application configuration, I've set start time in format
Monday-Friday
9:00AM-5:30PM
Now, I have a problem how to check if current day is within day boundare is (for the time is easy - parse time with DateTime.ParseExact and simple branch will do), but I don't know how to parse days.
I've tried with:
DayOfWeek day = DateTime.Now.DayOfWeek;
if (day >= (DayOfWeek)Enum.Parse(typeof(DayOfWeek), sr.start_day) &&
day <= (DayOfWeek)Enum.Parse(typeof(DayOfWeek), sr.end_day))
{ /* OK */ }
sr.start_day and sr.end_day are strings
but the problem occurred during weekend testing - apparently, in DayOfWeek enum, Sunday is first day of the week (refering to the comments on MSDN page
I suppose I could do some gymnastics with current code, but I am looking for the most readable code available.
Edit
Sorry for the misunderstanding - working days are not from Monday to Friday - they are defined as strings in config file, and they can be even from Friday to Saturday - which breaks my original code.
if ((day >= DayOfWeek.Monday) && (day <= DayOfWeek.Friday))
{
// action
}
From Hans Passant's comment on my original question:
Just add 7 to the end day if it is less than the start day. Similarly,
add 7 to day if it is less than the start day.
DayOfWeek day = DateTime.Now.DayOfWeek;
DayOfWeek start_day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), sr.start_day);
DayOfWeek end_day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), sr.end_day);
if (end_day < start_day)
end_day += 7;
if (day < start_day)
day += 7;
if (day >= start_day && day <= end_day)
{
//Action
}
extention for DateTime
public static bool IsWeekend(this DateTime date)
{
return new[] {DayOfWeek.Sunday, DayOfWeek.Saturday}.Contains(date.DayOfWeek);
}
This is an elegant solution for the problem. It's a class that can easily be imported into other projects. The coding allows the programmer to dynamically assign what days to check for and pass them as a string array to the class. The data can come from a database or be hard coded when you pass it to an instance of this class for processing. It returns the values of True if you're off work and False if you're working that day. Below the class I provided a simple example of implementation. This class features: Dynamic allocation of what days you have off, Simple error handler by setting strings to lowercase before comparing them, Easily integrated with a database that has your work schedule where your days off may not always be the same. Easily integrated as a hard coded number of days off.
// The Class To Check If You're Off Work
class DayOffChecker
{
public bool CheckDays(List<string> DaysOff)
{
string CurrentDay = DateTime.Now.DayOfWeek.ToString();
CurrentDay.ToLower();
foreach (string DayCheck in DaysOff)
{
DayCheck.ToLower();
if (CurrentDay == DayCheck)
{
return (true);
}
}
return (false);
}
}
// Example usage code:
class Program
{
List<string> DaysOff = List<string>();
DaysOff.Add("Saturday"); // Add some values to our list.
DaysOff.Add("Sunday");
DayOffChecker CheckToday = new DayOffChecker();
if(CheckToday.CheckDays(DaysOff))
{
Console.WriteLine("You're Off Today!!!");
}
}
We can also follow similar approach of checking if a given hour is between two hours. Following is the algorithm
checkIfFallsInRange(index,start,end)
bool normalPattern = start <= end ;
if ( normalPattern)
return index>=start && index<=end;
else
return index>=start || index <=end;
My simple solution to determining if the current day is a workday or not is:
public static bool IsWorkDay(this DateTime dt)
{
return IsWorkDay(dt, DayOfWeek.Sunday, DayOfWeek.Saturday);
}
public static bool IsWorkDay(this DateTime dt, params DayOfWeek[] noneWorkDays)
{
return !noneWorkDays.Contains(dt.DayOfWeek);
}
It assumes Sunday / Saturday are non-work days. Otherwise the user can specify the non-work days. And is an extension for easy of use.
Note: To avoid a loop could created a bit flag.
DayOfWeek Day = DateTime.Today.DayOfWeek;
int Time = DateTime.Now.Hour;
if (Day != DayOfWeek.Saturday && Day != DayOfWeek.Sunday)
{
if (Time >= 8 && Time <= 16)
{
//It is Weekdays work hours from 8 AM to 4 PM
{
}
else
{
// It is Weekend
}
You can use the DayOfWeek enumeration in order to see if a date is Sunday or Saturday. http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx I hope this can help.
The line below will return "Sunday"
string nameOfTheDay = DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("en-GB")).ToLower();
if(nameOfTheDay != "sunday" && nameOfTheDay != "saturday")
{
//Do Stuff
}
public bool IsWeekend(DateTime dateToCheck)
{
DayOfWeek day = (DayOfWeek) dateToCheck.Day;
return ((day == DayOfWeek.Saturday) || (day == DayOfWeek.Sunday));
}

Categories