I have a student
using Newtonsoft.Json;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace CheckPropertyAttributeClass.Models
{
public interface IRequestBody
{
}
public class Student: IRequestBody
{
public Student()
{
}
[JsonConverter(typeof(ESBJsonConverter), "NonEmptyString=>1313")]
public List<Student> Students { get; set; }
public List<Teacher> Teachers { get; set; }
[Newtonsoft.Json.JsonConverter(typeof(ESBJsonConverter), "range(1::100)=>6; nonemptystring=>1313;length(:16)=>1114")]
public int studentid { get; set; }
[Required]
[Newtonsoft.Json.JsonConverter(typeof(ESBJsonConverter), "range(18::29)=>6; nonemptystring=>1313;length(:16)=>1114")]
public string studentname { get; set; }
[Range(10, 20)]
public int age { get; set; }
[JsonProperty(Required = Required.Always)]
[JsonConverter(typeof(ESBJsonConverter), "NonEmptyString=>3064;")]
public string iban { get; set; }
//[JsonProperty(Required = Required.Always)]
//[JsonConverter(typeof(ESBJsonConverter), "Length(1:16)=>1194;")]
//public long Amount { get; set; }
public List<long> Amounts { get; set; }
//[JsonProperty(Required = Required.Always)]
//[JsonConverter(typeof(ESBJsonConverter), "NumericString=>1194;NonEmptyString=>1313;Length(8:8)=>1114;PDateTime(yyyyMMdd)=>1207")]
//public string DueDate { get; set; }
}
public class Teacher
{
[Required]
[JsonConverter(typeof(ESBJsonConverter), "range(18::29)=>6; nonemptystring=>1313;length(:16)=>1114")]
public string Teachername { get; set; }
}
}
and I have another method like this:
[HttpPost]
public void GetClassType([FromForm] FileUpload postedFile)
{
if (postedFile != null)
{
postedFile.FormFile.ContentType.ToLower();
var result = new StringBuilder();
using (var reader = new StreamReader(postedFile.FormFile.OpenReadStream()))
{
while (reader.Peek() >= 0)
result.AppendLine(reader.ReadLine());
}
}
}
the user upload the student.cs file and through GetClassType method I want to detect Just all type which in this file and convert the to list of objects.furthermore more I receive student.cs file from Iform file and read it through StreamReader so I have a text file but I don't know how to extract classes form the file.
Related
I am coming with question.
Why my class returns null value?
As You can see on this picture, class is returning null, but fields inside are not null.
This is Post model where I place virtual method to class Category, and the class is null
Why is that happening?
I checked every reference, and it's all good.
This may be caused by Windows Update or IIS/VisualStudio?
Please help
Post Model
using System;
using System.Collections.Generic;
namespace collector_forum.Data.Models
{
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime Created { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual Category Category { get; set; }
public virtual IEnumerable<PostReply> Replies { get; set; }
}
}
Category Model:
using System;
using System.Collections.Generic;
namespace collector_forum.Data.Models
{
public class Category
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime Created { get; set; }
public string ImageUrl { get; set; }
public virtual IEnumerable<Post> Posts { get; set; }
}
}
Index and BuildHomeIndex methods from HomeController:
public IActionResult Index()
{
var model = BuildHomeIndexModel();
return View(model);
}
public HomeIndexModel BuildHomeIndexModel()
{
var latestPosts = _postService.GetLatestPosts(10);
var posts = latestPosts.Select(post => new PostListingModel
{
Id = post.Id,
Title = post.Title,
AuthorId = post.User.Id,
AuthorName = post.User.UserName,
AuthorRating = post.User.Rating,
DatePosted = post.Created.ToString(),
RepliesCount = post.Replies.Count(),
Category = GetCategoryListingForPost(post)
});
return new HomeIndexModel
{
LatestPosts = posts,
SearchQuery = ""
};
}
PostListingModel if needed:
using collector_forum.Models.Category;
namespace collector_forum.Models.Post
{
public class PostListingModel
{
public CategoryListingModel Category { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string AuthorName { get; set; }
public int AuthorRating { get; set; }
public string AuthorId { get; set; }
public string DatePosted { get; set; }
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string CategoryImageUrl { get; set; }
public int RepliesCount { get; set; }
}
}
CategoryListingModel if needed too:
using collector_forum.Models.Post;
using System.Collections.Generic;
namespace collector_forum.Models.Category
{
public class CategoryListingModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public int NumberOfPosts { get; set; }
public int NumberOfUsers { get; set; }
public bool HasRecentPost { get; set; }
public PostListingModel Latest { get; set; }
}
}
I have a JSON document and I want to access the details of the STATUS SECTION but it keeps returning null.
JSON Data is as shown:
{
"results":[
{
"messageId":"15712480583306574",
"to":"",
"from":"TestServer",
"sentAt":"2019-10-16T17:47:38.368+0000",
"doneAt":"2019-10-16T17:47:38.370+0000",
"smsCount":1,
"mccMnc":"null",
"price":{
"pricePerMessage":0.0,
"currency":"USD"
},
"status":{
"groupId":5,
"groupName":"REJECTED",
"id":8,
"name":"REJECTED_PREFIX_MISSING",
"description":"Number prefix missing"
},
"error":{
"groupId":0,
"groupName":"OK",
"id":0,
"name":"NO_ERROR",
"description":"No Error",
"permanent":false
}
}
]
}
C# Code is:
string JsonData = response.Content.ToString();
dynamic results = JsonConvert.DeserializeObject<dynamic>(JsonData);
var statuses = results.status;
foreach(var stat in statuses) {
string groupname = stat.groupName.Value;
string name = stat.name.Value;
string description = stat.description.Value;
}
It keeps returning null, How can I access these members? I am using Newtonsoft.
If you want to access the status object property you need to rewrite your whole code.
string JsonData = response.Content.ToString();
var input = JObject.Parse(str);
var results = input["results"].Children();
var status = results.First()["status"];
string groupname = status["groupName"].ToString();
string name = status["name"].ToString();
string description = status["description"].ToString();
Console.WriteLine(groupname);
Console.WriteLine(name);
Console.WriteLine(description);
The result in Console
REJECTED
REJECTED_PREFIX_MISSING
Number prefix missing
But I would rather use concrete class. You need to create multiple classes. Here is good example.
public class Envelope
{
public List<Item> Results { get; set; }
}
public class Item
{
public Status Status { get; set; }
}
public class Status
{
public int GroupId { get; set; }
public string GroupName { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
After that the usage is much simpler.
string JsonData = response.Content.ToString();
MyEnvelope envelope = JsonConvert.DeserializeObject<MyEnvelope>(JsonData);
var status = envelope.results[0].status;
Console.WriteLine(status.GroupName);
Console.WriteLine(status.Name);
Console.WriteLine(status.Description);
Finest Option: Create A model for the JSON.
public class Price
{
public double pricePerMessage { get; set; }
public string currency { get; set; }
}
public class Status
{
public int groupId { get; set; }
public string groupName { get; set; }
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
}
public class Error
{
public int groupId { get; set; }
public string groupName { get; set; }
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public bool permanent { get; set; }
}
public class Result
{
public string messageId { get; set; }
public string to { get; set; }
public string from { get; set; }
public DateTime sentAt { get; set; }
public DateTime doneAt { get; set; }
public int smsCount { get; set; }
public string mccMnc { get; set; }
public Price price { get; set; }
public Status status { get; set; }
public Error error { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
Then do RootObject results = JsonConvert.DeserializeObject<RootObject>(JsonData);
Fair Option: Get the exact JToken you want.
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string jsonData = "{\"results\":[{\"messageId\":\"15712480583306574\",\"to\":\"\",\"from\":\"TestServer\",\"sentAt\":\"2019-10-16T17:47:38.368+0000\",\"doneAt\":\"2019-10-16T17:47:38.370+0000\",\"smsCount\":1,\"mccMnc\":\"null\",\"price\":{\"pricePerMessage\":0.0,\"currency\":\"USD\"},\"status\":{\"groupId\":5,\"groupName\":\"REJECTED\",\"id\":8,\"name\":\"REJECTED_PREFIX_MISSING\",\"description\":\"Number prefix missing\"},\"error\":{\"groupId\":0,\"groupName\":\"OK\",\"id\":0,\"name\":\"NO_ERROR\",\"description\":\"No Error\",\"permanent\":false}}]}";
JObject jObject = JObject.Parse(jsonData);
Console.WriteLine(jObject.SelectToken("results[0].status"));
}
}
I am trying to receive data from the Random User API (https://api.randomuser.me/) with C# (which I am new to). I have a React front end and am able to successfully retrieve and render gender of a person, location of a person. However, I am struggling when it comes to the details that are further nested, such as the first name of a person. My backend code at the moment is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace RandomPersonGenerator.Controllers
{
[Route("api/[controller]")]
public class GeneratorController : Controller
{
[HttpGet("[action]")]
public async Task<IActionResult> Generate()
{
using (var client = new HttpClient())
{
try
{
client.BaseAddress = new Uri("https://api.randomuser.me");
var response = await client.GetAsync("https://api.randomuser.me");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
var rawData = JsonConvert.DeserializeObject<PersonAPIResponse>(stringResult);
return Ok(new
{
Gender = rawData.Results.Select(x => x.Gender)
});
}
catch (HttpRequestException httpRequestException)
{
return BadRequest($"Error generating person: {httpRequestException.Message}");
}
}
}
}
public class PersonAPIResponse
{
public IEnumerable<PersonDescription> Results { get; set; }
}
public class PersonDescription
{
public string Gender { get; set; }
}
}
I have tried to retrieve the first name of a person by adding:
Name = rawData.Results.Select(x => x.Name) and Name = rawData.Results.Select(x => x.Name.First) but this is not retrieving the data. Is anyone able to help me select the first name from the Random User API JSON?
Thank you!
Your problem is that you need to change this line:
var rawData = JsonConvert.DeserializeObject<PersonAPIResponse>(stringResult);
to
RootObject person = JsonConvert.DeserializeObject<RootObject>(stringResult);
You should create a new return type class and map into that, what you want to return.. assigning from person:
public class PersonAPIResponse
{
//.... your own properties
}
Return
return Ok(new PersonAPIResponse
{
Gender = person.results[0].gender, //first result
});
You also need to include the following classes for deserializing the string:
public class Name
{
public string title { get; set; }
public string first { get; set; }
public string last { get; set; }
}
public class Coordinates
{
public string latitude { get; set; }
public string longitude { get; set; }
}
public class Timezone
{
public string offset { get; set; }
public string description { get; set; }
}
public class Location
{
public string street { get; set; }
public string city { get; set; }
public string state { get; set; }
public int postcode { get; set; }
public Coordinates coordinates { get; set; }
public Timezone timezone { get; set; }
}
public class Login
{
public string uuid { get; set; }
public string username { get; set; }
public string password { get; set; }
public string salt { get; set; }
public string md5 { get; set; }
public string sha1 { get; set; }
public string sha256 { get; set; }
}
public class Dob
{
public DateTime date { get; set; }
public int age { get; set; }
}
public class Registered
{
public DateTime date { get; set; }
public int age { get; set; }
}
public class Id
{
public string name { get; set; }
public object value { get; set; }
}
public class Picture
{
public string large { get; set; }
public string medium { get; set; }
public string thumbnail { get; set; }
}
public class Result
{
public string gender { get; set; }
public Name name { get; set; }
public Location location { get; set; }
public string email { get; set; }
public Login login { get; set; }
public Dob dob { get; set; }
public Registered registered { get; set; }
public string phone { get; set; }
public string cell { get; set; }
public Id id { get; set; }
public Picture picture { get; set; }
public string nat { get; set; }
}
public class Info
{
public string seed { get; set; }
public int results { get; set; }
public int page { get; set; }
public string version { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
public Info info { get; set; }
}
{
public class Name
{
public string Title { get; set; }
public string First { get; set; }
public string Last { get; set; }
}
public class Result
{
public Name Name { get; set; }
}
public class Person
{
public List<Result> Results { get; set; }
}
public async Task<Name> GetPersonAsync()
{
HttpClient client = new HttpClient
{
BaseAddress = new Uri("https://api.randomuser.me")
};
HttpResponseMessage response = await client.GetAsync("https://randomuser.me/api/");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
Person root = JsonConvert.DeserializeObject<Person>(stringResult);
Console.WriteLine(root.Results[0].Name.Last);
return root.Results[0].Name;
}
}
I have following sample Json string:
{"Items":[{"Id":"20","CaptureCategoryTypeId":5021,"Name":"24270","Description":"FSH CARRIBEAN CAPTAIN","IsEnabled":true}],"TotalResults":0}
I need to deserialize the same but I don't want to keep my class name as following:
public class Item
{
public string Id { get; set; }
public int CaptureCategoryTypeId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsEnabled { get; set; }
}
public class RootObject
{
public List<Item> Items { get; set; }
public int TotalResults { get; set; }
}
I want to keep custom class name such DataDetails. How that can be achieved in c#?
I don't quite understand what your question is but you can just change the class names to whatever you want. Below is a working example.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string JSONInput = #"{""Items"":[{""Id"":""20"",""CaptureCategoryTypeId"":5021,""Name"":""24270"",""Description"":""FSH CARRIBEAN CAPTAIN"",""IsEnabled"":true}],""TotalResults"":0}";
BlahObject deserializedProduct = JsonConvert.DeserializeObject<BlahObject>(JSONInput);
Console.ReadKey();
}
}
public class DataDetails
{
public string Id { get; set; }
public int CaptureCategoryTypeId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsEnabled { get; set; }
}
public class BlahObject
{
public List<DataDetails> Items { get; set; }
public int TotalResults { get; set; }
}
}
I have multiple tables I need to display in a single view. This seems to be a problem because the view only allows for one model definition from what I can tell. I've tried implementing a workaround solution, but have been unsuccessful.
Specifically, I get the error message: "The model item passed into the dictionary is of type 'System.Data.Entity.DbSet1[BillingApp.Models.HEADER_RECORD]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[BillingApp.Models.tbl1join]'."
The View
#model IEnumerable<BillingApp.Models.tbl1join>
#{
ViewBag.Title = "TABLE 01 DISPLAY";
Layout = "../Shared/Layout2.cshtml";
}
#section featured2 {
<html>
<body>
~excluding tables because there are too many fields~
</body></html>
}
class joining two of the tables (tbl1join.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BillingApp.Models
{
public class tbl1join
{
public HEADER_RECORD HeaderRecord { get; set; }
public HEADER_EXTENSION_RECORD ExtensionRecord { get; set; }
}
}
The Model Definitions:
HEADER_RECORD.cs
namespace BillingApp.Models
{
using System;
using System.Collections.Generic;
public partial class HEADER_RECORD
{
public int HRID { get; set; }
public string TABLE_NUMBER { get; set; }
public string COMPANY { get; set; }
public string STATE_CODE { get; set; }
public string BILL_CODE { get; set; }
public string RECORD_TYPE { get; set; }
public string MASK_EXTENSION_ID { get; set; }
public string OVERPAYMENT_LIMIT { get; set; }
public string UNDERPAYMENT_LIMIT { get; set; }
public string REFUND_ACTION_OVR { get; set; }
public string REFUND_ACTION_PAR { get; set; }
public string REFUND_ACTION_RTN_PRM { get; set; }
public string REFUND_ACTION_CNC { get; set; }
public string EFT_PAC_OPTION { get; set; }
public string EFT_PAC_NOTICE { get; set; }
public string EFT_PAC_NSF_LIMIT { get; set; }
public string PREMIUM_ROUNDING { get; set; }
public string DB_CC_OPTION { get; set; }
public string NSF_CHECK_LIMIT { get; set; }
public string NSF_CHECK_OPTION { get; set; }
public string FIRST_TERM_BILLING { get; set; }
public string CARRY_DATE_OPTION { get; set; }
public string ENDORSEMENT_DAYS { get; set; }
public string DATE_METHOD { get; set; }
public string RENEWAL_OPTION { get; set; }
public string DROP_DAYS { get; set; }
public string MULTI_PAY_IND { get; set; }
public string MINIMUM_INSTALLMENT { get; set; }
public string ENDORSEMENT_ACTION { get; set; }
public string I_OR_S_OPTION_DAYS { get; set; }
public string S_OPTION_PERCENT { get; set; }
public string SERVICE_CHARGE_PREPAID { get; set; }
public string REINSTATE_OPTION { get; set; }
public string CASH_WITH_APPLICATION { get; set; }
public string DB_CC_NOTICE { get; set; }
public string DOWN_PAY_DAYS { get; set; }
public string MONTH_BY_TERM { get; set; }
public string LEAD_MONTHS { get; set; }
public string INITIAL_MONTHS { get; set; }
public string DB_CC_REJECTS { get; set; }
public string RETURN_ENDORSEMENT_OPTION { get; set; }
public string RETURN_SPLIT_OPTION_PERCENT { get; set; }
public string AUTOMATED_REFUND_DAYS { get; set; }
public string RENEWAL_OPTION_BILL_PLAN { get; set; }
public string EFFECTIVE_DATE { get; set; }
public string MISC_DATA { get; set; }
public string MISC_DATA2 { get; set; }
}
}
HEADER_EXTENSION_RECORD.cs
namespace BillingApp.Models
{
using System;
using System.Collections.Generic;
public partial class HEADER_EXTENSION_RECORD
{
public int ERID { get; set; }
public string ETABLE_NUMBER { get; set; }
public string ECOMPANY { get; set; }
public string ESTATE_CODE { get; set; }
public string EBILL_CODE { get; set; }
public string ERECORD_TYPE { get; set; }
public string EMASK_EXTENSION_ID { get; set; }
public string OVERPAYMENT_TOLERANCE_PERCENT { get; set; }
public string UNDERPAYMENT_TOLERANCE_PERCENT { get; set; }
}
}
The Controller (BillingController.cs)
public ActionResult HeaderExtensionRecord()
{
{
return View(db.HEADER_EXTENSION_RECORD);
}
}
public ActionResult HeaderRecordTable1()
{
{
return View(db.HEADER_RECORD);
}
}
Update:
Added tbl1join as the return type in the controller, but gives an error saying it's a type being used as a variable.
public ActionResult HeaderRecordTable1()
{
{
return View(IEnumerable<tbl1join>);
}
}
Wrap it into a ViewModel
public class RecordVM
{
public HEADER_RECORD header { get; set; }
public HEADER_EXTENSION_RECORD ext { get; set; }
}
return View(new RecordVM { header = db.HEADER_RECORD, ext = db.HEADER_EXTENSION_RECORD });
The error message indicates that you are passing in the wrong type, you need to query the database and create the suitable model that your view is expecting. It looks like you are trying to pass 2 models to the view using the view model tbl1join.
You could populate the view model as follows for a specified id value:
public ActionResult ViewModelExtension(int id)
{
var viewModel = new tbl1join();
viewModel.HEADER_RECORD = db.HEADER_RECORD.Where(h => h.id == id).SingleOrDefault;
viewModel.HEADER_EXTENSION_RECORD = db.HEADER_EXTENSION_RECORD.Where(h => h.id == id).SingleOrDefault;
return View(viewModel);
}
I would be surprised if there isn't some relationship between the 2 models. If this was specified within your 2 models then the above could be done differently.