Internal 500 Error with DateTime set in Model - c#

Hey I'm getting a weird internal 500 error. I narrowed it down to finding that the DateTime structure gives me this, but I'm having a hard time understanding why. So I am using asp.net web api and currently storing info as so.
public void StoreFacebookInfo(string accessToken, IdentityUser user)
{
//Retrieve Facebook Mutual Friends
dynamic myMutualFriends = fb.Get(curFbId + "?fields=context.fields(mutual_friends)");
if (myMutualFriends.context.mutual_friends.data != null)
{
foreach (var item in myMutualFriends.context.mutual_friends.data)
{
var f = JsonConvert.DeserializeObject<mutualFriends>(item.ToString());
profileInfo.mutualFriendsList.Add(f);
}
}
//Save all information retrieved from FB into a db
profileInfo.externalId = myInfo.id;
profileInfo.name = myInfo.name;
profileInfo.firstName = firstname.first_name;
profileInfo.lastName = lastname.last_name;
profileInfo.link = link.link;
profileInfo.gender = gender.gender;
profileInfo.imageURL = "https://graph.facebook.com/" + myInfo.id + "/picture?type=large";
profileInfo.locale = locale.locale;
profileInfo.UserId = user.Id;
db.UserInfoes.Add(profileInfo);
db.SaveChanges();
}
}
As you can see, everything looks fine. In my model, I have the following:
public class UserInfo
{
public UserInfo()
{
this.friendsList = new List<friends>();
this.mutualFriendsList = new List<mutualFriends>();
}
[Key]
public int id { get; set; }
public string externalId { get; set; }
public string name { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string link { get; set; }
public string gender { get; set; }
public string imageURL { get; set; }
public string locale { get; set; }
public string language { get; set; }
public string travellevel { get; set; }
public DateTime birthdate { get; set; }
[ForeignKey("UserId")]
public IdentityUser User { get; set; }
public string UserId { get; set; }
public List<mutualFriends> mutualFriendsList { get; set; }
public List<friends> friendsList { get; set; }
}
When I am using DateTime for the birthdate, when it gets to db.saveChanges(), the code runs into an internal 500 error. When I change this DateTime into string the code runs fine and I am able to save the information. This is strange to me because when I run it on another computer, it works completely fine with the DateTime and not changing it to string.
It'd be great if you could explain this error a bit. Thanks for any help.

I think that your problem is the language culture of your client who is different of your server and which badly parse the DateTime (ie: dd/MM/yyyy vs MM/dd/yyyy).
Try to serialize and parse the DateTime in the same format.

Related

How do I convert a JSON DateTime format to a C# DateTime format from an API call

I'm currently building a project that retrieves API data and saves it into a database. Everything is working fine except for the DateTime values in the API. I have a class that uses RestSharp to obtain the API data then it uses NewtonSoft.Json to derserialize the API data into a JSON format which is then stored into a temporary DTO class file. Here is the API method.
public static void getAllRequestData()
{
var client = new RestClient("[My API URL]");
var request = new RestRequest();
var response = client.Execute(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string rawResponse = response.Content;
AllRequests.Rootobject result = JsonConvert.DeserializeObject<AllRequests.Rootobject>(rawResponse);
}
}
Now here is the DTO file (AllRequests) that will temporarily store the Converted JSON data.
public class AllRequests
{
public class Rootobject
{
public Operation Operation { get; set; }
}
public class Operation
{
public Result Result { get; set; }
public Detail[] Details { get; set; }
}
public class Result
{
public string Message { get; set; }
public string Status { get; set; }
}
public class Detail
{
[Key]
public int Id { get; set; }
public string Requester { get; set; }
public string WorkOrderId { get; set; }
public string AccountName { get; set; }
public string CreatedBy { get; set; }
public string Subject { get; set; }
public string Technician { get; set; }
public string IsOverDue { get; set; }
public string DueByTime { get; set; }
public string Priority { get; set; }
public string CreatedTime { get; set; }
public string IgnoreRequest { get; set; }
public string Status { get; set; }
}
}
The lines of code in Details that I want to be DateTime formats are "DueByTime" and "CreatedTime" instead of being String values. Currently they're only holding JSON format DateTime values in a String such as "1477394860065".
I've tried making "public string CreatedTime { get; set; }" to "public DateTime CreatedTime { get; set; }" However that only returned an error since it's JSON format. How could I rectify this issue so that it's stored in the DTO correctly in a DateTime format? Because ideally I want to scaffold this class file into a table so it can hold data in a database.
For more context to this, here's what I want rectified in my Database.
I want there to be a DateTime shown instead of a long list of numbers like there is here under Createby and DueBy.
Any help would be appreciated.
[EDIT] added the unix time format compliance[/EDIT]
Just putting in code what #Fildor said
public long CreatedTime { get; set; }
[JsonIgnore] // will ignore the property below when serializing/deserializing
public DateTimeOffset CreatedTimeDate {
// Don't need a setter as the value is directly get from CreatedTime property
get {
return DateTimeOffset.FromUnixTimeMilliseconds(CreatedTime);
}
}
Used also this answer to convert to DateTime as asked, using the local time.
Here is how you convert to DateTime if you don't need the offset : https://learn.microsoft.com/fr-fr/dotnet/standard/datetime/converting-between-datetime-and-offset

How to fix Error while converting Json string to Object C#?

Im using C# to get a file from my local pc data folder.
This is the code to do that:
var _rootpath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + directory;
var ENC = new Encryption();
var s = File.ReadAllText(_rootpath + "json");
var x = ENC.RijndaelDecrypt(s, App.EncryptionPassword);
This works fine so far.
x got now this value (so this is the string I want to convert to an object) :
{
"items":[
{
"id":194,
"guid":"594394",
"name":"Test",
"connectorId":248,
"customerId":1,
"customerName":"company",
"connectorTypeId":10,
"connectorTypeIcon":null,
"connectorCategoryId":1,
"vendor":"FasterForward",
"isActive":true,
"shopId":null,
"sku":null,
"workerBearerToken":"",
"workerUri":"http://localhost:9000"
}
],
"responseStatus":null
}
After this I want to convert this to an object
var _response = JsonConvert.DeserializeObject<CrmJobListResponse>(x);
This line gives an error:
{"Error converting value x to type 'ServiceModel.CrmJobListResponse'. Path '', line 1, position 991."}
ServiceModel.CrmJobListResponse:
namespace ServiceModel
{
public class CrmJobListResponse : ResponseBase
{
public CrmJobListResponse();
public List<CrmJob> Items { get; set; }
}
}
CrmJob class:
namespace ServiceModel.DTO
{
public class CrmJob : IHasId<int>
{
public CrmJob();
[Ignore]
public string WorkerBearerToken { get; set; }
[PropertyValue("sku")]
public string SKU { get; set; }
[PropertyValue("shop_id")]
public string ShopId { get; set; }
public bool IsActive { get; set; }
public string Vendor { get; set; }
public int ConnectorCategoryId { get; set; }
[Ignore]
public string WorkerRefreshToken { get; set; }
public string ConnectorTypeIcon { get; set; }
public string CustomerName { get; set; }
public int CustomerId { get; set; }
public int ConnectorId { get; set; }
[PropertyValue("jobname")]
public string Name { get; set; }
public string Guid { get; set; }
public int Id { get; set; }
public int ConnectorTypeId { get; set; }
[Ignore]
public string WorkerUri { get; set; }
}
}
Does anyone know why it can't convert my Json string to an object?
I didn't made the code myself, but I don't see why It should go wrong...
If you have a hard time creating DTOs you have some tools that may assist you https://app.quicktype.io/
You can also use paste special in VS to paste a Json directy to a C# class.
This also shows you if you malformed a Json.

Combining data from 2 databases in MVC

I am fairly new to asp.net mvc and I currently have an application that shows a number of errors. I have 2 pages that contain Application Errors and Log Errors. The data comes from 2 different databases but I am wanting to display the data from both databases on one page.
The tables have headings with different names that mean the same thing e.g. ApplicationName in the Application Database is the same thing as LogName in the Log Database.
Below is a small example of what I currently have and an example of what I am wanting.
Current
Application Errors
ID ApplicationName ApplicationMessage ApplicationDate
1 Something Hello World 01/01/2015
2 Something Else Another Message 03/01/2015
Log Errors
ID LogName LogMessage LogDate
1 Some Log A log message 02/01/2015
2 Another Log Another Log Message 04/01/2015
What I Want
Internal Errors
ID Name Message Date
1 Something Hello World 01/01/2015
2 Some Log A log message 02/01/2015
3 Something Else Another Message 03/01/2015
4 Another Log Another Log Message 04/01/2015
At the minute, I have 2 separate models for each database but I think I need to merge both models into one model that combines them both but I am unsure on how to do this. How would I be able to merge both data sources together to display the data within the same page?
Current Models
Application
[Table("ELMAH_Error")]
public class ElmahError
{
[Key]
public System.Guid ErrorId { get; set; }
public System.String Application { get; set; }
public System.String Host { get; set; }
public System.String Type { get; set; }
public System.String Source { get; set; }
public System.String Message { get; set; }
public System.String User { get; set; }
public System.Int32 StatusCode { get; set; }
public System.DateTime TimeUtc { get; set; }
public System.Int32 Sequence { get; set; }
public System.String AllXml { get; set; }
}
Log
[Table("LogEntry")]
public class LogEntry
{
[Key]
public Int64 ID { get; set; }
public DateTime LogDate { get; set; }
public Int16 Priority { get; set; }
public string SourceClass { get; set; }
public string Category { get; set; }
public string Message { get; set; }
public string UserID { get; set; }
public string ProcessID { get; set; }
}
From the models, there are a number of fields that I would like to merge as well as fields that are not similar that I would also like to include. The model below shows exactly what I want but I just don't know how to implement it.
Internal Errors
public class InternalErrors
{
public string Id { get; set; } //L:ID && E:ErrorId
public int Priority { get; set; } //L:Priority
public string Application { get; set; } //L:SourceClass && E:Application
public string Message { get; set; } //L:Message && E:Message
public string Type { get; set; } //L:Category && E:Type
public string User { get; set; } //L:UserID && E:User
public string ProcessID { get; set; } //L:ProcessID
public DateTime Date { get; set; } //L:LogDate && E:TimeUtc
public int StatusCode { get; set; } //E:StatusCode
public string AllXml { get; set; } //E:AllXml
public int Sequence { get; set; } //E:Sequence
public int ErrorCount { get; set; } //E:ErrorCount
}
I hope this is enough information for you to provide an answer, if you need anything else, let me know.
Thanks in advance
if what you want is this
Internal Errors
ID Name Message Date
1 Something Hello World 01/01/2015
2 Some Log A log message 02/01/2015
3 Something Else Another Message 03/01/2015
4 Another Log Another Log Message 04/01/2015
then create a class with name InternalErrors as follows.
public class InternalErrors
{
public int ID;
public string Name;
public string Message;
public DateTime Date;
}
Now you can write a Linq Query as follows to get data from Application Errors and Log Errors and Perform union on it.
var AppErrors=from AE in _db.ApplicationErrors select AE;
var LogErrors=from LE in _dc.LogErrors select LE;
var internerrors=AppErrors.Union(LogErrors);
var InternalErrors=(from ie in internerrors select new InternalErrors()
{
ID=ie.ID,
Message=ie.ApplicationMessage,
Name=ie.ApplicationName,
Date=ie.ApplicationDate
}).ToList();
The viewmodel approach from MRebati is the best solution.
I often find it usefull to have a base class and different implementations:
public abstract class ErrorViewModel
{
public abstract int Id { get; }
public abstract string Name { get; }
}
public class ElmahErrorViewModel
{
public ElmahErrorViewModel(ElmahError instance)
{
this.Instance = instance;
}
public ElmahError Instance { get; private set; }
public int Id { get { return Instance.ErrorId; } }
public string Name { get { return instance.Appication; } }
}
that way you can create a List<ErrorViewModel> and add entries with
var items = from e in context.ElmahErrors
select new ElmahErrorViewModel(e);
list.AddRange(items);
var items2 = from l in context.LogEntrys
select new LogEntryViewModel(l);
list.AddRange(items2);
This is very usefull since you hide the details but you still can seprate the list and access the underlying object with
var elmahErrors = items.OfType<ElmahErrorViewModel>().Select(x => x.Instance);
There are many ways to provide data from the models to the View.
One is the ViewModel. It must contain the data you want to send to view. Look at this:
using System;
public class ErrorViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Message { get; set; }
public DateTime Date { get; set; }
}
And in the Controller you need to Create a list of this ViewModel and populate it with your data.
you can use linq
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var elmahErrorList = new List<ElmahError>{
new ElmahError{ ErrorId = Guid.NewGuid(), Application = "Something",Message = "Hello World" , TimeUtc = DateTime.Now },
new ElmahError{ ErrorId = Guid.NewGuid(), Application = "Something Else",Message = "Another Message" , TimeUtc = DateTime.Now }
};
var logEntryList = new List<LogEntry>{
new LogEntry{ ID = 1, SourceClass = "Something",Message = "Hello World" , LogDate = DateTime.Now },
new LogEntry{ ID = 1, SourceClass = "Something Else",Message = "Another Message" , LogDate = DateTime.Now }
};
var internalErrorsList = new List<InternalErrors>();
var elmahErrorListinternalErrorses = elmahErrorList.Select(e => new InternalErrors
{
Id = e.ErrorId.ToString(),
Application = e.Application,
Message = e.Message,
Type = e.Type,
User = e.User,
Date = e.TimeUtc,
StatusCode = e.StatusCode,
AllXml = e.AllXml,
Sequence = e.Sequence
});
internalErrorsList.AddRange(elmahErrorListinternalErrorses);
var elmahErrorListlogEntryLists = logEntryList.Select(l => new InternalErrors
{
Id = l.ID.ToString(),
Priority = l.Priority,
Application = l.SourceClass,
Message = l.Message,
Type = l.Category,
User = l.UserID,
Date = l.LogDate
});
internalErrorsList.AddRange(elmahErrorListlogEntryLists);
internalErrorsList.ForEach(f =>
{
Console.Write(f.Id); Console.Write("\t");
Console.Write(f.Application);Console.Write("\t");
Console.Write(f.Message);Console.Write("\t");
Console.Write(f.Date);Console.Write("\t");
Console.WriteLine();
});
}
public class InternalErrors
{
public string Id { get; set; } //L:ID && E:ErrorId
public int Priority { get; set; } //L:Priority
public string Application { get; set; } //L:SourceClass && E:Application
public string Message { get; set; } //L:Message && E:Message
public string Type { get; set; } //L:Category && E:Type
public string User { get; set; } //L:UserID && E:User
public string ProcessID { get; set; } //L:ProcessID
public DateTime Date { get; set; } //L:LogDate && E:TimeUtc
public int StatusCode { get; set; } //E:StatusCode
public string AllXml { get; set; } //E:AllXml
public int Sequence { get; set; } //E:Sequence
public int ErrorCount { get; set; } //E:ErrorCount
}
public class ElmahError
{
public System.Guid ErrorId { get; set; }
public System.String Application { get; set; }
public System.String Host { get; set; }
public System.String Type { get; set; }
public System.String Source { get; set; }
public System.String Message { get; set; }
public System.String User { get; set; }
public System.Int32 StatusCode { get; set; }
public System.DateTime TimeUtc { get; set; }
public System.Int32 Sequence { get; set; }
public System.String AllXml { get; set; }
}
public class LogEntry
{
public Int64 ID { get; set; }
public DateTime LogDate { get; set; }
public Int16 Priority { get; set; }
public string SourceClass { get; set; }
public string Category { get; set; }
public string Message { get; set; }
public string UserID { get; set; }
public string ProcessID { get; set; }
}
}
Demo : https://dotnetfiddle.net/mrWGDn

