Conversion failed when converting date and/or time from character string [XAF ListViewFilter] - .net-core

I upgraded from framework to .NetCore with XAF 21.2.5
Now if I try to use the following ListViewFilter
[ListViewFilter("Today",
"[Created] >= LocalDateTimeToday()",
"Today", true, Index = 0)]
on my business object which has properties
public DateTime Created { get; set; }
I get an error
Microsoft.Data.SqlClient.SqlException
HResult=0x80131904
Message=Conversion failed when converting date and/or time from character string.
Source=Core Microsoft SqlClient Data Provider
StackTrace:
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
The docs indicate this should work
[Update]
After reading this question I started experimenting with
modelBuilder.Entity<MyEntity>().Property(x => x.Created).HasColumnType("datetime");
I am searching for the nullable one so as to map all the datetime properties.

The solution turned out to be to add the following to the OnModelCreating
modelBuilder.Entity<MyEntity>().Property(x => x.Created).HasColumnType("datetime");
And to carefully check each declared property in the entity to ensure that I had whether or not it was nullable set correctly
I had an int? incorrectly declared as an int

Related

Unable to cast object of type 'System.Int32' to type 'System.Collections.ArrayList'."

We have a replicated cache with 2 nodes, from time to time, we received this error and we aren't able to resolve: "Unable to cast object of type 'System.Int32' to type 'System.Collections.ArrayList'."
The stacktrace:
at Alachisoft.NCache.Web.Command.CommandResponse.ParseResponse()
at Alachisoft.NCache.Web.Caching.RemoteCache.Add(String key, Object value, CacheDependency dependency, CacheSyncDependency syncDependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, Int16 removeCallback, Int16 updateCallback, Int16 dsItemAddedCallback, Boolean isResyncExpiredItems, String group, String subGroup, Hashtable queryInfo, BitSet flagMap, String providerName, String resyncProviderName, EventDataFilter updateCallbackFilter, EventDataFilter removeCallabackFilter, Int64 size, String clientId)
at Alachisoft.NCache.Web.Caching.Cache.AddOperation(String key, Object value, CacheDependency dependency, CacheSyncDependency syncDependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, DSWriteOption dsWriteOption, CacheItemRemovedCallback onRemoveCallback, CacheItemUpdatedCallback onUpdateCallback, DataSourceItemsAddedCallback onDataSourceItemAdded, Boolean isResyncExpiredItems, String group, String subGroup, Tag[] tags, String providerName, String resyncProviderName, NamedTagsDictionary namedTags, CacheDataNotificationCallback cacheItemUdpatedCallback, CacheDataNotificationCallback cacheItemRemovedCallaback, EventDataFilter itemUpdateDataFilter, EventDataFilter itemRemovedDataFilter, Int64& size, Boolean allowQueryTags, String clientId, Int16 updateCallbackID, Int16 removeCallbackID, Int16 dsItemAddedCallbackID)
at Alachisoft.NCache.Web.Caching.Cache.Add(String key, CacheItem item, DSWriteOption dsWriteOption, DataSourceItemsAddedCallback onDataSourceItemAdded)
at Alachisoft.NCache.Web.Caching.Cache.Add(String key, CacheItem item)
In the log files we see:
...received response for request 118849, sender=<IP_Server_1>:7800, val=System.Byte[]
...received response for request 118849, sender=<IP_Server_2>:7800, val=Alachisoft.NCache.Common.DataStructures.Clustered.ClusteredArrayList
How can we resolve this problem?
The casting exception that you are getting is rather strange. This usually thrown on Cache get calls where you may be using an invalid cast. However, in this particular case it is on adding item to the cache which makes me believe this is on server side. Will need to review this - can you share some more details on this.
Please share complete application code snippet along with the flow on _cache.Add API within your code. Also share NCache version and edition information in order to review this in detail. You can run the "verifylicense.exe" tool (located at "C:\Program Files\NCache\bin\tools\verifylicense.exe") to check the current NCache version.
I think you should contact NCache support - support#alachisoft.com - their support is excellent - they should be able to expedite this for you.

Facing error while using "Remote" and "Compare" annotation at a time

I am using Remote validation to validate if username is already taken or not, its working fine. But now I need to add 'compare' data annotation to compare password and confirmPassword fields. But Its giving me error for missing assembly. When I remove Library System.Web.Mvc (which is used for Remote), then error goes away.
Is there any conflict between remote and compare or I'm missing something.
using System.Web.Mvc
using System.ComponentModel.DataAnnotaion
public partial class user
{
[Remote("CheckExistingUsername","Home",ErrorMessage = "Email already exists!")]
public string Username{get;set;}
public string password {get;set;}
[Compare("password",ErrorMessage="Un Matched")]
public string confirmPassword {get;set;}
}
try to add compare with namespace
[System.ComponentModel.DataAnnotations.Compare("pass",ErrorMessage = "unmatched")]
by default it is using the compare of System.Web.Mvc.CompareAttribute which might be causing problem
Do like this,
[CompareAttribute("pass", ErrorMessage = "Unmatched")]
For more info regarding CompareAttribute click here

