get cultureinfo of the actual system in MVC 3 - c#

I'm doing a Web .Net application, on MVC. I create a controller:
[HttpPost]
public JsonResult Fechas() {
DateTime fecha = DateTime.Now;
List<listas.Ffechas> actualFecha = new List<listas.Ffechas>();
actualFecha.Add(new listas.Ffechas( fecha.Year.ToString(),
fecha.Month.ToString(),
fecha.Hour.ToString(),
fecha.Minute.ToString(),
fecha.Second.ToString(),
fecha.Millisecond.ToString()
));
return Json(new { actualFecha, JsonRequestBehavior.DenyGet });
}
This controller its based on a List Model:
public class Ffechas {
public string FYear { get; set; }
public string FMonth { get; set; }
public string FHour { get; set; }
public string FMinute { get; set; }
public string FSecond {get;set;}
public string FMiliseconds {get;set;}
public Ffechas(string CYear,string CMonth, string CHour, string CMinute, string CSecond, string CMiliseconds) {
FYear = CYear;
FMonth = CMonth;
FHour = CHour;
FMinute = CMinute;
FSecond = CSecond;
FMiliseconds = CMiliseconds;
}
}
And send the information in Json format.
The point here is, How I can detect the actual culture or region language of the system and apply to my fecha Datetime, example:
if the actual system culture is ("en-us") the date is sended on that format or if the actual system culture is ("es-mx") the date is sended on that form.
I dont have problems with list or something like that, my issue is detect the culture system status and with this I can send through json the correct format. thanks for your help.

Related

pass model data between razor pages

I try pass model data between two Razor pages, data is not string or bool or int
data that i want pass to second page is a model,
i do taht with this way,
public class AskLibrarian
{
public int Id { get; set; }
public string FullName { get; set; }
public string Subject { get; set; }
public string Email { get; set; }
public string Text { get; set; }
public string UserIp { get; set; }
public DateTime CreateDate { get; set; }
public bool ReadIt { get; set; }
public bool Answer { get; set; }
public string reciptCode { get; set; }
}
And on Get method pass data with this way:
[BindProperty]
public AskLibrarian AskLibrarian { get; set; }
public async Task<IActionResult> OnPostQuestionAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
AskLibrarian.Answer = false;
AskLibrarian.CreateDate = DateTime.Now;
AskLibrarian.ReadIt = false;
string userIp = $"{ HttpContext.Connection.RemoteIpAddress}";
if (string.IsNullOrEmpty(userIp))
{
userIp = "127.0.0.1";
}
AskLibrarian.UserIp = userIp;
string rndNuber = Business.RandomNumberForQuestion.randCode;
AskLibrarian.reciptCode = rndNuber;
await _emailSenderService.SendEmailAsync(AskLibrarian.Email, AskLibrarian.FullName, rndNuber);
_context.AskLibrarians.Add(AskLibrarian);
await _context.SaveChangesAsync();
Message = "your message sended";
//return RedirectToPage("/Subfolder/Index", new { SFId = 7 });
return RedirectToPage("/Subfolder/AskLibrarianCode", new { asklib = AskLibrarian });
}
In post method in second page, like to get data on this way:
public void OnGet(Model.AskLibrarian asklib)
{
askLibrarianVM = new AskLibrarianVM
{
Answered = false,
CreateDate = asklib.CreateDate,
LastUpdate = asklib.CreateDate,
RandomeCode = asklib.reciptCode,
Status = false,
};
}
But asklib is empty ,I set a breakpoint at end of Get method and I sow that asklib if filled with valid values but in post method when i try to get data, asklib is empty
what is my mistake
The simple answer was :
return RedirectToPage("/Subfolder/AskLibrarianCode", AskLibrarian );
My mistake was
... new{asklib = AskLibrarian});
After more than two hours
The lowest friction way is to return View("SomeViewForTheModel", AskLibrarian) and do your thing with a completely different view. Your second page controller action really isn't doing anything.
Otherwise, you'll have to save the ID associated with your AskLibrarian object, presumably in a database, and then look it up on the second page either by putting the ID in the URL path (be sure to validate the user should see it!), or by looking up in the database whatever is owned by the user.

ASP.NET JsonResult results in 500 server error when two Json objects contain the same base64 encoded string

