pass the value null when datetime is not filled by user - asp.net

I create a function. Where date can be selected by the user . And when the user not select the date i want to pass null .
public DataSet GetInvoicebyPaging(int pageIndex, int pageSize, Int32 clientId, DateTime startDate, DateTime endDate, string invoiceNumber, ref int totalInvoice)
{
// doing something here
}
And this is the code part where i am calling the function
_orderDAC.GetInvoicebyPaging(pageIndex, grdInvoice.PageSize, clientid, Convert.ToDateTime(txtFirstDate.Text.Trim()), Convert.ToDateTime(txtLastDate.Text.Trim()), txtInvoiceNumber.Text.Trim(), ref invoicecount);
Sometime the user cant fill the txtFirstDate.Text but i am converting Convert.TodateTime() so how can i fix this because when user not fill the datetime it give me exception. So how can i handle this .

You need to change your method to:
public DataSet GetInvoicebyPaging(int pageIndex, int pageSize, Int32 clientId, DateTime? startDate, DateTime endDate, string invoiceNumber, ref int totalInvoice)
{
// doing something here
}
And when you parse the user data you can do:
DateTime? start = null;
DateTime possibleStartValue;
if(!string.IsNullOrEmpty(txtTextBox.Text) && DateTime.TryParse(txtTextBox.Text, out possibleStartValue))
{
start = possibleStartValue;
}

You can create a nullable date time variable as follows
DateTime? value = null;
and pass as a parameter
In your function you can use like DateTime? value as parameter
So you will have to do the following step
DateTime? startDate=txtFirstDate.Text.Trim()==""?null:Convert.ToDateTime(txtFirstDate.Text.Trim());
change your function argument so that it can take null value as above.

