I'm creating reports in C# ASP.Net, whereby in the reports I can filter data created between two different dates (e.g Start date: 15th July and End date: 17th July) but when it comes to filtering data created on a particular day (e.g StartDate: 15th July and End Date: 15th July) the query doesn't retrieve anything...
//Code from OutletDistributor.aspx.cs
ReportManager master = ObjectFactory.GetInstance<ReportManager>();
ReportResponse responce = new ReportResponse();
if (ddDistributor == Guid.Empty)
responce = master.GetAllOutletDistributor(sDate, EDate);
else
responce = master.GetOutletDistributor(sDate, EDate, ddDistributor);
ReportViewer1.Reset();
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.ProcessingMode = ProcessingMode.Local;
var stream = Assembly.GetAssembly(typeof(SampleReport)).GetManifestResourceStream(responce.ReportResource);
ReportDataSource reportDataSource = new ReportDataSource(responce.ReportDataSet, responce.ReportDataSource);
stream = RdlcReportHelper.TranslateReport(stream);
ReportViewer1.LocalReport.DataSources.Add(reportDataSource);
ReportViewer1.LocalReport.LoadReportDefinition(stream);
ReportViewer1.LocalReport.DisplayName = ResourceHelper.GetText(null, "hq.rpt.outletdist.heading");
ReportViewer1.LocalReport.Refresh();
//Code from ReportManager.cs
//Filter All Outlet Distributor
public ReportResponse GetAllOutletDistributor(DateTime StartDate, DateTime EndDate) {
ReportResponse report = new ReportResponse();
report.ReportResource = "Distributr.HQ.Lib.Reports.RcdlFiles.OutletDistributor.rdlc";
List<OutletReportItem> Report = _outletReport.GetAllOutlets()
.Where(p => p.CreationDate >= StartDate && p.CreationDate <= EndDate).ToList();
Report.ForEach(n => report.ReportDataSource.Add(n));
report.ReportDataSet = "dsOutletDistributor";
return report;
}
I assume that StartDate and EndDate both contain a time component. Remove it using the Date property:
StartDate = StartDate.Date;
EndDate = EndDate.Date;
// your query goes here...
Actually, your code List<OutletReportItem> Report = _outletReport.GetAllOutlets().Where(p => p.CreationDate >= StartDate && p.CreationDate <= EndDate).ToList() when initialize the object DateTime so the default value of date with hours, minutes and seconds which are '00'. So I think you could use DateTime.Compare()
In this condition where your date is same use "=" (instead of difference) in your query
Related
I am trying to retrieve data from oracle database between 2 dates. I keep getting the following error:
An exception of type 'Oracle.ManagedDataAccess.Client.OracleException' occurred in Oracle.ManagedDataAccess.dll but was not handled in user code
I'm not sure if the problem from the query I wrote:
public List<GetterAndSetterObj> GetDataBasedOnSelectedPeriod(DateTime fromDate, DateTime toDate)
{
using (ProdOracleContext oracleContext = new ProdOracleContext())
{
using (OracleCommand command = oracleContext.CreateCommand)
{
command.CommandText = string.Format("select * from datesTable where TRUNC(dates) BETWEEN TO_DATE('{0}','DD-MON-RRRR') AND TO_DATE('{1}','DD-MON-RRRR')", fromDate, toDate);
var queryResult = oracleContext.Get(command);
var list_v_sum_slaies_by_lice_no = new List<getterAndSetterObj>();
foreach (DataRow row in queryResult.Rows)
{
finalList.Add(new getterAndSetterObj
{
LICENCE_NUMBER = row["LICENCE_NUMBER"].ToString(),
SHOP_NAME = row["SHOP_NAME"].ToString(),
dates= row.Field<DateTime>("dates"),
SUM_ALL = int.Parse(row["SUM_ALL"].ToString())
});
} return finalList;
}
}
}
Then I call the function using these method:
public List<v_sum_slaies_by_lice_no> GetDataBasedOnSelectedPeriod(string fromDate, string toDate)
{
DateTime OfromDate = DateTime.ParseExact(fromDate, "dd/MM/yyyy", null);
DateTime OtoDate = DateTime.ParseExact(toDate, "dd/MM/yyyy", null);
return dataBase.GetDataBasedOnSelectedPeriod(OfromDate, OtoDate);
}
note, the input would be something like this:
20/06/2019
22/06/2019
Note, the date stored on the database as a datetime which include the time and I want to get the data based on the date only
Try to change the below line of code. If it will not work share the actual oracle error.
command.CommandText = string.Format("select * from datesTable where TO_CHAR(dates, 'DDMMYYYY') BETWEEN '{0}' AND '{1}'", fromDate.ToString("ddMMyyyy"), toDate.ToString("ddMMyyyy"));
I have the following event log query where I need to filter by event ID and specific date range for the Time Created. Here is what I current have:
var _PRINTINGDOCUMENTEVENTID = "307";
var startTime = System.DateTime.Now.AddMinutes(-10);
var endTime = System.DateTime.Now
var query = string.Format("*[[System/EventID={0}] and [System[TimeCreated[#SystemTime >= {1}]]] and [System[TimeCreated[#SystemTime <= {2}]]]", _PRINTINGDOCUMENTEVENTID, startTime.ToUniversalTime().ToString("o"), endTime.ToUniversalTime().ToString("o"));)
var logQuery = new EventLogQuery("Microsoft-Windows-PrintService/Operational", PathType.LogName, query );
var reader = new EventLogReader(logQuery);
I get the following error when I try to debug the event log query:
The specified query is invalid
Here is what the query value looks like while debugging:
"*[[System/EventID=307] and [System[TimeCreated[#SystemTime >=
2016-03-28T22:51:23.9082575Z]]] and [System[TimeCreated[#SystemTime <=
2016-03-28T23:01:23.9092576Z]]]"
How do I fix this issue?
I was able to determine the correct format for filtering by event id and a date range for TimeCreated
var eventId = "307";
var startTime = System.DateTime.Now.AddMinutes(-10);
var endTime = System.DateTime.Now;
var query = string.Format(#"*[System/EventID={0}] and *[System[TimeCreated[#SystemTime >= '{1}']]] and *[System[TimeCreated[#SystemTime <= '{2}']]]",
eventId,
startTime.ToUniversalTime().ToString("o"),
endTime.ToUniversalTime().ToString("o"));
Have you tried surrounding your formatted DateTimes with ticks?
and [System[TimeCreated[#SystemTime >= '{1}']]]
I'm using WinForms and C#, and I'm trying to compare between a date from the database and the current date.
My code is the following :
DataManager.NotificationManager obj = new DataManager.NotificationManager();
DataTable dt1 = obj.GetListExpiryDate();
string currendate = DateTime.Today.ToString("yyyy-MM-dd");
foreach (DataRow row in dt1.Rows)
{
if (DateTime.Parse(row.ItemArray[41].ToString("dd/MM/yyyy")) == currendate)
{
MessageBox.Show("Expired carte for the employee" + row["EmpFName"]);
} //.RowStyles[0].Height = 0; this.tlp_id.ColumnStyles[1].Width = 0; }
else
{
MessageBox.Show(" not Expired carte for the employee" + row["EmpFName"]);
}
}
The problem is that the data coming from the database doesn't have the same format of the currentdate value!
Any ideas please?
Do not format the date coming from the database as a string. Instead, use the value as DateTime:
if (((DateTime)row.ItemArray[41]).Date == DateTime.Today) {
MessageBox.Show("Expired carte for the employee" + row["EmpFName"]);
}
This way formatting would become irrelevant.
Note the use of .Date and DateTime.Today to ensure that only the date portion would be compared, ignoring the time portion.
Instead of converting the DateTime to a string in currentdate, convert the return from the database to a DateTime value and compare those.
DataManager.NotificationManager obj = new DataManager.NotificationManager();
DataTable dt1 = obj.GetListExpiryDate();
DateTime currendate = DateTime.Today;
foreach(DataRow row in dt1.Rows)
{
if (DateTime.Parse(row.ItemArray[41].ToString().Date) == currendate)
{
MessageBox.Show("Expired carte for the employee" + row["EmpFName"]);
}
else
{
MessageBox.Show(" not Expired carte for the employee"+row["EmpFName"]);
}
}
If Item 41 is indeed a DateTime object, the simplest thing to do would be:
var dt = row[41] as DateTime;
if (dt != null) {
// process dt as a DateTime object.
}
While using DateTime conversions, I would suggest one to use the TryParse();It allows you to provide an array of strings as your possible input formats.
Here's the most overloaded signature:
public static DateTime ParseExact(
string s,
string[] formats,
IFormatProvider provider,
DateTimeStyles style
)
I'm using below code for parsing an atom feed:
using(var reader = new MyXmlReader("http://tutsplus.com/courses.atom")) {
var doc = SyndicationFeed.Load(reader);
var newFeed = new AtomFeed {
Id = doc.Id,
Title = doc.Title.Text,
Url = url,
UpdateDate = DateTime.Now
};
XNamespace dc = "http://www.w3.org/2005/Atom";
newFeed.AtomEntries = (from entry in doc.Items
select new AtomEntry {
Id = entry.Id,
Links = entry.Links,
Title = entry.Title.Text,
Content = entry.Content.ToString(),
PublishDate = entry.PublishDate.DateTime,
UpdatedDate = entry.LastUpdatedTime.DateTime,
Authors = entry.Authors
}).ToList();
}
Seems that a string was not recognized as a valid DateTime in my feed. I'm also aware (+) that The SyndicationFeed.Load method expects to receive feeds that are in standard format like this: Mon, 05 Oct 2015 08:00:06 GMT. So I created my custom XML reader that recognizes different date formats. But still have same error!
Any idea?
When I tried it, with your linked custom XML reader, I also got this error when it came to parsing the "published" and "updated" dates. Looking at the code for the Atom10FeedFormatter class, it is trying to parse dates in these formats (DateFromString method)
const string Rfc3339LocalDateTimeFormat = "yyyy-MM-ddTHH:mm:sszzz";
const string Rfc3339UTCDateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ";
http://reflector.webtropy.com/default.aspx/WCF/WCF/3#5#30729#1/untmp/Orcas/SP/ndp/cdf/src/NetFx35/System#ServiceModel#Web/System/ServiceModel/Syndication/Atom10FeedFormatter#cs/2/Atom10FeedFormatter#cs
So I changed in the MyXmlReader implementation to set that format yyyy-MM-ddTHH:mm:ssZ, then all is well with this date parsing (I also had to change in ReadStartElement the element names to set readingDate equal to true, i.e. published and updated).
public override string ReadString()
{
if (readingDate)
{
string dateString = base.ReadString();
DateTime dt;
if (!DateTime.TryParse(dateString, out dt))
dt = DateTime.ParseExact(dateString, CustomUtcDateTimeFormat, CultureInfo.InvariantCulture);
return dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
}
else
{
return base.ReadString();
}
}
I have a program which fetches appointments from Microsoft Exchange for a given calendar and I want to output these in an ASP.net file
The "code behind" I have is:
DateTime StartDate = DateTime.Today;
DateTime EndDate = DateTime.Today.AddDays(1);
CalendarView cv = new CalendarView(StartDate, EndDate);
String MailboxToAccess = "RES_03037#company.com";
FolderId CalendarFolderId = new FolderId(WellKnownFolderName.Calendar, MailboxToAccess);
FindItemsResults<Appointment> fapts = service.FindAppointments(CalendarFolderId, cv);
if (fapts.Items.Count > 0)
{
DataRow row = table2.NewRow();
foreach (Appointment Appoint in fapts)
{
//Output to ASPX file
}
}
I am fairly new to ASP and C#
Your advice will be much appreciated!