Cannot deserialize datetime property Neo4j using C# client in a transaction - c#

My problem is related to this question:
I'm having the same failure, but in a different scenario:
At run time the error is occurring inside;
using (var scope = new TransactionScope())
{
// Doing stuff here fails only within a transaction!
scope.Complete();
}
The same problem code runs perfectly fine when executed outside of a transaction!
The error message is:
Newtonsoft.Json.JsonReaderException was unhandled
HResult=-2146233088 LineNumber=1 LinePosition=33 Message=Could
not convert string to DateTime: 15/05/2016 09:23:34 +00:00. Path 'a',
line 1, position 33. Path=a Source=Neo4jClient
The code versions are:
Neo4jClient version=1.1.0.16
Newtonsoft.Json version=8.0.1
This answer basically says I can pass a
new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" }
To the serialisation but as that is inside Neo4jClient how can I implement that.
Answer
client.JsonConverters.Add( new IsoDateTimeConverter() );

Adding this line of code immediately after creating the client, solved the of datetime serialisation problem.
Note: my culture is en-GB so I am not sure if this would need finegling to adjust for your culture settings.
client.JsonConverters.Add( new IsoDateTimeConverter() );
I think there are numerous ways of making this happen but this one definately works.

Related

System.FormatException after update donet and ef core