For any dates you want to be able to accept as null, like DateTime startDate you need to make them nullable like DateTime? startDate
And then before you call GetInvoicebyPaging try and sort out the datetimes.
DateTime startDate;
var correctStart = DateTime.TryParse(txtFirstDate.Text.Trim(), out startDate);
And then pass the parameter like
_orderDAC.GetInvoicebyPaging(pageIndex, grdInvoice.PageSize,
clientid, (correctStart ? startDate : null), etc
And you may have to check if txtFirstDate.Text is null as well.
After declaring startDate above you can do:
var dateString = txtFirstDate.Text ?? "";
And pass dateString.Trim() into the DateTime.TryParse

Related

How to set datetime through Groovy setter

i have a long value then i convert the Longvalue in datetime format. I am not sure if the conversion is in the right way, but i am able to get in the right format. Now i am struggling to set the converterted datetime in groovy using setter. #formattedDate can be in date format, i do not know how to save in datetime. I get the error conversion String datetime. Please help.
def time= 1550670822 / 1000;
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(time, 0, ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss", Locale.ENGLISH);
String formattedDate = dateTime.format(formatter);
trial.setFinishingTime(formattedDate);
In my class i have for setFinishingTime.
public String getFinishingTime()
{
return getPropertyContainer().getString(FINISHING_TIME, "")
}
public void setFinishingTime(String finishingTime)
{
getPropertyContainer().setString(FINISHING_TIME, finishingTime)
}
This part i am not sure, should it be like this in DateTime format:
public DateTime getFinishingTime()
{
return getPropertyContainer().getDate(FINISHING_TIME, "")
}
public void setFinishingTime(DateTime finishingTime)
{
getPropertyContainer().setDate(FINISHING_TIME, finishingTime)
}
If i change this to DateTime how can i store a DateTime of dd:mm:yyyy pattern which i get from the above code. Please help

Correctly convert DateTime property with Dapper on SQLite

I'm using Dapper to insert and get objects to/from SQLite: one object have a property of type DateTime (and DateTimeOffset) that I have to persist and retrieve with milliseconds precision. I can't find a way to correctly retrieve the value because Dapper fail with:
System.FormatException : String was not recognized as a valid DateTime.
in System.DateTimeParse.ParseExactMultiple(String s, String[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style)
in System.DateTime.ParseExact(String s, String[] formats, IFormatProvider provider, DateTimeStyles style)
in System.Data.SQLite.SQLiteConvert.ToDateTime(String dateText, SQLiteDateFormats format, DateTimeKind kind, String formatString)
in System.Data.SQLite.SQLite3.GetDateTime(SQLiteStatement stmt, Int32 index)
in System.Data.SQLite.SQLite3.GetValue(SQLiteStatement stmt, SQLiteConnectionFlags flags, Int32 index, SQLiteType typ)
in System.Data.SQLite.SQLiteDataReader.GetValue(Int32 i)
in System.Data.SQLite.SQLiteDataReader.GetValues(Object[] values)
in Dapper.SqlMapper.<>c__DisplayClass5d.<GetDapperRowDeserializer>b__5c(IDataReader r) in SqlMapper.cs: line 2587
in Dapper.SqlMapper.<QueryImpl>d__11`1.MoveNext() in SqlMapper.cs: line 1572
in System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
in System.Linq.Enumerable.ToList(IEnumerable`1 source)
in Dapper.SqlMapper.Query(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in SqlMapper.cs: line 1443
in Dapper.SqlMapper.Query(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in SqlMapper.cs: line 1382
What do I have to try? Column is of type DATETIME.
Do I have to create a custom TypeHandler and convert DateTime to and from a SQLite string in format "o"?
Dapper version 1.38
I know it's old, but I have found the solution.
After a lot of digging and analyzing Dapper code I came up with this (notice that this is 2019 year):
First you will have to create date time handler:
public class DateTimeHandler : SqlMapper.TypeHandler<DateTimeOffset>
{
private readonly TimeZoneInfo databaseTimeZone = TimeZoneInfo.Local;
public static readonly DateTimeHandler Default = new DateTimeHandler();
public DateTimeHandler()
{
}
public override DateTimeOffset Parse(object value)
{
DateTime storedDateTime;
if (value == null)
storedDateTime = DateTime.MinValue;
else
storedDateTime = (DateTime)value;
if (storedDateTime.ToUniversalTime() <= DateTimeOffset.MinValue.UtcDateTime)
return DateTimeOffset.MinValue;
else
return new DateTimeOffset(storedDateTime, databaseTimeZone.BaseUtcOffset);
}
public override void SetValue(IDbDataParameter parameter, DateTimeOffset value)
{
DateTime paramVal = value.ToOffset(this.databaseTimeZone.BaseUtcOffset).DateTime;
parameter.Value = paramVal;
}
}
Now, notice that Dapper translates .Net's type DateTimeOffset to dbType - DateTimeOffset. You need to remove this mapping and add your own like this:
SqlMapper.RemoveTypeMap(typeof(DateTimeOffset));
SqlMapper.AddTypeHandler(DateTimeHandler.Default);
That's all. Now everytime Dapper will see DateTimeOffset property in your model, it will run your DateTimeHandler to manage this.
I have found that custom TypeHandler for base types can't be used because of default typeMap that is choosen before looking for TypeHandler.
I have opened an issue dapper-dot-net but in the mean time I have solved replacing via reflection the default typeMap with a new one like the previous minus the four key DateTime, DateTime?, DateTimeOffset, DateTimeOffset?
I've made a slight modification to Adam Jachocki's solution as it didn't work for me. I am storing a date as TEXT in Sqlite and Dapper was giving me a string instead of a DateTime as the object value to parse. Apparently, Sqlite stores datetime values using three different data types: INTEGER (unix epoch), TEXT (ISO 8601 YYYY-MM-DD HH:MM:SS.SSS), and REAL ("number of days since noon in Greenwich on November 24, 4741 B.C."). That last one is really out there, so it isn't supported in the code below.
See the sqlite docs and this page for more info.
Below is my implementation of the DateTimeOffset TypeHandler. The rest of Adam's solution remains the same.
internal class DateTimeOffsetHandler : SqlMapper.TypeHandler<DateTimeOffset>
{
private static readonly TimeZoneInfo databaseTimeZone = TimeZoneInfo.Local;
private static readonly DateTime unixOrigin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
public static DateTimeOffsetHandler Default { get; } = new DateTimeOffsetHandler();
public DateTimeOffsetHandler() {}
public override DateTimeOffset Parse(object value)
{
if (!TryGetDateTime(value, out DateTime storedDateValue))
{
throw new InvalidOperationException($"Unable to parse value {value} as DateTimeOffset");
}
if (storedDateValue.ToUniversalTime() <= DateTimeOffset.MinValue.UtcDateTime)
{
return DateTimeOffset.MinValue;
}
else
{
return new DateTimeOffset(storedDateValue, databaseTimeZone.BaseUtcOffset);
}
}
public override void SetValue(IDbDataParameter parameter, DateTimeOffset value)
{
DateTime paramVal = value.ToOffset(databaseTimeZone.BaseUtcOffset).DateTime;
parameter.Value = paramVal;
}
private bool TryGetDateTime(object value, out DateTime dateTimeValue)
{
dateTimeValue = default;
if (value is DateTime d)
{
dateTimeValue = d;
return true;
}
if (value is string v)
{
dateTimeValue = DateTime.Parse(v);
return true;
}
if (long.TryParse(value?.ToString() ?? string.Empty, out long l))
{
dateTimeValue = unixOrigin.AddSeconds(l);
return true;
}
if (float.TryParse(value?.ToString() ?? string.Empty, out float f))
{
throw new InvalidOperationException("Unsupported Sqlite datetime type, REAL.");
}
return false;
}
}

How to insert date and Query date in SQLite table

I am not familiar with SQLite on handling date.
The problem:
Can I insert date this way or insert any date using DateTime to create.
Order_Date = DateTime.Today
How to :
a) How to use a select or query a recordset base or Order_Date ?
b) How to select or query a recordset base on Date Range ? from this date to this date.
Thanks
Class Order
{
[PrimaryKey, AutoIncrement]
public int SId { get; set; }
public int CustId { get; set; }
public string No { get; set; }
public string Customer { get; set; }
public DateTime Order_Date { get; set; }
}
using (var db = new SQLite.SQLiteConnection(DBPath))
{
var newOrder = new Order()
{
CustId = g_intCustId,
Customer = txtBlkCustomer.Text.Trim(),
Order_Date = DateTime.Today
};
db.Insert(newOrder);
----- Update :
1) I wanted to know what is the proper way to insert date into a field of dateTime DataType in table as Above? using Date from DateTime.Today, DateTime.Now
2) what fields need to add in SQLite table when enter Date with
a) normal Date format ( dd/mm/yyyy)
b) format like : Date with HHMMSS
3) How to query or select Date for (2a) and (2b)?
Thanks
Can I insert date this way or insert any date using DateTime to create.
Order_Date = DateTime.Today
Yes, DateTime.Today while insertion will work. SQLite internally stores DateTime objects as string.
How to use a select or query a recordset base or Order_Date ?
using (var db = new SQLite.SQLiteConnection(ApplicationData.Current.LocalFolder.Path + "\\aaa.sqlite"))
{
// You can use any one
var list2 = db.Query<Order>("SELECT * FROM Order WHERE Order_Date = datetime('2013-10-01')", "");
var list3 = db.Query<Order>("SELECT * FROM Order WHERE Order_Date = ?", DateTime.Today.AddDays(-5));
}
How to select or query a recordset base on Date Range ? from this date to this date.
using (var db = new SQLite.SQLiteConnection(ApplicationData.Current.LocalFolder.Path + "\\aaa.sqlite"))
{
// You can use any one
var list = db.Query<Order>("SELECT * FROM Order WHERE Order_Date BETWEEN datetime('2013-10-01') AND datetime('2013-10-07')", "");
var list1 = db.Query<Order>("SELECT * FROM Order WHERE Order_Date BETWEEN ? AND ?", DateTime.Today.AddDays(-9), DateTime.Today.AddDays(-3));
}
SQLite Date And Time Functions
Go thorough bellow link
Windows Phone 7 Native Database Programming via Sqlite Client for Windows Phone
SQLite-WinRT: Database programming on Windows Phone and Windows 8
How to use SQLite in Windows Phone
Hope it will help you