TypeMock to fake DateTime.Parse

I need a way to fake DateTime.Parse with Typemock and have it return the same date when called with any parameters.
I have a DB field that stores an encrypted string that is parsed as date when loaded. The class that holds the data has a Load() method where it copies DB data into its properties, decrypts what's encrypted and does some basic validation, such as:
public class BusinessObject{
public DateTime ImportantDate{get;set;}
...
public void Load(DBObject dbSource){
...
ImportantDate = DateTime.Parse(DecryptionService.Decrypt(dbSource.ImportantDate));
}
}
Runtime all works well.
I'm trying to write a unit test using TypeMock to load some fake data into BusinessObject using its Load method. BusinessObject has way too many properties and can not be deserialized from XML, but DBObject can, so I've stored some XMLs that represent valid data.
It all works well until DecryptionService is called to decrypt the data - it doesn't work because my dev machine doesn't have the DB certificates used in the encryption process. I can't get those on my machine just for testing, that would be a security breach.
I added this to my unit test:
Isolate.Fake.StaticMethods<DecryptionService>(Members.ReturnRecursiveFakes);
Isolate.WhenCalled(() => DecryptionService .Decrypt(null)).WillReturn("***");
Isolate.Fake.StaticMethods<DateTime>(Members.ReturnNulls);
Isolate.WhenCalled(() => DateTime.Parse("***" /*DateStr*/)).WillReturn(DateTime.Now.AddYears(2));
The first part where DecryptionService is faked works, social security and other sensitive strings are "decrypting", but no matter what parameters I give to DateTime I still get one exception or another (ArgumentNullException: String reference not set to an instance of an object if DateStr is null, FormatException when it's "*")
How (if) can I override DateTime.Parse with typemock so that it returns valid DateTime with any invalid paramters passed?
My name is Nofar and i'm from Typemock's support team.
DateTime.Parse is not supported in the WhenCalled API, so in order to fake it's returned value you need to wrap it with a method from your class, for example:
public class BusinessObject
{
public DateTime Load (string s)
{
return DateTime.Parse(s);
}
}
And you test will look like this:
[TestMethod]
public void TestMethodDateTime()
{
BusinessObject b = new BusinessObject();
DateTime now= DateTime.Now.AddYears(2);
Isolate.WhenCalled(()=>b.Load(null)).WillReturn(now);
Assert.AreEqual(now, b.Load(null));
}
Supporting DateTime.Parse in the WhenCalled API is in our backlog.
Please feel free to contact us via mail at support#typemock.com
Nofar
Typemock Support

How to pass a NULL value to a WCF Data Services' service operation?

I have a WCF data services' service operation such as
[WebGet(UriTemplate = "GetData")]
public IQueryable<string> GetData(int code, int deviceid, int groupId, DateTime dateTimeFrom, DateTime dateTimeTo)
{ ...
}
I am calling this service operation by sending a HTTP request to the server in this format:
http://localhost:6000/GetData?code=0&deviceId=1&groupId=0L&dateTimeFrom=datetime'2013-01-31T15:36:50.904'&dateTimeTo=datetime'2012-02-01T15:36:50.904'
and it is working like a charm.
Now I want to pass a NULL value as one of the parameters. How do I do that? Do I need to use nullable types such as "Int?" in the service operation declaration? How do I encode the NULL value in the URI?
Yes - you need to declare the parameter as nullable. Then you can simply omit the parameter (if it's nullable it will be treated as null then).

EF Migrations: Can't add DateTime column

I'm using ASP.Net 4 EF 4.3.1 Code First Migrations.
I have an existing model class. I've added a property to it:
public DateTime LastUpdated { get; set; }
When I run update-database -force -verbose I get:
ALTER TABLE [MyTable] ADD [LastUpdated] [datetime] NOT NULL DEFAULT
'0001-01-01T00:00:00.000'
System.Data.SqlClient.SqlException
(0x80131904): The conversion of a varchar data type to a datetime data
type resulted in an out-of-range value.
The statement has been terminated.
I'm going to guess this relates to the implied default value being used in the generated SQL - it would appear to be complaining that the varchar it used to initialize things is data lost.
The answer to this problem of not being able to add a non-null DateTime column is the same as the problem of getting 2 default values specified for a DateTime column:
EF 4.3.1 Migration Exception - AlterColumn defaultValueSql creates same default constraint name for different tables
That is, it's been broken a long time, and you can workaround it by migrating with it nullable:
public DateTime? LastUpdated { get; set; }
PM> update-database
Then migrate again with it not null to get where you intended:
public DateTime LastUpdated { get; set; }
PM> update-database

Resources