I got this strange error out of a sudden after updating from dotnet 6.0 to dotnet 7.0
and EF CORE from Version 12 to Version 13.
But even more strange is; if i debug it in my meshine, it works.
if i run this in a docker container on my synology NAS, i get this problem.
But it worked before the update.
Input:
<td>23.01.2023 16:20:58</td>
try to parse like this
Date = Convert.ToDateTime(columns[0].InnerHtml, new CultureInfo("de-DE")),
Time = Convert.ToDateTime(columns[0].InnerHtml, new CultureInfo("de-DE")).TimeOfDay
the actual error i got is:
System.FormatException: String '23.01.2023 16:20:58' was not recognized as a valid DateTime.
at System.Convert.ToDateTime(String value, IFormatProvider provider)
what could going on here?
Regardless of what you think the culture identifier of that file is (you seem to think it's German?), there is exactly one way to correctly parse a date from a string when you know what format it is: DateTime.[Try]ParseExact.
DateTime.ParseExact("23.01.2023 16:20:58", "dd.MM.yyyy HH:mm:ss", null)

c# SMO Backup - how to use ExpirationDate?

I followed roughly this example to backup a database with Microsofts SMO API and the code crashed with an exception telling invalid parameter ExpirationDate. I checked the documentation which does not contain details on how to set the parameter and my intuition told me it should be in the future, right? I was curious and tested some values:
DateTime.Today.AddDays(10) -> InvalidDataException
DateTime.Today.AddDays(-10) -> works fine
DateTime.Today.AddDays(-5) -> works fine
DateTime.Today.AddDays(-4) -> works fine
DateTime.Today.AddDays(-3) -> InvalidDataException
DateTime.Today.AddDays(-1) -> InvalidDataException
DateTime.Today.AddDays(100) -> InvalidDataException
DateTime.Today.AddDays(500) -> InvalidDataException
DateTime.Today.AddDays(1000) -> works fine
Reading this 5 year-old post it could be that the internal parameter is actually not of the type DateTime? But then it would be a bug, right?
These errors are likely the result of the locale of where the Backup.ExpirationDate property is being set from. Depending on the culture this is being executed in, the DateTime.AddDays method may increment the month instead of the day as expected, leading to the inconsistent results you saw. Of the values that you tested only the negative ones should cause errors, as the range of days for a backup expiration date is 0 - 99999, with 0 indicating that the backup will never expire as stated in the documentation. Try using the CultureInfo class to define a new locale then set the expiration date. This will require a reference to the System.Globalization namespace. Running the following code gave me no errors in setting the expiration date in a backup operation using the US (en-US) culture. Just make sure that the date in the culture you convert this to matches the date you expect it to in your timezone.
using System.Globalization;
string folderPath = #"C:\YourFolder\";
Server serv = new Server(#"YourServer");
Backup bkup = new Backup();
bkup.Database = "YourDatabase";
string bkupFilePath = folderPath + bkup.Database.ToString() + ".bak";
bkup.Action = BackupActionType.Database;
bkup.Devices.AddDevice(bkupFilePath, DeviceType.File);
bkup.BackupSetName = "YourDatabase Full Backup";
bkup.BackupSetDescription = "Full backup of YourDatabase";
DateTime today = DateTime.Now;
//define current date representation with en-US culture
string newLocale = today.ToString(new CultureInfo("en-US"));
//set Backup.ExpirationDate to use new culture
bkup.ExpirationDate = Convert.ToDateTime(newLocale);
bkup.ExpirationDate.AddDays(10);
bkup.ExpirationDate.AddDays(100);
bkup.ExpirationDate.AddDays(500);
bkup.ExpirationDate.AddDays(1000);
bkup.SqlBackup(serv);
edit I am super confused. I thought this solved my issue:
My issue was that I called backup.ExpirationDate.AddDays(X) without assigning it to anything. Therefore, the software was basically using "DateTime.Now".
Solution:
backup.ExpirationDate = backup.ExpirationDate.AddDays(X);
But it didn't completely. I still get the exception if I do this:
backup.ExpirationDate = backup.ExpirationDate.AddDays(1);
No idea why this code is wrong.

DateTime.Parse works in c# console app but not asp.net

I have written a C# console application that after all of it's processing outputs a DateTime to disk. It does this like so:
writer.WriteLine(myDateTime).
This same console appication has no problems with using the following to read this DateTime back:
DateTime.Parse(reader.ReadLine())
However, upon attempting to use the following code in my separate Asp.Net program I recieve an error saying that my string is not a valid DateTime which is odd to say the least.
StreamReader reader = new StreamReader(#"D:\InformerReports\Archive\ReliabilityData\StartTime.hist");
string dateString = reader.ReadLine();
return DateTime.Parse(dateString);
I have checked and the string it is reading in is 10/25/2016 12:00:00 AM.
I have also attempted to use return DateTime.ParseExact(dateString, "dd/MM/yyyy hh:mm:ss tt",null) but this returns the same error.
I can't seem to fathom why identical code performed on the same file works in one case and not the other. I'd appreciate some help.
I guess the culture of the server is different from the machine you are testing from.
The correct format you have to use seems to be:
return DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt", null)
// 10/25/2016 12:00:00 AM
As an add-on to the previous answers.
To avoid the differing cultures across clients you can set the site culture in the global.asax files Application_BeginRequest method like below:
Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-FR");
Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr-FR");
This will force the above specified culture for each user accessing the site.
I am not sure if there are drawbacks to doing it this way, but this solved my issue in the past.

Azure storage analytics log parse error

I'm getting parse exceptions when using WindowsAzure.Storage to access storage analytics logs.
This is my code for retrieving log records:
var recordList = this.SourceAnalyticsClient.ListLogRecords(
this.Service, this.StartTime, null, this.Configuration.BlobRequestOptions,
this.CreateOperationContext())
.ToList();
That code throws the following exception:
Error parsing log record: could not parse 'Wednesday, 03-Dec-14 08:59:27 GMT' using format: dddd, dd-MMM-yy HH:mm:ss 'GMT' (type InvalidOperationException)
Exception stack trace:
at Microsoft.WindowsAzure.Storage.Analytics.LogRecordStreamReader.ReadDateTimeOffset(String format)
at Microsoft.WindowsAzure.Storage.Analytics.LogRecord.PopulateVersion1Log(LogRecordStreamReader reader)
at Microsoft.WindowsAzure.Storage.Analytics.LogRecord..ctor(LogRecordStreamReader reader)
I'm guessing this happens because my thread is not using an English culture.
I need a way to resolve this problem or a workaround.
After investing this a little bit I found that LogRecordStreamReader.ReadDateTimeOffset is specifying a null format provider parameter to DateTimeOffset.TryParseExact. That means that the thread's current culture will be used - and that won't work for threads using non-English cultures.
A possible workaround is:
// Remember current culture setting
CultureInfo originalThreadCulture = Thread.CurrentThread.CurrentCulture;
try
{
// Assign the invariant culture temporarily
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
// Let WindowsAzure.Storage parse log records
recordList = this.SourceAnalyticsClient.ListLogRecords(
this.Service, this.StartTime, null, this.Configuration.BlobRequestOptions,
this.CreateOperationContext())
.ToList();
}
finally
{
// Restore original culture setting
Thread.CurrentThread.CurrentCulture = originalThreadCulture;
}
I've also created a pull request with a suggested fix.

Attempted to read or write protected memory when using Entity Framework

An unhandled exception of type 'System.AccessViolationException' occurred in StatCentric.Tracker.Worker.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I've read numerous posts on both Stack Overflow and various blogs and can't seem to find a solution for this.
I'm doing something very basic:
public void Execute(ITrackerRequestModel model)
{
PageviewRequest p = (PageviewRequest)model;
using (var db = new StatCentricEntities())
{
db.SetTimeout(60);
db.sp_Log_PageView2(p.SiteId, p.DateTimeUtc, p.vid, p.QueryString, p.p, p.t);
}
}
But this error pops up every time I try to call db.sp_Log_PageView2. This only seems to happen inside my worker role (I'm using Windows Azure).
Also worthy of note is that I'm using the Windows Azure Emulator and I am on Windows 8.1.
I've tried the following:
Doing a winsocket reset
Disabling JIT debugging (native,script, managed)
Disabling JIT debugging on module load
Followed some old posts to hot fixes that seem to be specific to .NET
2.0 and discontinued.
Did a memory diagnostic with no issues to make sure it wasn't my hardware.
I am running Visual Studio as administrator and connecting to a remote SQL Server Database hosted in Azure.
Any ideas on how to resolve or further diagnose this are appreciated.
This is not real fix but while waiting for fix from Microsoft you can use this workaround.
I have same problem. I also tried everything to solve that issue. After few days I gave up and used manual "workaround". It only took few minutes to copy and convert existing sproc calls to new ones.
Just ignore auto generated functions and manually call stored procedures. You can use auto generated classes for returned data. Copy and modify existing function and you will get easily correct parameter names and types.
Just implement partial class to different file:
public partial class StatCentricEntities
{
public virtual List<sp_Log_PageView2_Result> my_sp_Log_PageView2(
Guid? siteId,
DateTime time,
string param3,
string param4 )
{
return Database.SqlQuery<sp_Log_PageView2_Result>(
"sp_Log_PageView2 #siteId #time #param3 #param4",
new SqlParameter("siteId", siteId),
new SqlParameter("time", time),
new SqlParameter("param3", param3),
new SqlParameter("param4", param4)).ToList();
}
}
I was getting this "Attempted to read or write protected memory exception" error while using a SQL Server stored procedure that had an output parameter of type 'Date'. I tried various things without success and, in the interest of time, settled on the following solution.
1) Remove the output parameter of type date
2) Return a string via a select statement
SELECT CONVERT(char(10), #AsOfDate, 20) AS AsOfDate
3) Convert the string returned from the stored procedure to a DateTime value in C#
DateTime asOfDate = DateTime.Now;
using (var context = new DA.MyEntities())
{
var procResult = context.myStoredProcedure(myParameter).FirstOrDefault();
DateTime.TryParse(procResult, out asOfDate);
}
I'm not super happy with this compromise, but it did allow me to move forward.

Categories