Mobile Azure Service C# .NET Backend PATCH not updating

I've created a simple .NET backend mobile azure service in C#. I have the mobile service up and running (all it's doing currently is working with your normal CRUD on a single table). The problem I'm having is that the PATCH/UPDATE will not do as it says. I can do everything else I've tried, SELECT, INSERT, DELETE, but I've been unable to update data.
When I debug into the block of code that calls UpdateAsync, the patch.GetEntity()..... always has the values NULL or zeroed out or day one datetimes, like it's not passing along the property values of what I'm trying to update. The only value I ever have is the correct id. Below I tried to strip out some of the code I have, I used some of what was in the first few tutorials on the Azure website.
I have a Data Object:
public class AdminLookupDATA: EntityData
{
public string description { get; set; }
public int lookuptype { get; set; }
public int priority { get; set; }
public bool inactive { get; set; }
public DateTime createdate { get; set; }
public DateTime editdate { get; set; }
}
I have a DTO:
public class AdminLookupDTO
{
public string id { get; set; }
public string description { get; set; }
public int lookuptype { get; set; }
public int priority { get; set; }
public bool inactive { get; set; }
public DateTime createdate { get; set; }
public DateTime editdate { get; set; }
}
I have a Model:
public class AdminLookupModel
{
public string Id { get; set; }
public string description { get; set; }
public int lookuptype { get; set; }
public int priority { get; set; }
public bool inactive { get; set; }
public DateTime createdate { get; set; }
public DateTime editdate { get; set; }
}
My PATCH inside my controller:
public Task<AdminLookupDATA> PatchAdminLookupDATA(string id, Delta<AdminLookupDATA> patch)
{
return UpdateAsync(id, patch);
}
Also, I have the same issue if I try to run the PATCH function directly from the browser in the "try it out" section, so it's something I have configured wrong within the service project itself. Any suggestions would be greatly appreciated.
Thanks,
Rob
Your property names must start with a capital letter.
Otherwise configure the CamelCasePropertyNamesContractResolver as indicated here:
http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx
code snippet
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

