Filter DateTime with ExecSQL - outlook-addin

I'm applying this filter:
var date = new DateTime(2019, 06, 20).ToUniversalTime().ToString("dd/MM/yyyy HH:mm");
MAPITable mt = session.Stores.MAPITable;
mt.Item = inbox.Items;
var records = mt.ExecSQL($"select Subject, EntryID from Inbox Where \"urn:schemas:httpmail:datereceived\" > {date}");
I'm having this exception:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in ConsoleApplication1.exe
Additional information: Unsupported operator: /
Should it be possible to do this kind of filter? [With > operator]

You need to make sure the date variable is SQL formatted and encoded in single quotes.

Related

Undefined filter parameter in Hibernate

I am trying to map a LocalDate to a SQL Date, but am receiving this error:
java.lang.IllegalArgumentException: Undefined filter parameter
[afterDateLocal]
I can't provide a reproducible example, but here's the code of the ListingRepositoryImpl:
if (!queries.get("checkInDate").get(0).equals("undefined")) {
Filter afterDateFilter = session.enableFilter("afterDateFilter");
String afterDate = queries.get("checkInDate").get(0);
LocalDate afterDateLocal = LocalDate.parse(afterDate);
System.out.println("After date: " + afterDateLocal);
afterDateFilter.setParameter("afterDateLocal", afterDateLocal);
} else {
session.disableFilter("afterDateFilter");
}
And the filters defined on the entity listing:
#Entity
#Table(name="listing")
#FilterDefs({
#FilterDef(name="priceFilter", parameters=#ParamDef(name="priceComparison",type="double")),
#FilterDef(name="beforeDateFilter", parameters=#ParamDef(name="beforeDateLocal", type="date")),
#FilterDef(name="afterDateFilter", parameters=#ParamDef(name="afterDateLocal", type="date"))
})
#Filters({
#Filter(name="priceFilter", condition="price <= :priceComparison"),
#Filter(name="beforeDateFilter", condition=":beforeDateLocal <= date"),
#Filter(name="afterDateFilter", condition=":afterDateLocal >= date")
})
I am using Hibernate 5.5.7 so I expect LocalDate to work.
date was not defined in the database, which is why I received the error.
i had same problem ("Undefined filter parameter date value") with creating a filter with the LocalDate and i tried this at the type attribute (type = "java.time.LocalDate") and it worked for me.

offsetDateTime illegalArgumentException nhibernate

i am trying to map offsetDateTime to type SQL but i am not sure how to solve the 2 types.
inside my method i am updating the date with
List<Items> listItems = repository.fetchitemById(Ids);
OffsetDateTime date = OffsetDateTime.now();
if (listItems.size() > 0 && !isNull(listItems.get(0).getDate())) {
date = listItems.get(0).getDate();
}
the query is inside the repository a crudRepository with the date on it al already verified the order in the interface and the query they all match
when i evaluate the expression
listItems.get(0).getDate()
i get
Method threw 'java.lang.IllegalArgumentException' exception.
Projection type must be an interface!
java.lang.IllegalArgumentException: Projection type must be an interface!
Also inside the schema the date is a TIMESTAMP with NULL DEFAULT NULL
any thoughts
try this
List<Items> listItems = repository.fetchitemById(Ids);
OffsetDateTime date = OffsetDateTime.now();
if (listItems.size() > 0){
if(!isNull(listItems.get(0).getDate())) {
date =Timestamp.valueOf(listItems.get(0).getDate().toLocalDateTime);
}
}

Showing the result of a query

I'm trying to build a query to get the numbers of rows that have the same data on a column (my column is ESTADO).
var db = Database.Open("MyDB");
var selectedData = db.Query("SELECT COUNT (*) FROM graficos WHERE ESTADO='FECHADO'");
var data = db.QueryValue(selectedData);
But when i try to run it gives the following error:
Compiler Error Message: CS1502: The best overloaded method match for 'WebMatrix.Data.Database.QueryValue(string, params object[])' has some invalid arguments
Line 51: var data = db.QueryValue(selectedData);
Pass the query directly to the QueryValue() method.
var data = db.QueryValue("SELECT COUNT (*) FROM graficos WHERE ESTADO='FECHADO'");
Read this documentation for more information on how to use the Database.QueryValue() method.

How can I preempt a "Specified cast is not valid" exception?

