String was not recognized as a valid DateTime C#.net MVC - c#

I am using MVC and cant find a solution to this error!
here is my model
Scorecard.cs
public partial class Scorecard
{
public int ScorecardID { get; set; }
public int VendorID { get; set; }
public string Title { get; set; }
public bool Enabled { get; set; }
public System.DateTime Created { get; set; }
public int CreatedBy { get; set; }
public Nullable<System.DateTime> LastUpdated { get; set; }
public Nullable<int> UpdatedBy { get; set; }
and my constructor in my ScorecardRepository.cs
//CONSTRUCTOR
public ScorecardRepository()
{
allScorecards = new List<Scorecard>();
scorecardData = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/ScorecardXML.xml"));
var scorecards = from scorecard in scorecardData.Descendants("item")
select new Scorecard((int)scorecard.Element("ScorecardID"), (int)scorecard.Element("VendorID"),
scorecard.Element("Title").Value, (bool)scorecard.Element("Enabled"),
(DateTime)scorecard.Element("Created"), (int)scorecard.Element("CreatedBy"),
(DateTime)scorecard.Element("LastUpdated"), (int)scorecard.Element("UpdatedBy"));
allScorecards.AddRange(scorecards.ToList<Scorecard>());
}
so everything works apart from a DateTime error i am getting which is really confusing me as to why it keeps happening...
ERROR
all help would be greatly appreciated

How about trying:
Convert.ToDateTime(scorecard.Element("Created").Value)

When reading data out of the XDocument, you need to parse the dates rather than cast:
DateTime.Parse(scorecard.Element("Created"))

Do you need to cast explicitly to XElement before the explicit cast to DateTime? i.e.:
(DateTime)(XElement)(scorecard.Element("Created")), ...
Your cast should work with a valid string but, having seen your XML, there are values in there that cannot be parsed into dates. You'll need to check for FormatExceptions when you convert, if the data are not always going to be valid.

You should never trust the input. Use TryParse before you cast anything into any other type except string. And you should check for null values (especially for nullable types). Should it still throw exceptions, they are better managed (by you).

Try this :
(DateTime)Convert.ToDateTime(scorecard.Element("Created").Value),
in
public ScorecardRepository()
{
}

Related

How to define initial values according to generic value?

I have a generic entity class.
if T is guid, I want to initialize new guid value .
if T is int, I want to initialize id =0;
if T is string I want to initialize id =string.empty
What is the most suitable way to do this ?
public class BaseEntity<T>{
public string Id { get; set; } ;
public DateTime? CreatedAt { get; set; } = DateTime.Now;
public DateTime? UpdatedAt { get; set; }= DateTime.Now;
public DateTime? DeletedAt { get; set; }
}
You may want to consider using the default keyword to create an instance of any given type at runtime. However, with your given examples, your intentions may not simply be limited to avoiding unset properties.
Given that possibility, you could dynamically create the desired type and box/unbox it to trick the compiler - such as the example I've provided below.
This isn't generally recommended becuase of it's limited scope and general un-maintainability and error-pronedness.
You have other options as well such as creating generic instances using reflection, this may not be ideal since you have very specific "default" values that using reflection may just increase the complexity of the problem more than using a switch()(depending on your target framework, or if/else(like the example i've provided below.)
public class BaseEntity<T>
{
public T Id { get; set; } = (T)GetDefault<T>();
public DateTime? CreatedAt { get; set; } = DateTime.Now;
public DateTime? UpdatedAt { get; set; } = DateTime.Now;
public DateTime? DeletedAt { get; set; }
private static object GetDefault<U>()
{
Type paramType = typeof(U);
if(paramType == typeof(string))
{
return string.Empty;
}
else if(paramType == typeof(Guid))
{
return Guid.NewGuid();
}
return default(U);
}
}

how to post complex array to mvc c# api

I'm trying to post an array tat one of it's members (th) is an array of strings, I stringify the array, here is hob it looks stringified:
[{"id":"201669887","name":"אורה","Sunday":"1","Monday":"1","Tuesday":"1","Wednesday":"0","Thursday":"1","Friday":"1","Sunday1":"1","Monday1":"1","Tuesday1":"1","Wednesday1":"0","Thursday1":"1","Friday1":"0","totalWorkHour":9,"th":["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"year":" ","schoolName":null,"schoolNumber":null},{"id":"201669887","name":"חנה","Sunday":"1","Monday":"1","Tuesday":"1","Wednesday":"0","Thursday":"1","Friday":"1","Sunday1":"1","Monday1":"1","Tuesday1":"1","Wednesday1":"0","Thursday1":"1","Friday1":"0","totalWorkHour":9,"th":["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""]
I have a model in Mvc:
public class teachersExcelDataModel
{
.....
public int Thursday1 { get; set; }
public int Friday1 { get; set; }
public int totalWorkHour { get; set; }
public List<string> th { get; set; }
public string schoolName { get; set; }
public int schoolNumber { get; set; }
public string month { get; set; }
public string year { get; set; }
public teachersExcelDataModel()
{
th = new List<string>();
}
}
here is how i send it:
this.http.post(this.accessPointUrl3, JSON.stringify(this.sendData), { headers: this.headers }).subscribe(
noteRecord => {
if (noteRecord)
this.a = true;
}
);
and here is how I get it:
public void PostExportExcel([FromBody]List<teachersExcelDataModel>json)
but it comes null,
if i get it as object[], it;s okay,
where am i wrong?
Your example JSON string is not in correct format.
After fixing the format of the json, you will see that you are trying to parse schoolNumber field to integer, which in your case is null and I guess internally the framework throws exception.
Trying to parse the data to object[] does not require parsing null to integer, so now you know why it works in this case
the json format is incorrect based on what i can see from the question. missing "}" and "]" too.

JSON Deserializer "loses" last property of JSON value

passing a Json value like this one(this will be the var jsonValue in code):
"{\"Something\":0,\"Something2\":10,\"Something3\":{\"Something4\":17,\"Something5\":38042,\"Something6\":38043,\"Id\":215},\"Something7\":215,\"SomethingId\":42,\"Something8\":\"AString, Gläser\",\"Something8\":\"44-55-18\",\"Status\":{\"Caption\":\"Fixed\",\"Value\":7},\"Type\":\"Article\",\"Id\":97,\"#Delete\":true,\"Something9\":\"8\"}"
to the following code:
var deserializer = new JsonSerializer();
const string regex = #"/Date\((.*?)\+(.*?)\)/";
var reader = new JsonTextReader(new StringReader(jsonValue));
returnValue = deserializer.Deserialize(reader, type);
type is the typeof https://dotnetfiddle.net/LMPEl0 (thank you Craig) (sorry for the weird names, can't disclose the actual ones...)
The jsonvalue is generated by input in an editable cell of a DataTable and apparently places previously null values in the end of the json string.
I get a null value in the "Something9" property in the returnValue, instead of 8(Something9 was null before and set to 8 through an editable Cell of a DataTable)
Is there some problem with the Json value that I can't see?
Or do I need some setting in the Deserializer?
Thanks
You don't show what your type is so I generated one using http://json2csharp.com.
public class Something3
{
public int Something4 { get; set; }
public int Something5 { get; set; }
public int Something6 { get; set; }
public int Id { get; set; }
}
public class Status
{
public string Caption { get; set; }
public int Value { get; set; }
}
public class RootObject
{
public int Something { get; set; }
public int Something2 { get; set; }
public Something3 Something3 { get; set; }
public int Something7 { get; set; }
public int SomethingId { get; set; }
public string Something8 { get; set; }
public Status Status { get; set; }
public string Type { get; set; }
public int Id { get; set; }
[JsonProperty("#Delete")]
public bool Delete { get; set; }
public string Something9 { get; set; }
}
Because one of your properties has a name that is not valid as a .NET property I added the [JsonProperty] attribute to that one. After that it worked perfectly. Perhaps the problem is with how you declared the #Delete JSON property in your .NET type. Given that Something9 comes after that property it would be my guess that that's part of the problem.
Here's the fiddle.
https://dotnetfiddle.net/McZF9Q
While Craig's answer helped a lot and finally led to a solution the exact answer to the problem was the following:
The Status object is an Enum and was not Deserialized correctly.
Due to that, anything that followed in the Json string was also not deserialized.
Implementing a custom Enum Deserializer was the solution. There are other Questions in stackoverflow that helped with this, particularly this one here:
How can I ignore unknown enum values during json deserialization?
Thank you everyone :)

Giving a property two identifiers for deserializing JSON

I'm deserializing JSON into an object with JavaScriptSerializer in C#.
The object has the following properties:
public string plugin_name { get; set; }
public string slug { get; set; }
public string description { get; set; }
public string logo_full { get; set; }
public string[] categories { get; set; }
public Version[] versions { get; set; }
The thing is that the names (e.g. plugin_name) don't follow the usual naming guidelines (pascal case). Is there any simple way that I can give a property two identifiers? Or is there anything else that could help me achieve what I want. I'm aware that I could do this:
public string PluginName { get; set; }
public string plugin_name { set { PluginName = value; } }
But is there any simpler and cleaner solution to this?
Any help would be appreciated.
Per this documentation, you can add an attribute to assist in this mapping instead of having to create this redirect:
[JsonProperty("plugin_name")]
public string PluginName{get;set;}
But, as pointed out, this is specific to Json.NET. Is it possible for you to use that instead?

JSON RPC Returns numbers as property names

I receive this JSON string (part of a really big one) back from an oracle server (data is unchangeable) but now I have the tedious problem of not being able to deserialize this..
"rows":[
{
"1":"0000000001",
"2":"SPARE00002",
"5":"151.3354",
"13":"100",
"100000":"000000",
"100001":"FFFFFF",
"rowid":"0000000001"
},
with using NewtonSoft.JSon it creates the class :
public class Row
{
public string __invalid_name__1 { get; set; }
public string __invalid_name__2 { get; set; }
public string __invalid_name__5 { get; set; }
public string __invalid_name__13 { get; set; }
public string __invalid_name__100000 { get; set; }
public string __invalid_name__100001 { get; set; }
public string rowid { get; set; }
}
And while trying to deserialise into the class I get the awesome error :
Could not evaluate expression.
Is there any way to format this correctly so c# realises the string NAME is the same as the property name sent by the JSON string?
Any help is highly appreciated!
EDIT! Found the solution!
By adding [JsonProperty("1")] ..etc to the invalid name strings, the problem solved itself!
Awesome!
On each of the invalid property names, add the attribute: [JsonProperty("1")]

Categories