ErrorHandling in Filehelpers when using SqlStorage - c#

I provided record containing column with integer type, instead of reporting errors (as documented here) got InvalidCastException in method below (for filling records in storage):
protected void FillRecordOrder(object rec, object[] fields)
{
OrdersVerticalBar record = (OrdersVerticalBar) rec;
record.OrderDate = (DateTime) fields[0];
}
How to handle errors using SqlStorage in Filehelpers library?

What are the contents of fields[0]? Are you saying it contains an integer? Then you need to convert it somehow to a DateTime. Something like:
protected void FillRecordOrder(object rec, object[] fields)
{
OrdersVerticalBar record = (OrdersVerticalBar) rec;
if (fields[0] == null)
record.OrderDate = DateTime.MinValue;
else if (fields[0] is DateTime)
record.OrderDate = (DateTime)fields[0];
else if (fields[0] is int)
{
DateTime baseDate = new DateTime(1900, 1, 1);
DateTime newDate = baseDate.AddDays((int)fields[0]);
record.OrderDate = newDate;
}
}

Related

Infragistics UltraGrid, I want a formated string from a string value

I'm using Infragisitics 17.1 UltraGrid.
The Grid has 2 columns.
I want the formatted string of the second column, just like below.
'20170102123456' => '2017-01-02 12:34:56"
The data type of the second column is 'string' not 'date'.
This grid will have huge data, so any conversion is worry to me.
But any adive is welcome.
DataSoure just like below.
private void SetTestData()
{
DataTable dtDataSource = new DataTable("table1");
dtDataSource.Columns.Add("OrderDate", typeof(DateTime));
dtDataSource.Columns.Add("RequiredDate", typeof(string));
ultraGrid1.DataSource = dtDataSource;
DataRow rowNew = dtDataSource.NewRow();
rowNew["OrderDate"] = DateTime.Now;
rowNew["RequiredDate"] = "20170101123456";
dtDataSource.Rows.Add(rowNew);
}
And I Initialize Grid Just like below,
private void UltraGrid1_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
{
// Fit columns
e.Layout.AutoFitStyle = AutoFitStyle.ExtendLastColumn;
// Set date formats
e.Layout.Bands[0].Columns["OrderDate"].Format = "yyyy-MM-dd HH:mm:ss";
e.Layout.Bands[0].Columns["RequiredDate"].Format = "yyyy-MM-dd HH:mm:ss";
}
The first column works fine, but the second column does not.
How i can display the second column just like below?
'20170102123456' => '2017-01-02 12:34:56"
UltraGrid will not be able to do this conversation alone. What you can do in this specific case is implement your own custom IEditorDataFilter. To do so change your InitializeLayuot like this:
private void UltraGrid1_InitializeLayout(object sender, InitializeLayoutEventArgs e)
{
// Fit columns
e.Layout.AutoFitStyle = AutoFitStyle.ExtendLastColumn;
// Set date formats
e.Layout.Bands[0].Columns["OrderDate"].Format = "yyyy-MM-dd HH:mm:ss";
// You do not need this as the column data type is string
//e.Layout.Bands[0].Columns["RequiredDate"].Format = "yyyy-MM-dd HH:mm:ss";
// Set the column's editor DataFilter instead
e.Layout.Bands[0].Columns["RequiredDate"].Editor.DataFilter = new DF();
}
Then create your custom DataFilter like this:
internal class DF : IEditorDataFilter
{
public object Convert(EditorDataFilterConvertArgs conversionArgs)
{
switch(conversionArgs.Direction)
{
case ConversionDirection.DisplayToEditor:
break;
case ConversionDirection.EditorToDisplay:
var valueAsString = conversionArgs.Value.ToString();
var year = int.Parse(valueAsString.Substring(0, 4));
var month = int.Parse(valueAsString.Substring(4, 2));
var day = int.Parse(valueAsString.Substring(6, 2));
var hours = int.Parse(valueAsString.Substring(8, 2));
var minutes = int.Parse(valueAsString.Substring(10, 2));
var result = new DateTime(year, month, day, hours, minutes, 0).ToString("yyyy-MM-dd HH:mm:ss");
conversionArgs.Handled = true;
conversionArgs.IsValid = true;
return result;
case ConversionDirection.OwnerToEditor:
break;
case ConversionDirection.EditorToOwner:
break;
default:
break;
}
return conversionArgs.Value;
}
}

C# WinForm error import from excel to database