I'm returning a serialized list of models to the client. In these models there is a property named "DocumentBody" which is an encoded string of a file (usually an image).
Everything functions as intended, until I upload a duplicate file to the data that is fetched in GetAnnotationsForEntity(). Once I try to return the Json that contains the two objects with the same "DocumentBody" I get a 500 server error in my Chrome console and no additional information. I've stepped through the controller action and no exceptions are thrown.
What is it I don't understand about Json that would make it fail in this instance? As soon as the object with the duplicate "DocumentBody" is removed from the list, everything functions successfully once again. I've experimented with different values for all the other fields with no ill effects. I've also looked at the Json string in a JSON viewer and the structure seems to be as desired as well.
Here is the related code:
Post:
axios.post('../GetAnnotationsForEntity', {
entityType: this.state.entityType,
entityId: this.props.entityId
}, { headers: { 'X-Requested-With': 'XMLHttpRequest' } }).then((result) => {
if (result.status == 200) {
//parse the json data into a list
}
}
});
Controller Action:
public ActionResult GetAnnotationsForEntity(EntityType entityType, string entityId)
{
List<AnnotationModel> annotationsForEntity = new List<AnnotationModel>();
if (!string.IsNullOrWhiteSpace(entityId))
{
DynamicsHelper.GetAnnotationsForEntity(entityType, new Guid(entityId))?.ToList()?.ForEach(a =>
{
annotationsForEntity.Add(new AnnotationModel(a.Id, GetOffsetDateTimeForTimeZone(a.ModifiedOn), a.FileName, a.Subject, a.DocumentBody, a.NoteText, GetCulture()));
});
}
string serializedAnnotations = Newtonsoft.Json.JsonConvert.SerializeObject(annotationsForEntity);
return Json(serializedAnnotations);
}
AnnotationModel:
public class AnnotationModel
{
private readonly CultureInfo _cultureInfo;
private readonly DateTime? _modifiedOn;
public Guid Id { get; set; }
public string ModifiedOn => _modifiedOn.HasValue ? _modifiedOn.Value.ToString(_cultureInfo) : "";
public string FileName { get; set; }
public string Subject { get; set; }
public string DocumentBody { get; set; }
public string NoteText { get; set; }
public AnnotationModel(Guid id, DateTime? modifiedOn, string fileName, string subject, string documentBody, string noteText, CultureInfo cultureInfo)
{
Id = id;
_modifiedOn = modifiedOn;
FileName = fileName;
Subject = subject;
DocumentBody = documentBody;
NoteText = noteText;
_cultureInfo = cultureInfo;
}
}
Any insight would be appreciated. In the meantime, I have gotten around this issue by not returning Models and Json objects with "DocumentBody" at all, but that's not a solution I'm comfortable with without knowing why it was failing in the first place.

How to query Entity Framework database for records between 2 dates, then return that information for display on screen

I have an Entity MVC app with a code-first database. I need to produce a search box to search between 2 dates and return the records between those dates.
I will call the method with jQuery/ajax and render the results in a table.
I've tried writing an API, with no success. I am not even sure if this is the correct way to go about it?
namespace Areometrex_Leaflet.Models
{
[Table ("Flight_Lines")]
public class Flight_line
{
[Key]
public string Swath_name { get; set; }
public string Flight_name { get; set; }
public string Swath_record { get; set; }
public string Flight_date { get; set; }
public decimal Start_lat { get; set; }
public decimal Start_long { get; set; }
public decimal End_lat { get; set; }
public decimal End_long { get; set; }
public decimal Altitude { get; set; }
public DateTime Time_start { get; set; }
public DateTime Time_end { get; set; }
public string Sensor { get; set; }
}
public class FlightLineContext : DbContext
{
public DbSet<Flight_line> Flight_Lines { get; set; }
}
}
This is my model that holds the objects in the database. I need to search the "Flight_date" property, that is held in my DB in this following format as an "nvarchar" :
17/11/2018 11:09:18 PM
My current API looks something like this:
[HttpPost]
public IEnumerable<Flight_line> SearchFlight_Line()
{
string start, end;
var rc = RequestContext;
var data = rc.Url.Request.GetQueryNameValuePairs();
{
start = data.FirstOrDefault().Value ?? string.Empty;
end = data.LastOrDefault().Value ?? string.Empty;
}
//db format: 17/11/2018 11:22:56 PM
var s = DateTime.Parse(start);
var flightSearch = new List<Flight_line>();
using (_context)
{
var sql = $"SELECT * FROM Flight_Lines WHERE Flight_Date BETWEEN '{start}' AND '{end}'";
flightSearch = _context.Flight_Lines.SqlQuery(sql).ToList<Flight_line>();
}
return flightSearch;
}
Ideally, I want to call this API with jquery/Ajax and return results to be displayed in an MVC view. My guess is that this is dead easy, but I am only learning and I'm running out of ideas. I would have thought this was really simple, but I am struggling to find the answers I am looking for online, which leads me to believe perhaps I am doing it wrong?
First of all, don't save dates as string in your database, you will just have problems later on.
Instead of:
public string Flight_date { get; set; }
Set it up as DateTime:
public DateTime Flight_date { get; set; }
As far as the query for searching flights go, you can try this. This will return a list of "Flight_line" objects which you can then return wherever you need.
DateTime start = DateTime.Now;
DateTime end = DateTime.Now.AddDays(7);
var flights = _context.Flight_line.Where(f => f.Flight_date >= start && f.Flight_date <= end).ToList();

Asp.NetCore API Controller not getting Data from Json

