Serialize JSON in ASP.NET - asp.net

I am new in ASP.NET world and I am trying to achieve following.
I need to serialize API of this format
{
"results": {
"profile": {
"firstname": "John,
"lastname": "Newman",
},
"credit": {
"amount": 30
}
}
}
The problem is that I don't know how to model my data. I need a results object, which contains 2 other objects (profile and credit). You can see some sample code below.
public class Results
{
public class Data {
public Profile profile { get; set; }
public Credit credit {get; set; }
}
public class Profile {
public String firstname {get; set; }
public String lastname { get; set; }
}
public class Credit {
public int amount { get; set; }
}
}
static void Main(string[] args)
{
Results results= new Results
{
Data = new Data{
Profile = new Profile {
firstname = "John",
lastname = "Newman"
},
Credit = new Credit {
balance = "30"
}
}
};
string json = JsonConvert.SerializeObject(results);
Console.WriteLine(json);
}
The error I get is "Member Data cannot be initialized. It is not a field or property. What am I doing wrong?

Try this instead:
public class Profile
{
public String firstname { get; set; }
public String lastname { get; set; }
}
public class Credit
{
public int amount { get; set; }
}
public class Result
{
public Profile profile { get; set; }
public Credit credit { get; set; }
}
public class Wrapper
{
public Result results { get; set; }
}
static void Main(string[] args)
{
var wrapper = new Wrapper
{
results = new Result
{
profile = new Profile
{
firstname = "John",
lastname = "Newman"
},
credit = new Credit
{
amount = 30
}
}
};
string json = JsonConvert.SerializeObject(wrapper);
Console.WriteLine(json);
}

Try this :
static void Main(string[]args) {
Base results = new Base() {
Results = new Results() {
profile = new Profile() {
firstname = "John",
lastname = "Newman"
},
credit = new Credit() {
amount = 30
}
}
};
string json = JsonConvert.SerializeObject(results);
Console.WriteLine(json);
Console.ReadLine();
}
public class Base {
public Results Results {get;set;}
}
public class Results{
public Profile profile {get;set;}
public Credit credit {get;set;}
}
public class Profile{
public String firstname {get;set;}
public String lastname {get;set;}
}
public class Credit{
public int amount {get;set;}
}
Class Base wraps Results class to get the required JSON structure.

Related

Why is my database table not loading using in ASP.NET Core