Reportviewer not displaying data from object

I have read several questions and answers on this topic, it seems to be a fairly common topic, but none have so far been able to help me.
I am using Visual Studio 2013 and entity framework and trying to create a local report from an object and display it in the reportviewer.
When I run it the report headers show but no data despite the fact that my GetConstraints() method is called and runs without a problem.
The model for the data has been kept fairly simple:
public class ConstraintDataModel
{
public string name { get; set; }
public int interval { get; set; }
public string complianceEntity { get; set; }
public string inspectionEntity { get; set; }
public string nominalValue { get; set; }
public int taskID { get; set; }
public string installations { get; set; }
public int groupTask { get; set; }
public string lastInspectionDate { get; set; }
public string nextInspectionDate { get; set; }
public int missed { get; set; }
public string rating { get; set; }
}
As has the method for returning it:
public static List<ConstraintDataModel> GetConstraints()
{
List<ConstraintDataModel> constraintList = new List<ConstraintDataModel>();
List<ICMConstraint> constraints = (List<ICMConstraint>)ctx.ICMConstraints.Where(cust => cust.CustomerID.Equals(1001)).ToList();
foreach (ICMConstraint constraint in constraints)
{
ConstraintDataModel constraintsModel = new ConstraintDataModel();
constraintsModel.taskID = constraint.ConstraintID;
constraintsModel.name = constraint.Name;
constraintsModel.complianceEntity = GetEntityName(constraint.ComplianceEntityID);
constraintsModel.inspectionEntity = GetEntityName(constraint.InspectionEntityID);
constraintsModel.installations = GetInstallations(constraint.ConstraintID);
constraintsModel.interval = constraint.Interval;
constraintsModel.nextInspectionDate = constraint.NextInspectionDate.ToShortDateString();
constraintsModel.missed = constraint.MissedInspections;
constraintsModel.nominalValue = constraint.NominalValue;
constraintsModel.rating = GetConstraintRating(constraint.ConstraintID);
}
return constraintList;
}
I have followed a few tutorials and haven't deviated from them. I have also tried explicitly binding the data on Page_Load but that doesn't help.
I am not sure what other code to post so if anything else is need just say.
Don't you need to add the object to the list you are returning:
}
return constraintList;
to this:
constraintList.Add(constraintsModel);
}
return constraintList;

Categories

Resources