Format DateTime object in Model as NotMapped Property - json

I have a model called Report having bellow two properties. I am going to retrieve the data and send it to jQuery datatable. I need to format the date field before sending it to view, I did it as bellow:
public class Report
{
public int Id {get; set;}
public DateTime ActivityDate { get; set; }
//Here is the date formation property
public string FormattedDate => ActivityDate.ToString();
}
Here is the action method which is being called by jQuery datatable:
[JQDataTable]
public ActionResult Search()
{
IQueryable<Report> data = db.Reports;
return View("Index",data);
}
The problem is, I can not get the formatted date, instead I am getting an error of:
The specified type member 'FormattedDate' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
I tried and search alot but was unable to find a solution for this. In next step I want to convert this date to PersianCalendar object and return its string.

I have faced similar problems using ToString inside Linq query. For your case I think it would be easier to handle the conversion of datetime in time of view and leave the datetime variable as is. Rather accept specific format for the search action, parse the received date and do the query.
After suffering for a very long time, I now tend to accept datetime from view as string with my explicitly specified format ("yyyy-mm-dd" just my personal choice :P ) and use DateTime.TryParseExact() handling the null input as well.
Hope it helps. Happy coding.

Related

Sending JSON via REST using DynamoDB attribute name

I have a field in my Car POJO class that looks like this:
#DynamoDBAttribute(attributeName = "release_year")
private int year;
I want to add a Car to my database by sending a POST request via Postman. I was hoping that my JSON body could look like this:
{
"release_year": 2015
}
It is not possible, I have to use 'year' instead. In my dynamoDB, the field is called 'release_year';
My question is: is it possible to use 'release_year' in my POST request somehow, but still keep 'year' in the POJO class? Or do I have to rename the field to 'release_year'?
I don't have exp with Java but seem #DynamoDBAttribute annotation only works on function level. So pls try
private int year;
#DynamoDBAttribute(attributeName = "release_year")
public int getYear() { return year; }
public void setYear(int year) { this.year = year; }
I found out that the annotation #JsonSetter(valueName) over the fields would suffice for my case. I can use
{
release_year: 2015
}
for my POST request, and when I use GET request, that value will be release_year instead of year like before.
I guess #DynamoDBAttribute only works for the columns in the database and does not affect the requests.

Typescript - auto conversion from a Json string with a date string to an object with a Date property

When calling a REST service returning JSON, how can I format a date so that it is converted automatically into a typescript Date object?
The result of calling a REST call is this message:
{"id":3796,...,"startTempValue":"2019-05-26T19:39:01Z"}
I also tried this ISO format:
{"id":3796,...,"startTempValue": "2019-05-26T19:39:01.000Z"}
The model object is:
export class Settings {
public id: number;
public shortName;
public description: string;
public value: string;
public possibleValues: string;
public startTempValue: Date;
}
The result of startTempValue is a string ... ?! I want the startTempValue to be a Date object.
Of course, I could convert the Date string to a Date object manually. So, doing something like the code below at reception of the REST service result. But there should be a better way. Another alternative would be to convert it at the server to an epoch (milliconds). That is possible, but still, this 'string' variant is more readable.
if ( this.settings[i].startTempValue !== undefined &&
this.settings[i].startTempValue !== null) {
this.settings[i].startTempValue = new Date(this.settings[i].startTempValue);
} else {
this.settings[i].startTempValue = null;
}
JSON only deals with primitives like numbers, strings, arrays and objects.
There is no information within JSON that describes what its contents mean. So even if something looks like a date to you, it's still just a string.
So how could you convert it manually? Well, if you know in advanced what property names are always dates, you could loop through the result and convert these preemptively. Or you could loop through all the values and take anything that looks like a date and automatically convert.
A third option would be to have some kind of schema that marks certain things as dates and use that for your automatic conversion.
The point is that there is no built-in way to infer this, and it's kind of up to you do to something else with your data

Does the business logic for deserializing a JsonPayload have to match?

