I am facing struggle to bind values to grid which are retrieved from data base. I have a database column of type DateTime which is nullable. So, when I am trying to bind that null value, it is throwing an error while adding those column value to object property . So, before adding values fetched from database, i am using a function that converts the value to its default type before adding to object. Since , the default value for datetime Type is 1/1/0001 12:00:00 AM . So, where ever null values are present , I am getting this value for this field.
How to solve this issue? Please give your sugesstions.
To explain my scenario , i am adding a piece of code here.
public static T GetValue<T>(object o)
{
T val = default(T);
if (o != null && o != DBNull.Value)
{
val = (T)o;
}
return val;
}
This is the helper function I am using while reading data from the data reader.
Since you declared datetime as nullable, instead of converting it to datetime,convert it by using datetime?
Thus it allows datetime values with null values
Related
i tried to modify a collection before returning it to be exported with maatwebsite Excel. The column i tried to modify is the created_date column (the default created_date of laravel) so that when exported to excel, i only get the date not datetime.
i tried:
namespace App\Exports;
use App\Invoice;
use Maatwebsite\Excel\Concerns\FromCollection;
class InvoicesExport implements FromCollection
{
public function collection()
{
$temp = Invoice::all();
$len = count($temp);
for($i=0;$i<$len;$i+=1){
$temp[$i]->created_at = $temp[$i]->created_at->format('m/d/Y')
}
return $temp;
}
}
in the controller:
public function export()
{
return Excel::download(new InvoicesExport, 'invoices.xlsx');
}
but, when exported, the result in the excel file is, for example: '07/26/2016T00:00:00.000000Z'
i noticed that the time become zero, and when i tried:
$temp[$i]->created_at = "some random string"
the laravel in webpage return error said that "some random string" cannot be parsed to datetime by Carbon Class constructor.
how can i make the exporting does not construct datetime with the string i give in the 'created_at' column, but just return the plain string instead? if let's say, i can't modify the database so i can't create extra column and extra column for this simple thing is too much, i think.
If you are using Maatwebsite\Excel 2.1 try column formatting by the setColumnFormat($array) method.
If Maatwebsite\Excel 3.1, try with the WithMapping interface.
created_at is marked as 'datetime' in the $cast property of your model by default so when you set it it's automatically cast as date (with Carbon::parse('the value you gave'))
If you want to export your collection with some values formatted you should not mutate the objects of the original objects but create new dedicated objects/arrays that will not interfere with model behavior nor corrupt your existing objects.
Does anyone know how to create the date type predicate for Hazelcast?
I use Predicates.equal("date","value"); It doesn't work properly. I pass an existing date value in Hazelcast. It returns nothing. java.util.date should be comparable.
I don't know why it doesn't compare properly. Anybody can help, appreciate very much!
you can also try out your own predicate. i.e. if you have a map with key being Object and value being Date then you can do the following:
final Date requiredDate = /*your date object*/;
map.values(new Predicate<Object, Date>() {
public boolean apply(Entry<Object, Date> arg0) {
Date date = arg0.getValue();
if(requiredDate.equals(date))
return true;
else
return false;
}
});
you can do other forms of comparisons inside the apply method as well.
I was wondering if CsvHelper by Josh Close has anything in the configuration I am missing to translate values to null. I am a huge fan of this library, but I always thought there should be some sort of configuration to let it know what values represent NULL in your file. An example would be a column with the value "NA", "EMPTY", "NULL", etc. I am sure I could create my own TypeConverter, but I was hoping there would be an easier option to set somewhere in a config as this tends to be fairly common with files I encounter.
Is there a configuration setting to do this relatively easily?
I found the TypeConversion in the CsvHelper.TypeConversion namespace but am not sure where to apply something like this or an example of the correct usage:
new NullableConverter(typeof(string)).ConvertFromString(new TypeConverterOptions(), "NA")
I am also using the latest version 2.2.2
Thank you!
I think some time in the last seven years and thirteen versions since this question was asked the options for doing this without a custom type map class expanded, e.g.:
csvReader.Context.TypeConverterOptionsCache.GetOptions<string>().NullValues.Add("NULL");
csvReader.Context.TypeConverterOptionsCache.GetOptions<DateTime?>().NullValues.AddRange(new[] { "NULL", "0" });
csvReader.Context.TypeConverterOptionsCache.GetOptions<int?>().NullValues.Add("NULL");
csvReader.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanFalseValues.Add("0");
csvReader.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanTrueValues.Add("1");
CsvHelper can absolutely handle nullable types. You do not need to roll your own TypeConverter if a blank column is considered null. For my examples I am assuming you are using user-defined fluent mappings.
The first thing you need to do is construct a CsvHelper.TypeConverter object for your Nullable types. Note that I'm going to use int since strings allow null values by default.
public class MyClassMap : CsvClassMap<MyClass>
{
public override CreateMap()
{
CsvHelper.TypeConversion.NullableConverter intNullableConverter = new CsvHelper.TypeConversion.NullableConverter(typeof(int?));
Map(m => m.number).Index(2).TypeConverter(intNullableConverter);
}
}
Next is setting the attribute on your CsvReader object to allow blank columns & auto-trim your fields. Personally like to do this by creating a CsvConfiguration object with all of my settings prior to constructing my CsvReader object.
CsvConfiguration csvConfig = new CsvConfiguration();
csvConfig.RegisterClassMap<MyClassMap>();
csvConfig.WillThrowOnMissingField = false;
csvConfig.TrimFields = true;
Then you can call myReader = new CsvReader(stream, csvConfig) to build the CsvReader object.
IF you need to have defined values for null such as "NA" == null then you will need to roll your own CsvHelper.TypeConversion class. I recommend that you extend the NullableConverter class to do this and override both the constructor and ConvertFromString method. Using blank values as null is really your best bet though.
I used "ConvertUsing"...
public class RecordMap : CsvHelper.Configuration.ClassMap<Record>
{
public RecordMap()
{
AutoMap();
Map(m => m.TransactionDate).ConvertUsing( NullDateTimeParser );
Map(m => m.DepositDate).ConvertUsing( NullDateTimeParser );
}
public DateTime? NullDateTimeParser(IReaderRow row)
{
//"CurrentIndex" is a bit of a misnomer here - it's the index of the LAST GetField call so we need to +1
//https://github.com/JoshClose/CsvHelper/issues/1168
var rawValue = row.GetField(row.Context.CurrentIndex+1);
if (rawValue == "NULL")
return null;
else
return DateTime.Parse(rawValue);
}
}
I am trying to perform some logic in a CRM 2011 Custom Workflow Activity with some attributes from the calling entity. I am having an issue with determining whether a particular attribute is null or not. I have tried seemingly all combinations of GetAttributeValue and the Attributes collection, but it seems that I will always get either a Specified Cast is not Valid or Object Reference Not Set to an Instance of an Object error when there is a null value for an attribute I'm trying to access. Does anyone know the correct method for accessing an attribute that may be null? In this example, I am working with attributes of the Guid/Entity Reference type.
You can always check to see if the attributes collection contains the specific attribute that you're looking for, but you shouldn't even have to do that. All Non-nullable types (Guid, DateTime, etc) are stored as nullable types in the Attributes collection and that's probably your problem. Try something like this ( assuming late bound):
var isValid = entity.GetAttributeValue<bool?>("new_IsValid");
CRM never returns a non-nullable value. Even things that you think would be null (bool, DateTime, int, etc) are returned as their nullable equivalent. A non-nullable cast will still succeed if the value is not null, but if the value is null, it'll give you a null reference error;
object a = new bool?(true);
bool value = ((bool)a); // Works
object b = new bool?();
bool value = ((bool)b); // Null Ref Error
This syntax ended up working for me:
//if current outside counsel not null, grab GUID value
if (thisCase.lgl_outsidecounselid != null)
{
currentOCGUID = thisCase.lgl_outsidecounselid.Id;
}
//it's null, set Guid to Guid.empty
else
{
currentOCGUID = Guid.Empty;
}
I have used dynamic object but here is a situation where the column names comes from a pre-defined string arrays.How can i create objects at runtime with these pre-defined set of column values?.
The reason why i wanted to do this way is to create a custom class and add custom validation attributes in it so that i can use reflection at runtime to populate values to these dynamic objects mapped to my custom class and validate the values using a single function.
dynamic x = new MyCustomClass();
x.Name = "Jones"; // The Field or Column name "Name" comes from a array of strings.
Validator.Validate(x); //Here i use reflection to iterate through the custom attributes on MyCustomClass and validate them based on conditions.
Is it possible to do something like this x."Name" = "Jones"; :-)
I would suggest perhaps adding an indexer property to your MyCustomClass?
public string this[string binder] {
get {
string result;
return (this.TryGetMember(binder, out result)) ? result : string.Empty
}
set {
this.TrySetMember(binder, value);
}
}
x["Name"] = "Jones";