I'm making ajax POST call to my web API and posting a JSON. Below is my code
C# class:
public class Employee:EmployeeBase
{
private string _EId;
private string _EName;
private string _Designation;
private EmployeeBase[] _Expirence;
public string EId
{
get { return _EId; }
set { _EId = value; }
}
public string EName
{
get { return _EName; }
set { _EName = value; }
}
public string Designation
{
get { return _Designation; }
set { _Designation = value; }
}
public Expirence[] MyExpirence
{
get { return _Expirence; }
set { _Expirence = value; }
}
}
public class EmployeeBase
{
private string _Id;
private string _Company;
private string _Years;
public string Id
{
get { return _Id; }
set { _Id = value; }
}
public string Company
{
get { return _Company; }
set { _Company = value; }
}
public string Years
{
get { return _Years; }
set { _Years = value; }
}
}
Controller:
[HttpPost]
public ActionResult SaveAssociatDisassociateCameras(Employee zone)
{
}
Sample JSON:
Sample 1 :
{
"Id":"E100",
"Name":"TestEmployee",
"Designation":"Test Engineer",
"MyExpirence":[
{
"Id":"01",
"Company":"Company1",
"Years":"10"
}
]
}
Sample 2 :
{
"Id":"E100",
"Name":"TestEmployee",
"Designation":"Test Engineer",
"MyExpirence":[
{
"Id":"01",
"Company":"Company1",
"Years":"10"
}
],
"DummyArray":[
]
}
Now the issue is when I post Sample 1 JSON is getting properly posted to controller. But in controller MyExpirence array is null. But I'm getting values for EId,EName etc. Only MyExpirence array is null.
In other hand if I post Sample 2 adding a dummy array to the JSON I'm getting proper values. In this case I'm getting proper value for EId,EName and even for MyExpirence array.
I cant understand why I'm getting null for MyExpirence in Sample 1. And I'm not okay with the Sample 2 solution. I want a correct way of doing this.
Your code won't compile: _Expirence is different to MyExpirence property. Fix it like in next sample
public class Employee:EmployeeBase
{
private string _EId;
private string _EName;
private string _Designation;
private EmployeeBase[] _Expirence;
public string EId
{
get { return _EId; }
set { _EId = value; }
}
public string EName
{
get { return _EName; }
set { _EName = value; }
}
public string Designation
{
get { return _Designation; }
set { _Designation = value; }
}
public Expirence[] MyExpirence
{
get { return _Expirence; }
set { _Expirence = value; }
}
}
Related
I have a Dictionary with Key-Value pair where Value is a complex Object.
Becaouse of a speed I have used AsParalle().
Problem that occures is that in some of my return objects are placed multiple results of other Key-Value pair.
For examle:
ResutDict has multiple Key-Value pairs.
public IDictionary<string, IOutboundResult> ResultDict
{
get { return m_ResultDict; }
set { m_ResultDict = value; }
}
ResultDict.AsParallel()
.WithDegreeOfParallelism(amountOfThreads)
.ForAll(kvp => { DO YOUR THING AND RETURN OBJECT S_Out}
All of them should return one Object. That later will be serialized into XML.
public class S_Out : ISerializable
{
private List<details> detailField;
[System.Xml.Serialization.XmlElement("details")]
public List<details> details
{
get { return detailField; }
set { detailField = value; }
}
}
public class details
{
private string idField;
private string countryField;
private string town_cityField;
private string postcodeField;
private List<extract> extractField;
public string id
{
get { return idField; }
set { idField = value; }
}
public string country
{
get { return countryField; }
set { countryField = value; }
}
public string town_city
{
get { return town_cityField; }
set { town_cityField = value; }
}
public string postcode
{
get { return postcodeField; }
set { postcodeField = value; }
}
[XmlElement("extract")]
public List<extract> extract
{
get { return extractField; }
set { extractField = value; }
}
}
This list of details is there only for some other cases, but in this particular case should contain only one detail.
During Parallel different Threads write in there so in some files I have no detail object, and in some of them whole list of details.
It should be one detail for one xml file.
Have anyone Idea why is this happening?
I want my custom PropertyGrid with student1 and student2 as nodes with "Name,Section,Percentage,School" as childs for both nodes.
I tried like this :
class StudentClass
{
private string name;
private string section;
private string percentage;
private string school;
[CategoryAttribute("Student1")]
public string School
{
get { return school; }
set { school = value; }
}
[CategoryAttribute("Student1")]
public string Percentage
{
get { return percentage; }
set { percentage = value; }
}
[CategoryAttribute("Student1")]
public string Section
{
get { return section; }
set { section = value; }
}
[CategoryAttribute("Student1")]
public string Name
{
get { return name; }
set { name = value; }
}
private string name1;
[CategoryAttribute("Student2")]
public string Name1
{
get { return name1; }
set { name1 = value; }
}
private string section1;
[CategoryAttribute("Student2")]
public string Section1
{
get { return section1; }
set { section1 = value; }
}
private string percentage1;
[CategoryAttribute("Student2")]
public string Percentage1
{
get { return percentage1; }
set { percentage1 = value; }
}
private string school1;
[CategoryAttribute("Student2")]
public string School1
{
get { return school1; }
set { school1 = value; }
}
}
public Form1()
{
InitializeComponent();
StudentClass sc = new StudentClass();
propertyGrid1.SelectedObject = sc1;
}
The Output is as shown below :
Now in the above picture for Student2 instead of "Name1,Section1,Percentage1,School1" I want to display same as student1.
But I didn't get the required output. So Kindly help me out of this.
I am using C# Winforms in VS2010
And Suggest me how to deny columns resizing i.e., I should not allow user to resize the columns.
You can use the DisplayName attribute:
private string name1;
[CategoryAttribute("Student2"), DisplayName("Name")]
public string Name1
{
get { return name1; }
set { name1 = value; }
}
But note that if the user puts the property grid into A-Z mode, they'll both end up next to each other with no real way to tell them apart. You may find there's a more appropriate way to represent your data.
I have a customer object class:
public class customerObject
{
private string _address1;
private string _address2;
private string _address3;
private string _category;
private string _country;
private string _county;
private string _custcode;
private string _fullname;
private string _int_rep_hou;
private string _int_rep_key;
private double _lat;
private double _lng;
private string _postcode;
private string _rep_code;
private string _telephone;
public customerObject()
{
}
public string Address1
{
get { return _address1; }
set { _address1 = value; }
}
public string Address2
{
get
{
return _address2;
}
set { _address2 = value; }
}
public string Address3 { get { return _address3; } set { _address3 = value; } }
public string Category
{
get { return _category; }
set { _category = value; }
}
public string Country { get { return _country; } set { _country = value; } }
public string County { get { return _county; } set { _county = value; } }
public string Custcode
{
get { return _custcode; }
set { _custcode = value; }
}
public string Fullname
{
get { return _fullname; }
set { _fullname = value; }
}
public string Int_rep_hou
{
get { return _int_rep_hou; }
set { _int_rep_hou = value; }
}
public string Int_rep_key
{
get { return _int_rep_key; }
set { _int_rep_key = value; }
}
public double Lat { get { return _lat; } set { _lat = value; } }
public double Lng { get { return _lng; } set { _lng = value; } }
public string Postcode { get { return _postcode; } set { _postcode = value; } }
public string Rep_code
{
get { return _rep_code; }
set { Rep_code = value; }
}
public string Telephone { get { return _telephone; } set { _telephone = value; }
}
}
I have a CustomCollections class
public class CustomerCollection
{
public List<customerObject> Customers { get; set; }
}
My method that loops through dt rows and converts to a customer object
public List<Valueobjects.CustomerCollection> dolist(DataTable temptablename)
{
//Create Collection Object
Valueobjects.CustomerCollection Collection = new Valueobjects.CustomerCollection();
foreach (DataRow row in temptablename.Rows)
{
//Create Customer Object
Valueobjects.customerObject Customer = new Valueobjects.customerObject();
//set values of customer object
Customer.Rep_code = "";
Customer.Int_rep_key = "";
Customer.Int_rep_hou = "";
Customer.Fullname = row["Fullname"].ToString().Trim();
Customer.Custcode = row["Custcode"].ToString().Trim();
Customer.Category = row["Category"].ToString().Trim();
Customer.Address1 = row["Address1"].ToString().Trim();
Customer.Address2 = row["Address2"].ToString().Trim();
Customer.Address3 = row["Address3"].ToString().Trim();
Customer.Postcode = row["Postcode"].ToString().Trim();
Customer.Country = row["Country"].ToString().Trim();
Customer.Telephone = row["Telephone"].ToString().Trim();
Customer.Lat = Convert.ToDouble(row["Lat"]);
Customer.Lng = Convert.ToDouble(row["Lng"]);
Customer.County = row["County"].ToString().Trim();
//add to the collection (list)
Collection.Customers.Add(Customer);
}
temptablename = null;
return Collection;
}
However when I create a new Customer object and a new CustomerCollection object I am getting an error when adding the customer to the collection list.
Error:
Error 32 Cannot implicitly convert type
'Classes.Valueobjects.CustomerCollection' to
'System.Collections.Generic.List'
Your method is returning a List<CustomerCollection>:
public List<Valueobjects.CustomerCollection> dolist(DataTable temptablename)
{
//...
}
But the code is trying to return a CustomerCollection:
return Collection;
Just as the error says, these two types are different.
If a CustomerCollection is already a collection of customers, then semantically what is a List<Valueobjects.CustomerCollection>? A collection of collections? It seems like you're over-pluralizing your objects :)
There are two approaches here. Either return a CustomerCollection from the method:
public CustomerCollection dolist(DataTable temptablename)
{
//...
}
Or use a List<Customer> if you want to use generic lists as your collection containers:
public List<Customer> dolist(DataTable temptablename)
{
//...
var Collection = new List<Customer>();
//...
Collection.Add(Customer);
//...
return Collection;
}
Side note: You may want to stick to C# conventions for variable naming. As you can see from the code highlighting here on Stack Overflow, your variable names can easily be mistaken for classes/types, which can cause confusion when supporting the code.
Return a CustomerCollection instead of a List<Valueobjects.CustomerCollection>:
public Valueobjects.CustomerCollection Dolist(DataTable temptablename)
{
// ...
Your object has a list, it is not a list.
MSDN: Inheritance
Call to a REST based API returns me data in JSON format(stored in variable strJSONStringFromAPI).
{
"id": "551",
"name": "Dev D",
"work": [
{
"employer": {
"name": "Microsoft Corporation"
},
"position": {
"name": "Software Development"
}
}
],
"gender": "male"}
I have created following classes corresponding to above JSON data
public class Employer
{
private string _name;
public string name
{
get { return _name; }
set { _name = value; }
}
}
public class Position
{
private string _name;
public string name
{
get { return _name; }
set { _name = value; }
}
}
public class Work
{
private Employer _employer;
private Position _position;
public Employer employer
{
get { return _employer; }
set { _employer = value; }
}
public Position position
{
get { return _position; }
set { _position = value; }
}
}
public class UserInfo
{
private string _id;
private string _name;
private Work[] _wk;
public string id
{
get { return _id; }
set { _id = value; }
}
public string name
{
get { return _name; }
set { _name = value; }
}
public Work[] work
{
get { return _wk; }
set { _wk = value; }
}
}
Now i have method GetUserInfo which should return object UserInfo as shown below
Public UserInfo GetUserDetails()
{
UserInfo user = New UserInfo();
user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfo>(strJSONStringFromAPI);
return user;
}
later i will access the values as
label1.text = user.ID ;
label2.text = user.name;
As of now i am getting all properties of above user object as NULL (user.ID = null etc etc)
I know i am missing something very important here..can someone help me what else needs to be done in in Employer , Position and Work classes so that i get proper values (eg user.ID = "551" etc)
Your Work class above will not compile.
public class Work
{
private Employer _employer;
private Position _position;
public Employer employer
{
get { return _employer; }
set { _employer = value; }
}
public Position position
{
get { return _employer; }
set { _employer = value; }
}
}
The Position property can't use _employer.
Tested your code with that corrected, it does work as expected. Here's a simple test using a HTTP Handler:
<%# WebHandler Language="C#" Class="JsonDotnet" %>
using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
public class JsonDotnet : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string json = context.Server.MapPath(
"~/app_data/json-test.txt"
);
UserInfo user = Newtonsoft.Json.JsonConvert
.DeserializeObject<UserInfo>(
File.ReadAllText(json)
);
context.Response.Write(user.id + "<br>");
context.Response.Write(user.name + "<br>");
context.Response.Write(user.work[0].employer.name + "<br>");
}
public bool IsReusable {
get { return false; }
}
public class Employer {
public string name { get; set;}
}
public class Position {
public string name { get; set;}
}
public class Work {
public Employer employer { get; set;}
public Position position { get; set;}
}
public class UserInfo {
public string id { get; set;}
public string name { get; set;}
public Work[] work { get; set;}
}
}
Don't forget to put your json string in ~/app_data/json-test.txt.
Are you sure strJSONStringFromAPI is exactly the same as the string you specified in your first code snippet above?
Your private variable should be public when you deserialize the json object and all name should be same in both in json object as well as in classes
Here is the thing, I have a problem creating a new object using the remote mechanism "marshal by value".
Here is my class:
[Serializable]
internal class Empleado_MBV
{
public Empleado_MBV()
{
Id = 123456789;
Nombres = "NotEntry";
Apellidos = "NotEntry";
FechaNacimiento = DateTime.MinValue;
Direccion = "NotEntry";
Metapreferencias = "NotEntry";
}
private List<Multas> _multas;
internal List<Multas> Multas
{
get { return _multas; }
set { _multas = value; }
}
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _nombres;
public string Nombres
{
get { return _nombres; }
set { _nombres = value; }
}
private string _apellidos;
public string Apellidos
{
get { return _apellidos; }
set { _apellidos = value; }
}
private DateTime _FecNac;
public DateTime FechaNacimiento
{
get { return _FecNac; }
set { _FecNac = value; }
}
private string _direccion;
public string Direccion
{
get { return _direccion; }
set { _direccion = value; }
}
private string _metapreferencias;
public string Metapreferencias
{
get { return _metapreferencias; }
set { _metapreferencias = value; }
}
public string _AppDomainHost
{
get { return AppDomain.CurrentDomain.FriendlyName.ToString(); }
}
}
But when I try to create an object in another "appdomain", the property "_AppDomainHost" of "Empleado" does not show the "appdomain" I had created, but show the "appdomain" by default. Some ideas?
AppDomain ad1 = AppDomain.CreateDomain("NewAppDomain");
//Crear new object in my new AD.
Empleado_MBV mbv_emp = (Empleado_MBV)ad1.CreateInstanceFromAndUnwrap("DEMO_MBV_MBR.exe", "DEMO_MBV_MBR.Empleado_MBV");
Console.WriteLine(AppDomain.CurrentDomain.FriendlyName.ToString());
Console.WriteLine("MBV : {0}",mbv_emp._AppDomainHost.ToString());
Console.ReadLine();
Result:
DEMO_MBV_MBR.vshost.exe
MBV : DEMO_MBV_MBR.vshost.exe
The result that I want:
DEMO_MBV_MBR.vshost.exe
MBV : NewAppDomain
You need to store AppDomain in Empleado_MBV's constructor.
What you are doing right now is displaying current AppDomain using its Current static property. It will return the AppDomain where current code is being executed.
Example:
private string _appDomainHost;
public string _AppDomainHost
{
get { return _appDomainHost; }
}
and in constructor:
_appDomainHost = AppDomain.CurrentDomain.FriendlyName.ToString();