I am using a dbinitializer to try and seed data to a couple tables on my database. Everything seems to be ok except my Enrolls table doesn't want to populate. The Enrolls table holds all the List<> values of my Students and Courses. From that Enroll table I should be able to see which student is enrolled in which course. I am following a Microsoft docs tutorial but seem to hit a snag.
The thing is when I include the Enrolls property while creating an object in the initializer the entire database does not seed. However when I comment it out all tables except Enroll seed. I poked around a bit before I came here. Just hoping for a little guidance with some fresh pair of eyes as to where I should check/debug.
Truly hope I asked in a way that is understandable.
This is the DbInitializer:
public static class DbInitializer
{
public static void Initialize(StudentRegistrationContext context)
{
context.Database.EnsureCreated();
// Look for any students.
if (context.Students.Any() )
{
return; // DB has been seeded
}
var students = new Student[]
{
new Student
{
FirstName="A",
LastName="B",
Address = new Address
{
HouseNumber = "19",
Street="A ",
City="C",
Country = "T",
Email="s",
PhoneNumber = "6"
},
**// Enrollments = new List<Enroll> { new Enroll { CourseID = 2, ID=1 } }**
},
},
};
foreach (Student s in students)
{
context.Students.Add(s);
}
context.SaveChanges();
var course = new Course[]
{
new Course{CourseName = "Introduction to Computer Hardware",CourseCode = "ITEC120", NoOfCredits = 3, Category = Category.COMPULSORY},
new Course{ CourseName = "Introduction to Operating Systems", CourseCode= "ITEC122", NoOfCredits = 3, Category = Category.COMPULSORY },
new Course{ CourseName = "Programming 1",CourseCode = "ITEC133", NoOfCredits = 3, Category = Category.COMPULSORY},
new Course{CourseName = "Human and Computer Interface Design", CourseCode = "ITEC229", NoOfCredits = 3, Category = Category.COMPULSORY},
new Course{CourseName = "Webpage Design", CourseCode = "ITEC240", NoOfCredits = 3, Category = Category.COMPULSORY},
new Course{CourseName = "Computer Networks Architecture and Protocol",
};
foreach (Course c in course)
{
context.Course.Add(c);
}
context.SaveChanges();
var teacher = new Advisor[]
{
new Advisor{
FirstName="Teacher",
LastName="One",
Address = new Address{ HouseNumber = "123456",
Street="Teacher Street",
City="College City",
Country = "Trinidad",
Email="teacher#gmail.com",
PhoneNumber = "5648965"
},
Department="Department1",
Specialization=Category.ISD
},
};
foreach (Advisor t in teacher)
{
context.Advisor.Add(t);
}
context.SaveChanges();
var enroll = new Enroll[]
{
new Enroll{CourseID = 2, ID =2 },
};
foreach (Enroll e in enroll)
{
context.Enroll.Add(e);
}
context.SaveChanges();
}
}
My model classes:
public class Enroll
{
public int ID { get; set; }
public int CourseID { get; set; }
public Student Student { get; set; }
public Course Course { get; set; }
// public DateTime RegistrationDate { get; set; }
}
public class Student : Person
{
// public List<Course> Attends { get; set; }
public DateTime RegistrationDate { get; set; }
public List<Enroll> Enrollments { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public string CourseCode { get; set; }
public double NoOfCredits { get; set; }
public Category Category { get; set; }
public List<Enroll> Enrollments { get; set; }
}
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
}
So I figured out my issues. It was a mixture of ...
Editing the OnModelCreating function in the context
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Enroll>()
.HasOne(s => s.Student)
.WithMany(en => en.Enrollments)
.HasForeignKey(fk => fk.ID);
modelBuilder.Entity<Enroll>()
.HasOne(s => s.Course)
.WithMany(en => en.Enrollments)
.HasForeignKey(fk => fk.CourseID);
}
....and making my collection properties virtual:
public class Student : Person
{
public DateTime RegistrationDate { get; set; }
public virtual List<Enroll> Enrollments { get; set; }
}
public class Enroll
{
public int ID { get; set; }
public int CourseID { get; set; }
public virtual Student Student { get; set; }
public virtual Course Course { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public string CourseCode { get; set; }
public double NoOfCredits { get; set; }
public Category Category { get; set; }
public virtual List<Enroll> Enrollments { get; set; }
}
Thanks guys

asp.net core does not respect case sensitivity

i have this controller method that return an array of objects
public async Task<ActionResult<List<AllClientsDataModelDb>>> GetAll()
{
var ReturnValue = new List<AllClientsDataModelDb>();
ReturnValue = await Clda.GetClients(new { cm = 1 });
return (ReturnValue);
}
here is the code of AllClientsDataModelDb class
public class AllClientsDataModelDb
{
public long IDCLIENT { get; set; }
public string CL_CODE { get; set; }
public string CL_NOM { get; set; }
public string CL_ADRESSE { get; set; }
public string CL_CODEPOS { get; set; }
public string CL_VILLE { get; set; } = null;
public int CL_ETATCOMPTE { get; set; }
public int CL_AlerteCompta { get; set; }
}
but the result of that method (in browser) does not respect the case sensitivity of the class properties
Example :
[{"idclient":1,"cL_CODE":"1","cL_NOM":"EUROPEQUIPEMENTMysql","cL_ADRESSE":"ModifSoft","cL_CODEPOS":"44","cL_VILLE":"STDENIS","cL_ETATCOMPTE":1,"cL_AlerteCompta":0},
{"idclient":2,"cL_CODE":"2","cL_NOM":"A UTOMATISMES-SERVICESzzzz","cL_ADRESSE":null,"cL_CODEPOS":"97420","cL_VILLE":"LEPORT","cL_ETATCOMPTE":1,"cL_AlerteCompta":0},
what i'm doing wrong ?
You need to create your own Json Profile Formatter by inheriting from JsonOutputFormatter.
public class PascalCaseJsonProfileFormatter : JsonOutputFormatter
{
public PascalCaseJsonProfileFormatter() : base(new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() }, ArrayPool<char>.Shared)
{
SupportedMediaTypes.Clear();
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse
("application/json;profile=\"https://en.wikipedia.org/wiki/PascalCase\""));
}
}
Then modify your Startup.cs file's ConfigureServices Method like this.
services.AddMvc()
.AddMvcOptions(options =>
{
options.OutputFormatters.Add(new PascalCaseJsonProfileFormatter());
});
Try this, it should work.