Hei. I need to understand why I receive an error like that :
C# windows form import from excel error
I can't separe the year from string (year time). Or, can I renounce at split and import directly the string as "date"? Sorry, I'm too beginner in c#, but I need this help, is a task for me.
Here is my code :
for (int i = 0; i < dvColumns.Count; i++)
{
string columnName = string.Empty;
string columnField = string.Empty;
if ((dvColumns[i]["Header"] != null) && (!Convert.IsDBNull(dvColumns[i]["Header"])))
{
columnName = dvColumns[i]["Header"].ToString();
}
if ((dvColumns[i]["Field"] != null) && (!Convert.IsDBNull(dvColumns[i]["Field"])))
{
columnField = dvColumns[i]["Field"].ToString();
}
rangeObject = cellsObject.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, cellsObject, new object[] { row, i + 1 });
object valueObject = rangeObject.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, rangeObject, null);
if (columnName == "FiscalCode" && columnField == "PartnerId")
{
string fiscalCode = Erp.Core.Utils.GetStringFromObject(valueObject);
partnerId = p.GetPartnerIdByFiscalCode(fiscalCode);
eventRow["PartnerId"] = partnerId;
}
else if (columnField == "StartDate" || columnField == "EndDate")
{
string date = Erp.Core.Utils.GetStringFromObject(valueObject);
DateTime columnDate = DateTime.Now;
string[] dateComponents = null;
int year = 0;
int month = 0;
int day = 0;
if (date.Contains("."))
{
dateComponents = date.Split('.');
}
if (date.Contains("/"))
{
dateComponents = date.Split('/');
}
if (date.Contains(":"))
{
dateComponents = date.Split(':');
}
if (dateComponents.Length > 1)
{
string s = dateComponents[0];
day = Erp.Core.Utils.GetIntFromObject(s);
s = dateComponents[1];
month = Erp.Core.Utils.GetIntFromObject(s);
s = dateComponents[2];
year = Erp.Core.Utils.GetIntFromObject(s);
columnDate = new DateTime(year, month, day, 9, 0, 0);
}
eventRow[columnField] = columnDate;
}
else if (columnField != "PartnerId" && columnField != "StartDate" && columnField != "EndDate")
{
eventRow[columnField] = valueObject;
}
}
I tried to keep in excel same format as in database table : 'yyyy/mm/dd hh:mm:ss.000'.
The line date = Erp.Core.Utils.GetStringFromObject(valueObject); get my date from first excel cell.
ds.Tables["Events"] is all time empty.
I know this line eventRow[columnField] = date; must add the dates in DB, really? After split, day is ok (receive an int by s[0]), month is ok (receive an int by s[1], but s[2] for year is something like 2017 19:06:22 .... year plus time). I tried to split again by space, but without results, to keep the number (2017) in year variable.
Best way is to use DateTime.ParseExact method. In your case, if original format is 'yyyy/mm/dd hh:mm:ss.000', you can convert it to DateTime like this:
//string date = Erp.Core.Utils.GetStringFromObject(valueObject);
string date = "2017/08/15 10:20:30.000";
DateTime columnDate = DateTime.ParseExact(date, "yyyy/MM/dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
This way you can skip parsing excel string.
In your example, usage will be like this:
//...snip...
else if (columnField == "StartDate" || columnField == "EndDate")
{
string date = Erp.Core.Utils.GetStringFromObject(valueObject);
//parsing date string
DateTime columnDate = DateTime.ParseExact(date, "yyyy/MM/dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
eventRow[columnField] = columnDate;
}
else if (columnField != "PartnerId" && columnField != "StartDate" && columnField != "EndDate")
{
eventRow[columnField] = valueObject;
}
if hours are in 12-hour format, use lowercase hh, like this "yyyy/MM/dd hh:mm:ss.fff"

Nullable-How to compare only Date without Time in DateTime types in C#?

How to compare only Date without Time in DateTime types in C#.One of the date will be nullable.How can i do that??
DateTime val1;
DateTime? val2;
if (!val2.HasValue)
return false;
return val1.Date == val2.Value.Date;
You can use the Date property of DateTime object
Datetime x;
Datetime? y;
if (y != null && y.HasValue && x.Date == y.Value.Date)
{
//DoSomething
}
This uses short-circuit to avoid comparisons if nullable date is null, then uses the DateTime.Date property to determine equivalency.
bool Comparison(DateTime? nullableDate, DateTime aDate) {
if(nullableDate != null && aDate.Date == nullableDate.Value.Date) {
return true;
}
return false;
}
bool DatesMatch(DateTime referenceDate, DateTime? nullableDate)
{
return (nullableDate.HasValue) ?
referenceDate.Date == nullableDate.Value.Date :
false;
}
If you want a true comparison, you can use:
Datetime dateTime1
Datetime? dateTime2
if(dateTime2.Date != null)
dateTime1.Date.CompareTo(dateTime2.Date);
Hope it helps...
The only challenging aspect here is the fact that you want something which is both DateTime and nullable.
Here is the solution for standard DateTime: How to compare only Date without Time in DateTime types in C#?
if(dtOne.Date == dtTwo.Date)
For nullable, it's just a matter of choice. I would choose an extension method.
class Program
{
static void Main(string[] args)
{
var d1 = new DateTime(2000, 01, 01, 12, 24, 48);
DateTime? d2 = new DateTime(2000, 01, 01, 07, 29, 31);
Console.WriteLine((d1.Date == ((DateTime)d2).Date));
Console.WriteLine((d1.CompareDate(d2)));
Console.WriteLine((d1.CompareDate(null)));
Console.WriteLine("Press enter to continue...");
Console.ReadLine();
}
}
static class DateCompare
{
public static bool CompareDate(this DateTime dtOne, DateTime? dtTwo)
{
if (dtTwo == null) return false;
return (dtOne.Date == ((DateTime)dtTwo).Date);
}
}
You could create a method like the one below, following the similar return values as the .net framework comparisons, giving -1 when the left side is smallest, 0 for equal dates, and +1 for right side smallest:
private static int Compare(DateTime? firstDate, DateTime? secondDate)
{
if(!firstDate.HasValue && !secondDate.HasValue)
return 0;
if (!firstDate.HasValue)
return -1;
if (!secondDate.HasValue)
return 1;
else
return DateTime.Compare(firstDate.Value.Date, secondDate.Value.Date);
}
Of Course a nicer implementation would be to create an extension method for this.

Getting the exact format for DateTime from an XML file

In my XML I have a date value as shown below:
[CDATA[07/07/1980]]
I do the following to retrieve the date:
public static DateTime? GetDateTimeValue(string dateTimeString)
{
DateTime i;
if ((dataTimeString != null) && (dataTimeString.Value.Trim() != ""))
if (DateTime.TryParse(dateTimeString, out i))
return i;
return null;
}
The value I get is 07/07/1980 12:00:00 AM.
I can do the following:
DatdTime.TryParse(dateTimeString.ToShortDateString())
But I don't want to manipulate the data in any way. I want to get the date as is.
Any help will be greatly appreciated.
Here is a method I use, but I do not use a nullable DateTime.
private static DateTime nodate = new DateTime(1900, 1, 1);
public static DateTime NODATE { get { return nodate; } }
public static DateTime GetDate(object obj) {
if ((obj != null) && (obj != DBNull.Value)) { // Databases return DBNull.Value
try {
return Convert.ToDateTime(obj);
} catch (Exception) { }
try {
return DateTime.Parse(obj.ToString());
} catch (Exception) { }
}
return NODATE;
}
I can't always use TryParse because a lot of my code has to be Compact Framework safe.
If anything goes wrong, I will see my NODATE value (January 1, 1900) in my date fields. It is pretty safe to guess that most of my database programs have no date if they try to display something indicating they were input on January 1st of 1900. After all: Everyone has New Year's off, right? :)

How to read from string?

I'm trying to learn how to schedule pictures depending on what time a user has selected.
Here is code with questions:
private void startjob()
{
string theDate = DateTimePicker1.Value.ToString();
DateTime dt = Convert.ToDateTime(date);
{
DateTime start = new DateTime(2009, 12, 9, 10, 0, 0); //How Do I make this to read the string that is converted from DateTimePicker instead of this?
DateTime end = new DateTime(2009, 12, 10, 12, 0, 0); //How Do I make this to read the string that is converted from DateTimePicker instead of this?
DateTime now = DateTime.Now;
if ((now > start) && (now < end))
{
//match found
}
}
}
DateTimePicker.Value returns the DateTime object. You're trying to convert to and from a string type unnecessarily.
DateTime start = DateTimePickerStart.Value;
DateTime end = DateTimePickerEnd.Value;
Supposing your controls are named as DateTimePicker1 and DateTimePicker2:
private void startjob()
{
DateTime start = DateTimePicker1.Value;
DateTime end = DateTimePicker2.Value;
DateTime now = DateTime.Now;
if ((now > start) && (now < end))
{
//match found
}
}
DateTimePicker.Value property is a DateTime object itself, hence your code can be simplified, no need to convert to string.

Categories