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}']]]
Related
I am using the following helper function:
public List<EventRecord> GetEvents(DateTime afterTime)
{
var formattedDateTime = $"{afterTime:yyyy-MM-dd}T{afterTime:HH:mm:ss}.000000000Z";
var query = $"*[(System/Provider/#Name='.Net Runtime') and (System/EventID=1000) and (System/TimeCreated/#SystemTime >= '{formattedDateTime}')]";
var queryResult = new EventLogQuery("Application", PathType.LogName, query);
var reader = new EventLogReader(queryResult);
var events = new List<EventRecord>();
while (true)
{
var rec = reader.ReadEvent();
if (rec == null)
{
break;
}
events.Add(rec);
}
return events;
}
This code almost works except the query seems to be ignoring the TimeCreated entirely. It's returning all events with the given ProviderName and EventId. I have tried all sorts of different things to get this to work but no matter what, TimeCreated is ignored.
Anyone see what I'm doing wrong?
Edit 1
Even replacing the query line with:
var query = $"*[System[TimeCreated[#SystemTime >= '{formattedDateTime}']]]";
Doesn't work. Returns all events regardless of when they were Created.
Edit 2
So I tried using the 'custom view' builder to generate an XML query for me and what I found was even more perplexing:
So currently the time displayed on my machine is: 2:42pm.
In 24 hour time it should be 14:42pm.
When I create a query using the custom view and select:
From: 'Events On' 03/18/2021 2:42pm , it creates the following:
<QueryList>
<Query Id="0" Path="Application">
<Select Path="Application">*[System[Provider[#Name='.NET Runtime'] and (EventID=1000) and TimeCreated[#SystemTime>='2021-03-18T20:42:13.000Z']]] </Select>
</Query>
</QueryList>
Why on gods green earth did it convert 2:42pm to 20:42?
So apparently you need to convert your time to UniversalTime for this to work.
Here is a working sample:
public List<EventRecord> GetEvents(DateTime afterTime)
{
var formattedDateTime = afterTime.ToUniversalTime().ToString("o");
var query = $"*[System[Provider[#Name='.NET Runtime'] and (EventID=1000) and TimeCreated[#SystemTime>='{formattedDateTime}']]]";
var queryResult = new EventLogQuery("Application", PathType.LogName, query);
var reader = new EventLogReader(queryResult);
var events = new List<EventRecord>();
while (true)
{
var rec = reader.ReadEvent();
if (rec == null)
{
break;
}
events.Add(rec);
}
return events;
}
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"));
when convert utcnow to local time, it shows error like
"LINQ to Entities does not recognize the method 'System.DateTime
ToLocalTime()' method, and this method cannot be translated into a
store expression."
I am using SQL Server 2014 and not mango db. It will work when I use the function UTCtoLocal outside the query. But I need to use it within the linq query to speed up the execution. There is any other way to do that.
group new
{
Id = ord.Id,
ShipmentInfoId = shipment.Id,
PartnerName = partner.Name,
PartNumber = ordItem.SellerProductID,
OrderNumber = ord.UniqueOrderID,
PartCount = shipment.PartCount,
DeliveryDate = ord.DeliveryDate,
IsSentInvoice = shipment.IsSentInvoice != null ? shipment.IsSentInvoice : false,
IsSentASN = shipment.IsSentASN != null ? shipment.IsSentASN : false,
ShippingPartCount = 0,
IsManualEntered = ord.IsManualEntered,
LastGeneratedInvoiceDate = shipment.LastGeneratedInvoiceDate.Value.UtcToLocal(),
LastGeneratedASNDate = shipment.LastGeneratedASNDate.Value.UtcToLocal(),
Solution here by playing around with your DateTimeKind.Utc and ToLocalTime()
var dt = new DateTime(2010, 1, 1, 1, 1, 1, DateTimeKind.Utc);
string s = dt.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz");
Console.WriteLine(s);
Source: datetime to string with time zone
i have 'created date' and 'closed date' in my file and i'm converting it in json so i have that dates in json.
in my method i have two parameter like from date and to date and i want to count particular column data of my file between from date and to date.so how can we write code to fetch it using linq.
i tried this...
public JsonResult StatusDerails(DateTime from,DateTime to)
{
string csvurl = WebConfigurationManager.AppSettings["csvfileurl"];
var lines = System.IO.File.ReadAllLines(csvurl).Skip(1);
List<Product> prdt = new List<Product>();
foreach (string line in lines)
{
Product c1 = new Product();
var split = line.Split(',');
c1.ID = Int32.Parse(split[0]);
c1.Area_Path = split[1];
c1.IterationPath = split[2];
c1.State = split[3];
c1.Reason = split[4];
c1.Priority = Int32.Parse(split[5]);
c1.Severity = split[6];
c1.Tags = split[7];
c1.Title = split[8];
c1.CreatedDate = split[9];
c1.CreatedBy = split[10];
c1.ResolvedDate = split[11];
c1.ResolvedBy = split[12];
c1.ClosedDate = split[13];
c1.AssignedTo = split[14];
prdt.Add(c1);
}
//var list = prdt.GroupBy(a=>a.AreaPath).Select(a=>new UIproduct() {
var productName = prdt.Select(a => a.Area_Path).Distinct();
List<StatusDetail> statusdetail = new List<StatusDetail>();
foreach (var Name in productName)
{
StatusDetail sd = new StatusDetail();
sd.CarryOver = prdt.Where(a => a.CreatedDate >= from.Date.ToString() && a.ClosedDate <= to.Date.ToShortDateString
}
return Json(statusdetail, JsonRequestBehavior.AllowGet);
}
The comparison of DateTime as string will not be a good option and that wont gives you the exact result, So I recommend you to change the type of CreatedDate and ClosedDate to DateTime. and compare two DateTime values in linq. I think instead of splitting json for creating object of certain types you can use json converters.
Fix for your scenario:
c1.CreatedDate = DateTime.Parse(split[9]);
c1.ClosedDate = DateTime.Parse(split[13]);
Don't forget to change the type in the class, Now its fine to use the linq as like the following:
sd.CarryOver = prdt.Where(a => a.CreatedDate >= from.Date && a.ClosedDate <= to.Date);
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