MVC 5 Multiple Models in a Single View

Could somebody please provide an example of how to combine two models within one view?
Currently I have a page called RecordCard which contains:
#model IEnumerable<WebApplication1.Models.Weight>
This is provided by the following code in the AccountController:
public ActionResult RecordCard()
{
var UserId = User.Identity.GetUserId();
var weightModel = from m in db.Weights where m.UserId == UserId select m;
return View(weightModel);
}
The RecordCard page also contains a form which is bound to the following class:
public class AddWeightModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Stone")]
public Nullable<short> Stone { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Pound")]
public Nullable<short> Pound { get; set; }
}
However, these are two individual models with different purposes, so how do I combine to a single model that contains an IEnumerable list and set of form elements that will ultimately post to the AccountController correctly to add a record to the database using the following code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RecordCard(Weight Model)
{
if (ModelState.IsValid)
{
using (WebApplication1Entities db = new WebApplication1Entities())
{
Weight weight = new Weight();
weight.UserId = User.Identity.GetUserId();
weight.Stone = Model.Stone;
weight.Pound = Model.Pound;
weight.Date = System.DateTime.Now;
db.Weights.Add(Model);
db.SaveChanges();
}
}
return View(Model);
}
I have included the Weight class below:
public partial class Weight
{
public int Id { get; set; }
public string UserId { get; set; }
public Nullable<short> Stone { get; set; }
public Nullable<short> Pound { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
Also here is the WebApplication1Entities class which declares the Weight table as Weights:
public partial class WebApplication1Entities : DbContext
{
public WebApplication1Entities()
: base("name=WebApplication1Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Weight> Weights { get; set; }
}
Please explain what needs to be modified and how, no matter what I try to read, follow and implement, I seem to be missing something.
Any help would be much appreciated :-)
I would say this is good example of using ViewModel here. I would suggest something like -
Create ViewModel with the composition of the two classes
public class AddWeightModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Stone")]
public Nullable<short> Stone { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Pound")]
public Nullable<short> Pound { get; set; }
}
....
public partial class Weight
{
public int Id { get; set; }
public string UserId { get; set; }
public Nullable<short> Stone { get; set; }
public Nullable<short> Pound { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
.....
public class WeightViewModel
{
public IList<AddWeightModel> AddWeightModel { get; set; }
public Weight Weight { get; set; }
}
Then change your view to accept the view models -
#model WeightViewModel
Finally modify your controller to cope with the change -
public ActionResult RecordCard()
{
var UserId = User.Identity.GetUserId();
var weightModel = from m in db.Weights where m.UserId == UserId select m;
var viewModel = new WeightViewModel
{
Weight = weightModel,
AddWeightModel = new List<AddWeightModel>(){}
};
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RecordCard(WeightViewModel viewModel)
{
Weight Model = viewModel.Weight;
if (ModelState.IsValid)
{
using (WebApplication1Entities db = new WebApplication1Entities())
{
Weight weight = new Weight();
weight.UserId = User.Identity.GetUserId();
weight.Stone = Model.Stone;
weight.Pound = Model.Pound;
weight.Date = System.DateTime.Now;
db.Weights.Add(Model);
db.SaveChanges();
}
}
return RedirectToAction("RecordCard");
}
I've tackled this before, can came to an elegant solution.
First, you'd want to setup your main classes to send, as well as a 'holder' class to store them to eventually send to a view.
As you probably found out, this is because a view can't have multiple models sent to it.
public class WebsiteTheme
{
public string Color { get;set; }
public string Title { get;set; }
public WebsiteTheme() {
Color = "blue";
Title = "test website";
}
}
public class User
{
public string Name { get;set; }
public string Gender { get;set; }
public User() {
Name = "Anonymous";
Gender = "Unspecified";
}
}
public class ToPage
{
public WebsiteTheme WebsiteTheme{ get; set; }
public User User { get; set; }
public ToPage() {
websiteTheme = new WebsiteTheme();
user = new User();
}
}
This will allow you to send any amount of classes to your page.
Then, in your controller, you'd want to populate those classes. Make sure to initialise them all first, then set the populated classes to your holder class.
WebsiteTheme websiteTheme = new WebsiteTheme();
websiteTheme.Color = "orange";
User user = new User();
user.Name = "Darren";
ToPage toPage = new ToPage();
toPage.User = user;
toPage.WebsiteTheme = websiteTheme;
return View(toPage);
In your view, you'd call them in any way you want to. But make sure to use HolderModel.SpecifiedModel in every case.
#model WebApplication1.Models.ToPage
#Html.DisplayFor(model => model.User.Name)
I did a compound model like this:
public class CompoundModel
{
public SearchModel SearchModel { get; set; }
public QueryResultRow ResultModel { get; set; }
}
public class QueryResultRow
{
[DisplayName("Id")]
public long id { get; set; }
[DisplayName("Importdatum")]
public System.DateTime importdate { get; set; }
[DisplayName("Mandant")]
public int indexBMClient { get; set; }
}
public class SearchModel
{
[Required]
[DataType(DataType.Date)]
[Display(Name = "Zeitraum von")]
public DateTime dateFrom { get; set; }
[Display(Name = "Terminal-ID")]
public string tid { get; set; }
[Display(Name = "Belegnummer")]
public string receiptnumber { get; set; }
}
In the view header:
#model MyProject_aspmvc.Models.CompoundModel
And get data access from the SearchModel, for example:
model => model.SearchModel.tid
and data access from the ResultModel, for example:
model => model.ResultModel.importdate

Selecting a subset of data in ServiceStack.OrmLite

Is there any way to return a subset of a table in ServiceStack.OrmLite?
Something like:
public class MyStuff
{
public Guid Id { get; set; }
public string Name { get; set; }
public byte[] Data { get; set; } // Some large blob, which is not desired in the list
}
var somestuff = db.Select<MyStuff>(x => new { Id = x.Id, Name = x.Name });
I am really hoping to avoid manual stuff, like "select blabla from somewhere"...
I had that exact same problem. Here is what I did:
public class MyStuff
{
public Guid Id { get; set; }
public string Name { get; set; }
public byte[] Data { get; set; }
}
var somestuff = Db.Select<MyStuff>(p => p.Select(x => new { x.Id, x.Name }));
The only changes made, to what you did above, were done to the Db.Select.
Create a class for your basic information and set an alias.
[Alias("MyStuff")]
public class MyBasicStuff
{
public Guid Id { get;set; }
public string Name { get; set; }
}
var basicStuff = db.Select<MyBasicStuff>();

Insert multiple values from text box to the data base using the list<string>

This is the required image, I want to insert multiple value through Name, Employee Code and E-mail Id, by submit button which is in this page.
My database contains following field Id(primary key),Name (varchar 50),Employee Code (varchar 50), E-mail Id (varchar 50).
In the data layer, I code as following:
public static bool AddParticipantlistemployeecode(DimensionQuestion dimension)
{
bool result;
using (var helper = new DbHelper())
{
_cmdtext = "sp_NewGeneratedUniqueCode";
var success = new SqlParameter("#Success", SqlDbType.Bit, 1, ParameterDirection.Output, true, 0, 0,
"Result", DataRowVersion.Default, 0);
foreach (string s in dimension.CandidateName)
{
if (s.Trim().Length > 0)
{
var parameter = new[]
{
// new SqlParameter("#CompanyName",dimension.CompanyName ),
new SqlParameter("#CandidateName",s ),
new SqlParameter("#EmployeeCode",s ),
new SqlParameter("#EmailId",s ),
success,
};
helper.ExecuteScalar(_cmdtext, CommandType.StoredProcedure, parameter);
}
}
result = (bool)success.Value;
}
return result;
}
In the Model layer:
using System.Text;
using System.Collections.Generic;
namespace Cengrow.Survey.Core.Model
{
public class DimensionQuestion
{
public string CompanyName { get; set; }
// public string DimensionNumber { get; set; }
public List<string> CandidateName { get; set; }
public List<string> EmployeeCode { get; set; }
public List<string> EmailId { get; set; }
public int DimensionName { get; set; }
public string Section { get; set; }
//public string Rating { get; set; }
public List<string> Questions { get; set; }
//public string Question2 { get; set; }
//public string Question3 { get; set; }
//public string Question4 { get; set; }
//public string Question5 { get; set; }
//public string Question6 { get; set; }
//public string Question7 { get; set; }
//public string Question8 { get; set; }
//public string Question9 { get; set; }
//public string Question10 { get; set; }
//public string Question11 { get; set; }
//public string Question12 { get; set; }
//public string Question13 { get; set; }
//public string Question14 { get; set; }
//public string Question15 { get; set; }
}
}
And finally in the business logic on the button click:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
FillObjects();
//if (InsertData.InsertCandidateCompany(_CandidateCompanyInformation ))
if (InsertData.AddParticipantlistemployeecode(_DimensionQuestion))
{
ShowMessage("Information is saved");
//Reset();
}
else
{
ShowMessage("Please try again");
}
}
finally
{
_DimensionQuestion = null;
}
}
private void FillObjects()
{
List<string> sp = new List<string>();
_DimensionQuestion = new Cengrow.Survey.Core.Model.DimensionQuestion();
// _DimensionQuestion.CompanyName = txtCompanyName.Text.Trim();
sp.Add(txtName1.Text.Trim());
sp.Add(txtName2.Text.Trim());
sp.Add(txtName3.Text.Trim());
sp.Add(txtName4.Text.Trim());
sp.Add(txtName5.Text.Trim());
sp.Add(txtName6.Text.Trim());
sp.Add(txtName7.Text.Trim());
sp.Add(txtName8.Text.Trim());
sp.Add(txtName9.Text.Trim());
sp.Add(txtName10.Text.Trim());
sp.Add(txtName11.Text.Trim());
sp.Add(txtName12.Text.Trim());
sp.Add(txtName13.Text.Trim());
sp.Add(txtName14.Text.Trim());
sp.Add(txtName15.Text.Trim());
sp.Add(txtName16.Text.Trim());
sp.Add(txtName17.Text.Trim());
sp.Add(txtName18.Text.Trim());
sp.Add(txtName19.Text.Trim());
sp.Add(txtName20.Text.Trim());
sp.Add(txtName21.Text.Trim());
sp.Add(txtName22.Text.Trim());
sp.Add(txtName23.Text.Trim());
sp.Add(txtName24.Text.Trim());
sp.Add(txtName25.Text.Trim());
_DimensionQuestion.CandidateName = sp;
sp.Add(txtEmployeeCode1.Text.Trim());
sp.Add(txtEmployeeCode2.Text.Trim());
sp.Add(txtEmployeeCode3.Text.Trim());
sp.Add(txtEmployeeCode4.Text.Trim());
sp.Add(txtEmployeeCode5.Text.Trim());
sp.Add(txtEmployeeCode6.Text.Trim());
sp.Add(txtEmployeeCode7.Text.Trim());
sp.Add(txtEmployeeCode8.Text.Trim());
sp.Add(txtEmployeeCode9.Text.Trim());
sp.Add(txtEmployeeCode10.Text.Trim());
sp.Add(txtEmployeeCode11.Text.Trim());
sp.Add(txtEmployeeCode12.Text.Trim());
sp.Add(txtEmployeeCode13.Text.Trim());
sp.Add(txtEmployeeCode14.Text.Trim());
sp.Add(txtEmployeeCode15.Text.Trim());
sp.Add(txtEmployeeCode16.Text.Trim());
sp.Add(txtEmployeeCode17.Text.Trim());
sp.Add(txtEmployeeCode18.Text.Trim());
sp.Add(txtEmployeeCode19.Text.Trim());
sp.Add(txtEmployeeCode20.Text.Trim());
sp.Add(txtEmployeeCode21.Text.Trim());
sp.Add(txtEmployeeCode22.Text.Trim());
sp.Add(txtEmployeeCode23.Text.Trim());
sp.Add(txtEmployeeCode24.Text.Trim());
sp.Add(txtEmployeeCode25.Text.Trim());
_DimensionQuestion.EmployeeCode = sp;
sp.Add(TextBox1.Text.Trim());
sp.Add(TextBox2.Text.Trim());
sp.Add(TextBox3.Text.Trim());
sp.Add(TextBox4.Text.Trim());
sp.Add(TextBox5.Text.Trim());
sp.Add(TextBox6.Text.Trim());
sp.Add(TextBox7.Text.Trim());
sp.Add(TextBox8.Text.Trim());
sp.Add(TextBox9.Text.Trim());
sp.Add(TextBox10.Text.Trim());
sp.Add(TextBox11.Text.Trim());
sp.Add(TextBox12.Text.Trim());
sp.Add(TextBox13.Text.Trim());
sp.Add(TextBox14.Text.Trim());
sp.Add(TextBox15.Text.Trim());
sp.Add(TextBox16.Text.Trim());
sp.Add(TextBox17.Text.Trim());
sp.Add(TextBox18.Text.Trim());
sp.Add(TextBox19.Text.Trim());
sp.Add(TextBox20.Text.Trim());
sp.Add(TextBox21.Text.Trim());
sp.Add(TextBox22.Text.Trim());
sp.Add(TextBox23.Text.Trim());
sp.Add(TextBox24.Text.Trim());
sp.Add(TextBox25.Text.Trim());
_DimensionQuestion.EmailId = sp;
}
The data is not coming proper into the database
You are adding the same value to all three parameters:
new SqlParameter("#CandidateName",s ),
new SqlParameter("#EmployeeCode",s ),
new SqlParameter("#EmailId",s
In all cases you are adding "s" which is CandidateName.
Edit: Candidate should be a class:
public class Candidate
{
public string Name { get; set; }
public string EmployeeCode { get; set; }
public string Email { get; set; }
public Candidate(string name, string code, string email)
{
this.Name = name;
this.EmployeeCode = code;
this.Email = email;
}
}
Then your DimensionQuestion should contain a
List<Candidate> Candidates
instead of
public List<string> CandidateName { get; set; }
public List<string> EmployeeCode { get; set; }
public List<string> EmailId { get; set; }
Then you FillObjects method add Candidate objects to the Candidates list
Candidates.Add(new Candidate(txtName1.Text.Trim(),
txtEmployeeCode1.Text.Trim(),
TextBox1.Text.Trim()));
Candidates.Add(new Candidate(txtName2.Text.Trim(),
txtEmployeeCode2.Text.Trim(),
TextBox2.Text.Trim()));
Finaly your data layer should be:
foreach (Candidate candidate in dimension.Candidates)
{
if (!String.IsNullOrEmpty(candidate.Name))
{
var parameter = new[]
{
// new SqlParameter("#CompanyName",dimension.CompanyName ),
new SqlParameter("#CandidateName",candidate.Name ),
new SqlParameter("#EmployeeCode",candidate.Code ),
new SqlParameter("#EmailId",candidate.Email ),
success,
};
helper.ExecuteScalar(_cmdtext, CommandType.StoredProcedure, parameter);
}
}

Resources