I am currently attempting to deserialize a Json Payload that has been fired from a webhook URL on an MVC application, but I do not know if the business logic provided has to match exactly to prevent any null values.
Basically the Json Payload contains way to much useless information that I do not what to display. This is a brief preview of what the Payload looks like:
"webhookEvent":"jira:issue_updated",
"user":{
"self":"http://gtlserver1:8080/rest/api/2/user?username=codonoghue",
"name":"codonoghue",
"issue":{
"id":"41948",
"self":"http://gtlserver1:8080/rest/api/2/issue/41948",
"key":"OP-155",
"fields":{
"summary":"Test cc recipient",
"progress":{
"progress":0,
"total":0}, ....
I only want to display information about the issue and the other information is just white noise to me and don't want to use it. Now do I have to create classes only for the issue details etc like this:
Public Class jiraIssue
Public Property id As String
Public Property key As String
Public Property fields As jiraFields
End Class
Or do I have to make sure to provide sufficient business logic about the User class just to make sure that it will be received correctly? I also know that using Json2csharp.com the classes that can be made are user, issue, fields, progress as well as the overall RootObject, so I also want to know is do these classes need to contain the exact same matching variables as the JsonPayload, e.g. I don't want progress to have the variable total.
When using Json2csharp that in every class they contain an ID variable with the property as string and I would like to know if this is needed in the classes to be able to display the information or can I not use it as it is also irrelevant.
The main thing that I want to deserialize is the RootObject, which contains a webhookEvent (string) an issue (which links to issue class, which links to fields class which links to all relevant information), comment which links to a comment class. I want to deserialize this so would this be correct?
Public Class Rootobject
Public Property webhookEvent As String
Public Property issue As Issue
Public Property comment As Comment2
Public Property timestamp As Long
End Class
Public Class Issue
Public Property key As String
Public Property fields As Fields
End Class
Public Class Fields
Public Property issueType as IssueType
Public Property summary As String
Public Property summary As String
End Class
Dim Issue As RootObject = New System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(Of RootObject)(json)
For Each item As var In Issue.issue
Console.WriteLine("WebhookEvent: {0}, issue: {1}", item.WebhookEvent, item.issue)
Next
Update
It seems that the problems that I was having was due to the JsonPayload itself, the business logic did not affect. There were issues with the incompatible characters, some fields were null and could not be and a few others as well.
I have correctly got my Json payload correctly read in and the Json Payload information does not have to correctly match up with the classes that you create. You only have to create classes and variables for the information that you need from the Json Payload. For example if you did not want the information on comments do not create a comment class.
Public Class Rootobject
Public Property webhookEvent As String
Public Property issue As Issue
' Public Property comment As Comment2
' comment out the comment class because it is not needed
Public Property timestamp As Long
End Class

asmx change DateTime format

Haven't found anything out there after doing some searches.
I'm wondering if
there's any way to specify how an asmx WebService serializes a DateTime to json?
Can this be setup as a webconfig setting? Or am I stuck with the /Date(millis)/ format?
I don't know any way to do this, but one solution is to use a double value (or possibly long if you're not interested in fractional milliseconds) which contains the total number of milliseconds since the UnixEpoch. You could use a helper class something like:
public static class DateTimeExtensions
{
public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1);
public static double ToUnixTime(this DateTime dateTime)
{
return (dateTime - UnixEpoch).TotalMilliseconds;
}
...
}

Provide binary download links where needed using ASP.NET MVC3 Linq to SQL, maintaining Deferred Loading

I am using a VARBINARY(MAX) column to store binary files in a SQL Server table. The other columns in the same table are used to store attributes about the file, such as a description and a time stamp indicating when the file was uploaded.
I created a view in MVC3 that lists the attributes and a link which the user can use to download the binary file. Some records have a file to download and others do not.
At first the view rendered very slowly because Linq to SQL was including the binary column in the SELECT clause. I changed the Delay Loaded (Linq to SQL Deferred Loading) property for the binary column in the domain model to true to prevent this happening.
I needed a boolean to tell me which records actually have a binary so that the download link only appears when there is a file to download so I added a parameter called BinaryExists to my view model.
namespace MyProject.Models.ViewModels
{
public class DownloadsViewModel
{
public int DownloadsID { get; set; }
public DateTime DateUploaded { get; set; }
public string Description { get; set; }
public Boolean BinaryExists { get; set; }
public DownloadsViewModel()
{
}
public DownloadsViewModel(Downloads dModel)
{
this.DownloadsID = dModel.DownloadsID;
this.DateUploaded = dModel.DateUploaded;
this.Description = dModel.Description;
this.BinaryExists = dModel.Binary != null;
}
}
}
Adding this.BinaryExists = dModel.Binary != null; resulted in Linq to SQL downloading all of the binaries and slowing down the view again.
I want Linq to SQL to provide the boolean indicator without negatively affecting the view performance by downloading the binary. This can be accomplished in T-SQL using the following query.
SELECT
DownloadsID,
DateUploaded,
Description,
CASE
WHEN Binary IS NULL THEN
0
ELSE
1
END AS BinaryExists
FROM Downloads
The CASE statement provides the boolean trigger for when a download link should be made available without actually having to download the binary first just to check whether or not it exists.
Is there a way to do the same thing in Linq to SQL?
Thank you!
Based on mutual feedback, here's the most straightforward solution:
Add a new computed column to the database and use the formula: (CONVERT([bit],case when [Binary] IS NULL then (0) else (1) end,(0))). Set it to "Is Persisted: Yes" for efficiency during querying. Set the datatype of the column to bit not null so that it maps to a bool in the ViewModel. Then, you can use that column to gain information about the bigger lazy loaded binary data column.