How to work with several fields in DateTime?

public DateTime EnterDeparture()
{
Console.WriteLine("Enter Year:");
return new DateTime().AddYears(int.Parse(Console.ReadLine()));
}
// This will return new DateTime(Without assigned Year) Cause DateTime is value type.
public DateTime EnterDeparture()
{
DateTime EnterDeparture = new DateTime();
Console.WriteLine("Enter Year:");
EnterDeparture.AddYears(int.Parse(Console.ReadLine()));
return EnterDeparture;
}
How to work with several fields in DateTime ? (Year,Days for example) Default constructors aren't suitable.
The DateTime.AddXXX methods return new DateTime instances, the existing struct does not change. Since each method returns a new instance, you can chain the method calls together. At the very least, you want to capture each return value into a variable. For example:
DateTime myDate = DateTime.Today;
DateTime tomorrowAtNoon = myDate.AddDays(1).AddHours(12);
You could have also written it like
DateTime tomorrow = myDate.AddDays(1);
DateTime tomorrowAtNoon = tomorrow.AddHours(12);
Follow?

Linq2EF: Return DateTime with a TimeZone Offset

Our database has all times stored as UTC, and we know the user's current timezone, so want to return it relative to that. So we want to incorporate the offset in a LINQ projection as so:
var users = from u in this.Context.Users
select new UserWithCorrectedDate
{
Id = u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
RegistrationDate = u.RegistrationDate.Value.AddHours(-5)
};
Of course, Linq2EF cannot convert "AddHours" into a canonical function. Is there another way to do this?
UPDATE:
Another thought, if the timezone offset was stored in the database as another column, would there be a way to have the DB perform the calculation (date + offset)?
Linq to Entities supports SqlFunctions. If you know the offset number of hours you could do something like this:
var users = from u in this.Context.Users
select new UserWithCorrectedDate
{
Id = u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
RegistrationDate = SqlFunctions.DateAdd("hour", -5, u.RegistrationDate.Value)
};
If you want to be more precise by using the Timezone function, you could do something like this (this is a bit of a workaround):
public static DateTime UtcToNewYorkTime(DateTime utcDateTime)
{
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime converted = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, tzi);
return converted;
}
And then in your POCO UserWithCorrectedDate object, have a get only property for the Timezoned date ie.
public class UserWithCorrectDate
{
public DateTime UTCDate {get;set;}
public DateTime NYDate
{
get
{
return Utilities.UtcToNewYorkTime(this.UTCDate);
}
}
}
The quick and dirty way to do this is to convert to a list, and just linq to object to get it done:
from u in this.Context.Users.ToList()
select new { ... }

Resources