LocalDate with Property place holder Spring - spring-mvc

I am working with Spring Boot and property placeholders. I have a property file with the value : date.A=24/07/17.
I have a class and I am using the #Value annotation:
#Value("${date.A}")
private LocalDate dateA;
But I am getting the runtime error when running gradle build integrationTest:
Caused by: java.time.format.DateTimeParseException: Text '24/07/17' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 24
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDate.parse(LocalDate.java:400)

I would need a closer look at the yml file to give the best answer..But here is my hunch-
The expected format is MM/dd/YY.
Can you please try changing the yml file to something like this
..
date
A=07/24/17
..

I think you need to write converter for that as follows:
public LocalDate convertToDateObject(String value) throws ConversionException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
try {
return LocalDate.parse(value, formatter);
} catch (DateTimeParseException ex) {
return null;
}
}

The date should be specified in en_US locale, so you need to swap the month and day:
date.A=7/24/17

Related

Serilog Custom Sink Formatting Issue with Serilog LogEventPropertyValue

I'm having to create my own custom sink because none of the ones currently available give me what I need.
Issue I have is when fetching the key/value pair Value from the logEvent message in the Emit Method, the value is wrapped with quotation marks & backslashes.
I've tried converting the out value from the dictionary into a string and then removing the unwanted attributes but nothing is working for me.
Method in my Custom Sink Class:
public void Emit(LogEvent logEvent)
{
var properties = logEvent.Properties;
Serilog.Events.LogEventPropertyValue value;
if (properties.TryGetValue("logEventCategory", out value))
{
// Regex.Replace((value.ToString() ?? "").Replace("'", #"\'").Trim(), #"[\r\n]+", " "); // Not working
var notWorking = value.ToString();
var formattedValueNotWorking = value.ToString().Replace("\r\n", "\\r\\n");
}
}
It just seems that any attempted formatting of the key/value pair Value is ignored: You see that the example string value System is wrapped with a \"System\"
All I want is the actual string, not the backslashes or quotation marks that is wrapped around the string.
Creating my own sink is a hard enough task and I just want to keep things simple, have spent two days trying to understand the wider picture in message formatting but with custom sinks it gets too complicated and bloated coding for what I need. All the other standard message structure attributes are rendering OK, such as message / level / timestamp etc, it's just fine tuning the rendering of the propertie values I require in order to save these values into their own columns in my DB.
You need to unwrap the string from the enclosing ScalarValue:
// using Serilog.Events;
public void Emit(LogEvent logEvent)
{
var properties = logEvent.Properties;
Serilog.Events.LogEventPropertyValue value;
if (properties.TryGetValue("logEventCategory", out value) &&
value is ScalarValue sv &&
sv.Value is string rawValue)
{
// `rawValue` is what you're looking for
Looks like I just needed to use the correct syntax for string replace:
public void Emit(LogEvent logEvent)
{
var properties = logEvent.Properties;
Serilog.Events.LogEventPropertyValue value;
if (properties.TryGetValue("logEventCategory", out value))
{
var formattedValueWorking = value.ToString().Replace("\"", "");
var test = formattedValueWorking;
}
}

.NET CORE 2.1.1 with Entity Framework Core 2.1.4 Code First: Conversion failed when converting date and/or time from character string

I have a Extension Method to seed my table after created:
public static class ModelBuilderExtensions
{
public static void Seed(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<AppUser>(entity =>
{
entity.HasData(
new Event() { id = 1, WhenDate = DateTime.Now.AddMonths(1) }
)
}
}
I created migration file with this command
Add-Migration InitialCreate
and then
Update-Database
to create database with table but I have this error:
Conversion failed when converting date and/or time from character
string
in my InitialCreate file I have this line:
WhenDate = table.Column(type: "datetime", nullable: false)
in my console log, in insert into command, I see this character string:
'2019-03-12T16:09:33.617+01:00'
I guess the string format is not correct, but how to change it? And what is the right format?
Thanks
I found a solution, if I replace Now by UtcNow it works ! Because it remove "+01:00"...
replace
DateTime.Now.AddMonths(1)
by
DateTime.UtcNow.AddMonths(1)
string result:
'2019-03-12T17:08:25.682Z'
For me, this occurs when I tried to alter column after running update-database:
I fixed by added manual default value like:
defaultValue:"0001-01-01"
For example:
migrationBuilder.AddColumn<DateTime>(
name: "OperationDateTime",
schema: "DefinitionContext",
table: "Path",
type: "DateTime",
nullable: false,
defaultValue:"0001-01-01");

asp.net date time is not result same

this is the property I have :
[DataType(DataType.Time)]
public TimeSpan StartingTime { get; set; }
now in controller I will check if the starting time is less then now
var now = DateTime.Now.TimeOfDay;
return View(db.SchoolTime.ToList().Where(a => a.StartingTime < now );
here even the starting-time is less then now in database but not returning list to vew
I think it's because Starting-time is lik(09:00:00) but the now is like 09:10:00:12312312
please help thanks in advance
It is not because of the '<' condition.
Try changing the code to:
return View(db.SchoolTime.Where(a => a.StartingTime < now).ToList());
Where condition doesn't get applied unless you enumerate over the collection.
ToList() will help you do that.
Else it will execute once the collection is enumerated in the View.
Use the following code
DateTime parsedDate;
string pattern = ;
DateTime.TryParseExact(StartingTime, "MM-dd-yy", null, DateTimeStyles.None, out parsedDate);
parsedDate.TimeOfDay;// out put in your format MM:HH:SS
Inorder to make the above code to work you need to add using System.Globalization; namespace.
Update 1 :
As per your code
var now = DateTime.Now.TimeOfDay;
returns 00:00:00 every time because it should be assigned when you are creating the DateTime object itself.
So use this
var now = DateTime.Now.ToString("hh:mm:ss")
return View(db.SchoolTime.ToList().Where(a => a.StartingTime < now );

Invalid date format causing ModelState to be invalid in controller

I am getting an invalid ModelState when data is returned from a View using an ajax call but only for edits. I am passing a datetime value from a SQL record to the view. The date shows up just fine in a Kendo UI DateTime picker. If I make a new selection from the datetime picker, I don't get the exception, it's only if I don't make any changes do I get the invalid error. Here is what the MVC controller is showing:
The value '/Date(1387443600000)/' is not valid for RequiredByDate."
What am I missing here? First time I have ever had an issue with a datetime field like this.
EDIT: Found out the date was being formatted in the view once the controller passed it in. Here is what I had to do before using it on the page and eventually sending it back to the controller (code is verbose for debugging purposes):
var myModel = model;
var jsonDate = myModel.Header.RequiredByDate; // "/Date(1387443600000)/"
var value = new Date(parseInt(jsonDate.substr(6)));
var ret = value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();
//ret is now in normal date format "12-13-2013"
After posting an edit above I found what I think is an even better solution to the problem. Here is a function that converts the string to an actual date object:
function dateFromStringWithTime(str) {
var match;
if (!(match = str.match(/\d+/))) {
return false;
}
var date = new Date();
date.setTime(match[0] - 0);
return date;
}

SQL statement's placeholders that is not replaced leads to "Cannot update '#columnName'; field not updateable"

I'm writing some code updating database with a SQL statement that has some placeholders . But it doesn't seem to update these placeholders.
I got the following error:
Cannot update '#columnName'; field not updateable
Here is the method:
public void updateDoctorTableField(string columnName, string newValue, string vendorNumber) {
sqlStatement = "update Doctor set #columnName = #newValue where `VENDOR #` = #vendorNumber;";
try {
_command = new OleDbCommand(sqlStatement, _connection);
_command.Parameters.Add("#columnName", OleDbType.WChar).Value = columnName;
_command.Parameters.Add("#newValue", OleDbType.WChar).Value = newValue;
_command.Parameters.Add("#vendorNumber", OleDbType.WChar).Value = vendorNumber;
_command.ExecuteNonQuery();
} catch (Exception ex) {
processExeption(ex);
} finally {
_connection.Close();
}
}
Not all parts of the query are parameterisable.
You can't parametrise the name of the column. This needs to be specified explicitly in your query text.
If this is sent via user input you need to take care against SQL Injection. In fact in any event it would be best to check it against a whitelist of known valid column names.
The reason the language does not allow for parameters for things like table names, column names and such is exactly the same reason why your C# program does not allow for substitution of variables in the code. Basically your question can be rephrased like this in a C# program:
class MyClass
{
int x;
float y;
string z;
void DoSomething(string variableName)
{
this.#variable = ...
}
}
MyCLass my = new MyClass();
my.DoSomething("x"); // expect this to manuipulate my.x
my.DoSomething("y"); // expect this to manuipulate my.y
my.DoSomething("z"); // expect this to manuipulate my.z
This obviously won't compile, because the compiler cannot generate the code. Same for T-SQL: the compiler cannot generate the code to locate the column "#columnName" in your case. And just as in C# you would use reflection to do this kind of tricks, in T-SQL you would use dynamic SQL to achieve the same.
You can (and should) use the QUOTENAME function when building your dynamic SQL to guard against SQL injection.

Resources