In querying an MS Access database in a Web API app, I get a "Specified cast is not valid" exception if I'm trying to assign an empty string to a variable. IOW, when this code:
var accountID = oleDbD8aReader.GetInt16(0);
var platypusName = oleDbD8aReader.GetString(1);
...reaches a record where the second column in the result set contains an empty/null string, it bombs.
So, I thought I could head that off at the pass like this:
string platypusName;
var accountID = oleDbD8aReader.GetInt16(0);
if (!string.IsNullOrEmpty(oleDbD8aReader.GetString(1)))
{
platypusName = oleDbD8aReader.GetString(1);
}
else
{
platypusName = string.Empty;
}
...but it doesn't work - I still get a "Specified cast is not valid" exception.
How can I safely check for an empty string/null value there and ignore that pass through the result set so that it will get subsequent records?
Or can I preclude this by changing the SQL statement to exclude empty/null strings from the result set? If so, how? The query is in this format:
SELECT td_duckbill_accounts.platypus_no, t_accounts.name
FROM t_accounts
INNER JOIN td_duckbill_accounts ON t_accounts.account_no = td_duckbill_accounts.account_no
ORDER BY td_duckbill_accounts.platypus_no
I think having the query return empty string is easy solution:
SELECT td_duckbill_accounts.platypus_no,
IIF(ISNULL(t_accounts.name),'',t_accounts.name) AS name
FROM t_accounts
INNER JOIN td_duckbill_accounts ON t_accounts.account_no = td_duckbill_accounts.account_no
ORDER BY td_duckbill_accounts.platypus_no
This should also work but I can't test it right now:
SELECT td_duckbill_accounts.platypus_no,
Nz(t_accounts.name,'') AS name
FROM t_accounts
INNER JOIN td_duckbill_accounts ON t_accounts.account_no = td_duckbill_accounts.account_no
ORDER BY td_duckbill_accounts.platypus_no
Sometimes what is needed is to change the data type method used in OleDbDataReader, as this code and the comments show:
while (oleDbD8aReader != null && oleDbD8aReader.Read())
{
string accountId = oleDbD8aReader.GetString(0);
string accountName = oleDbD8aReader.GetString(1);
//int useOnItems = oleDbD8aReader.GetInt32(2); <= get "specified cast not valid" with Int32
int useOnItems = oleDbD8aReader.GetInt16(2); // This works
expenses.Add(new Expense { account_id = accountId, name = accountName, use_on_items = useOnItems });
}
The data type in the underlying table is Integer, so I guess for LongInteger (another Access integer type) GetInt32() would be the OleDbDataReader method to use.

How can I create a DateTime value in a Linq Query?

I am trying to create a query in Linq to Entities. I want it to return objects that include a DateTime property derived from strings in the table I am querying. The data (in SQL Server) has a string date field (in the database it appears as VARCHAR(8)) called date_occurred. It has a String time field (varchar(6)) called time_occurred.
An example of the contents of date_occurred is "20131007" to represent Oct. 7, 2013. An example of the contents of time_occurred is "145710" to mean 10 seconds after 2:57pm.
I have tried two methods that don't work:
Dim ATQuery = From e In EntityContext.vwSecAppAuditToday
Order By e.date_occurred, e.time_occurred
Select New AuditEntry With {
.EventTime = DateTime.ParseExact(Trim(e.date_occurred) & Trim(e.time_occurred), "yyyyMMddHHmmss", CultureInfo.InvariantCulture),
.ServerName = e.server_name
}
This throws a NotSupportedException with a message stating: "LINQ to Entities does not recognize the method 'System.DateTime ParseExact(System.String, System.String, System.IFormatProvider)' method, and this method cannot be translated into a store expression."
Before that, I tried:
Dim ATQuery = From e In EntityContext.vwSecAppAuditToday
Order By e.date_occurred, e.time_occurred
Select New AuditEntry With {
.EventTime = New DateTime(Integer.Parse(e.date_occurred.Substring(0, 4)),
Integer.Parse(e.date_occurred.Substring(4, 2)),
Integer.Parse(e.date_occurred.Substring(6, 2)),
Integer.Parse(e.time_occurred.Substring(0, 2)),
Integer.Parse(e.time_occurred.Substring(2, 2)),
Integer.Parse(e.time_occurred.Substring(4, 2))),
.ServerName = e.server_name
}
This also throws a NotSupportedException. In this case, the message states: "Only parameterless constructors and initializers are supported in LINQ to Entities."
Is what I am trying to do possible using Linq to Entities?
Edit: Comment Alert
For those who read this post later, Moho and Matt Johnson have made especially helpful comments. I have marked these with +1.
Select an anonymous class that contains the fields of interest (called a projection), then create DateTime struct per item after the IQueryable has been enumerated:
Dim ATQuery = From e In EntityContext.vwSecAppAuditToday
Order By e.date_occurred, e.time_occurred
Select New With {
.DateOccurred = e.date_occurred,
.TimeOccurred = e.time_occurred,
.ServerName = e.server_name
}
Dim q2 = From e In ATQuery.ToArray()
Select New AuditEntry With {
.EventTime = DateTime.ParseExact(Trim(e.DateOccurred) & Trim(e.TimeOccurred), "yyyyMMddHHmmss", CultureInfo.InvariantCulture),
.ServerName = e.ServerName
}
Your New DateTime contains only integer, so it looks like 20131008011300 (for 2013/10/08 01:13:00)
/ between date, : between time and a space between date and time are missed