I have 2 applications, one which posts data to another. When I run the first application the post method in the controller executes but the model or ObjavaDto (objaveList) can't be found so it's null. When I copy-paste the json from var json into Postman everything works. What am I missing?
var json = new JavaScriptSerializer().Serialize(objaveList[2]);
I used [2] just for simplicity reasons because there are a lot of them
string url = "http://localhost:61837/api/Objave";
string result;
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/json");
result = client.UploadString(url, "POST", json);
}
2nd application Controller
namespace StecajeviInfo.Controllers.Api
{
[Route("api/[controller]")]
public class ObjaveController : Controller
{
[HttpPost]
public void Post([FromBody]ObjavaDto objaveList)
{
}
}
}
public class ObjavaDto
{
public string OznakaSpisa { get; set; }
public string NazivOtpravka { get; set; }
public string NazivStecajnogDuznika { get; set; }
public string PrebivalisteStecajnogDuznika { get; set; }
public string SjedisteStecajnogDuznika { get; set; }
public string OIBStecajnogDuznika { get; set; }
public string OglasSeOdnosiNa { get; set; }
public DateTime DatumObjave { get; set; }
public string OibPrimatelja { get; set; }
public string Dokument { get; set; }
}
Sent data looks like this
{
"OznakaSpisa":"St-6721/2015",
"NazivOtpravka":"Rješenje - otvaranje stečajnog postupka St-6721/2015-7",
"NazivStecajnogDuznika":"RAIN AIR d.o.o.",
"PrebivalisteStecajnogDuznika":"Savska 144/A, 10000, Zagreb",
"SjedisteStecajnogDuznika":"",
"OIBStecajnogDuznika":‌​"37144498637",
"Oglas‌​SeOdnosiNa":"Missing Oib",
"DatumObjave":"\/Date(1501106400000)\/",
"OibPrimatelja"‌​:"37144498637",
"Doku‌​ment":"e-oglasna.pra‌​vosudje.hr/sites/def‌​ault/files/ts-zg-st/‌​…;"
}
Thank you all for your replies, you have been very helpful and gave me an idea how to test. I tested with commenting out properties and I found out it's because of the special characters in Naziv otpravka ("Rješenje" and "stečajnog") which are luckily present only in that property.
I found that this solved the problem https://stackoverflow.com/a/12081747/6231007
client.Headers["Content-Type"] = "application/json; charset=utf-8";
client.UploadDataAsync(new Uri(url), "POST",
Encoding.UTF8.GetBytes(json));
Datetime is problematic. Make it nullable (DateTime?) and test with that. You'll probably get all other properties filled and datetime will stay null. If that's the problem, make sure your client sends datetime format that your model binder understands.

How to deserialize JSON date time from MongoDB to C# class

I'm using c# driver to interact with mongoDB.
I have a class that I created and which I populate with the data I get from mongoDB.
One of the properties in that class is DateTime.
The value I get from mongo is /\Date(number)/. Which is ok because this is what I'm suppose to return to the client.
The value that I get from mongo after I retrieve the data is ISODate(some number).
I get an exception: "Invalid JSON primitive: ISODate".
How can I configure mongoDB to save the DateTime like I got it i.e. /\Date(number)/?
Sorry L.B - I didn't noticed your answer but went straight to the answer I was given.
Here's the class I'm trying to deserialize:
public class EventDate
{
public EventDate()
{
}
public int? VenueConfigID { get; set; }
public string Category { get; set; }
public DateTime DateAndTime { get; set; }
public string DisplayDate { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string ShortNote { get; set; }
public string Home { get; set; }
public int? ID { get; set; }
public string Name { get; set; }
}
Here's how I deserialize it:
mongo = MongoServer.Create();
mongo.Connect();
db = mongo.GetDatabase("productionDB");
var col = db.GetCollection<BsonDocument>("eventDates");
var query = Query<PerformerDates>.EQ(ev => ev.PerformerID, performerId);
//MongoCursor<BsonDocument> performer = col.Find(query);
MongoCursor<BsonDocument> performer = col.FindAll();
JavaScriptSerializer js = new JavaScriptSerializer();
List<EventDate> finalMatchedDates = new List<EventDate>();
foreach (var p in performer)
{
//System.Threading.Tasks.Task<EventDate[]> obj2 = JsonConvert.DeserializeObjectAsync<EventDate[]>(p.Elements.ToList()[3].Value.ToString());
EventDate[] obj3 = JsonConvert.DeserializeObject<EventDate[]>(p.Elements.ToList()[3].Value.ToString());
}
mongo.Disconnect();
Solved!!
Eventually I solved it. I used a string instead of a DateTime. When I get it from the DB, I convert it to a DateTime and when I sent it back to the client I serialize it with the format of: /\Date()/
Just use BsonSerializer.Deserialize method.
MongoDB's serializer has a much higher performance over NewtonSoft's Json.Net or Microsoft's DataContractSerializer.
Very common occurring problem! One solution is to use JSON.NET.
See this answer for more help. Although you might be confused with JSON DateTime object but don't worry. It will work!
string json; // Assign JSON here.
var v = Newtonsoft.Json.JsonConvert.DeserializeObjectAsync<T>(json);

Categories

Resources