I'm using reflection to order by list of objects.
I would like to order this list on a property of a nested object.
This is the code in which I get the list, and I do the sorting of the list
List<DocumentModel> documentList;
if (contractid == -1)
documentList = helpsi.framework.core.CustomerProvider.DocumentModel.getAllDocumentModelListByCustomer(custid, custtypeid);
else
documentList = helpsi.framework.core.CustomerProvider.DocumentModel.getAllDocumentModelListGridByContract(contractid);
if (sord.Equals("asc")) documentList = documentList.OrderBy(x => x.GetType().GetProperty(sidx.ToUpper()).GetValue(x, null)).ToList();
else documentList = documentList.OrderByDescending(x => x.GetType().GetProperty(sidx.ToUpper()).GetValue(x, null)).ToList();
The DocumentModel object has a DocumentModelType property that contains a DocumentStateDesc string property.
Can I sort the list by the DocumentTypeDesc property using reflection? What can I use in the sidx parameter?
Thanks
This is the DocumentModel class
public class DocumentModel : ObjBase
{
#region Attributi
private long _id;
private string _documentModel;
private long? _documentModelTypeId;
private long? _documentModelIssuingEntityId;
private string _documentModelFilename;
private string _documentModelPath;
private DateTime? _documentModelStart;
private DateTime? _documentModelEnd;
private string _documentModelVersion;
private long _contractId;
private string _contractNumber;
private long _contractTypeId;
private long _contractStateId;
private string _contractState;
private long _documentModelStateId;
private string _documentModelValoId;
private DateTime? _documentModelUploadDate;
private byte[] _documentModelContent;
private long _documentModelFilter;
private bool _flagDeleted;
private long _userId;
private int _orderDocumentModel = 0;
private string _placeOfIssue;
private string _issuingEntity;
private DateTime? _releaseDate;
private int? _idOpInsert;
private int? _idOpId;
private long? _customerId;
private long? _customerTypeId;
private string _customerNumber;
private DateTime? _documentModelInvalidated;
private bool _flagValidating;
private string _fileRemotePath;
private long? _folderId;
private string _folderName;
protected new HELPSI_Database HELPSI_Database = Common.HELPSI_Database.HELPSI_Anag;
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_ID")]
public long CODE_DOCUMENT_MODEL_ID
{
get { return _id; }
set { _id = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_MODEL")]
public string DESC_DOCUMENT_MODEL
{
get { return _documentModel; }
set { _documentModel = value; }
}
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_TYPE_ID")]
public long? CODE_DOCUMENT_MODEL_TYPE_ID
{
get { return _documentModelTypeId; }
set { _documentModelTypeId = value; }
}
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_ISSUING_ENTITY_ID")]
public long? CODE_DOCUMENT_MODEL_ISSUING_ENTITY_ID
{
get { return _documentModelIssuingEntityId; }
set { _documentModelIssuingEntityId = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_MODEL_FILENAME", IsNullable = true)]
public string DESC_DOCUMENT_MODEL_FILENAME
{
get { return _documentModelFilename; }
set { _documentModelFilename = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_MODEL_PATH", IsNullable=true)]
public string DESC_DOCUMENT_MODEL_PATH
{
get { return _documentModelPath; }
set { _documentModelPath = value; }
}
[XmlElement(ElementName = "DATE_DOCUMENT_MODEL_START")]
public DateTime? DATE_DOCUMENT_MODEL_START
{
get { return _documentModelStart; }
set { _documentModelStart = value; }
}
[XmlElement(ElementName = "DATE_DOCUMENT_MODEL_END")]
public DateTime? DATE_DOCUMENT_MODEL_END
{
get { return _documentModelEnd; }
set { _documentModelEnd = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_MODEL_VERSION", IsNullable = true)]
public string DESC_DOCUMENT_MODEL_VERSION
{
get { return _documentModelVersion; }
set { _documentModelVersion = value; }
}
[XmlElement(ElementName = "CODE_CONTRACT_ID")]
public long CODE_CONTRACT_ID
{
get { return _contractId; }
set { _contractId = value; }
}
[XmlElement(ElementName = "FLAG_DELETED")]
public bool FLAG_DELETED
{
get { return _flagDeleted; }
set { _flagDeleted = value; }
}
[XmlElement(ElementName = "CODE_USER_ID")]
public long CODE_USER_ID
{
get { return _userId; }
set { _userId = value; }
}
[XmlElement(ElementName = "ORDER_DOCUMENT_MODEL")]
public int ORDER_DOCUMENT_MODEL
{
get { return _orderDocumentModel; }
set { _orderDocumentModel = value;}
}
private DocumentModelType _documentModelType;
[XmlElement(ElementName = "DocumentModelType", IsNullable = true)]
public DocumentModelType documentModelType
{
get { return _documentModelType; }
set { _documentModelType = value; }
}
private DocumentModelState _documentModelState;
[XmlElement(ElementName = "DocumentModelState", IsNullable = true)]
public DocumentModelState documentModelState
{
get { return _documentModelState; }
set { _documentModelState = value; }
}
private DocumentModelIssuingEntity _documentModelIssuingEntity;
[XmlElement(ElementName = "DocumentModelIssuingEntity", IsNullable = true)]
public DocumentModelIssuingEntity documentModelIssuingEntity
{
get { return _documentModelIssuingEntity; }
set { _documentModelIssuingEntity = value; }
}
//private DocumentModelFolder _documentModelFolder;
//[XmlElement(ElementName = "DocumentModelFolder", IsNullable = true)]
//public DocumentModelFolder documentModelFolder
//{
// get { return _documentModelFolder; }
// set { _documentModelFolder = value; }
//}
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_STATE_ID")]
public long CODE_DOCUMENT_MODEL_STATE_ID
{
get { return _documentModelStateId; }
set { _documentModelStateId = value; }
}
[XmlElement(ElementName = "VALO_DOCUMENT_MODEL_ID")]
public string VALO_DOCUMENT_MODEL_ID
{
get { return _documentModelValoId; }
set { _documentModelValoId = value; }
}
[XmlElement(ElementName = "DATE_DOCUMENT_MODEL_UPLOAD")]
public DateTime? DATE_DOCUMENT_MODEL_UPLOAD
{
get { return _documentModelUploadDate; }
set { _documentModelUploadDate = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_MODEL_CONTENT")]
public byte[] DESC_DOCUMENT_MODEL_CONTENT
{
get { return _documentModelContent; }
set { _documentModelContent = value; }
}
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_FILTER_ID")]
public long CODE_DOCUMENT_MODEL_FILTER_ID
{
get { return _documentModelFilter; }
set { _documentModelFilter = value; }
}
private long _code_siteId;
[XmlElement(ElementName = "CODE_SITEID")]
public long CODE_SITEID
{
get { return _code_siteId; }
set { _code_siteId = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_RELEASE_PLACE")]
public string DESC_DOCUMENT_RELEASE_PLACE
{
get { return _placeOfIssue; }
set { _placeOfIssue = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_RELEASED_BY")]
public string DESC_DOCUMENT_RELEASED_BY
{
get { return _issuingEntity; }
set { _issuingEntity = value; }
}
[XmlElement(ElementName = "DATE_DOCUMENT_RELEASED")]
public DateTime? DATE_DOCUMENT_RELEASED
{
get { return _releaseDate; }
set { _releaseDate = value; }
}
[XmlElement(ElementName = "CODE_OP_INSERT_ID")]
public int? CODE_OP_INSERT_ID
{
get { return _idOpInsert; }
set { _idOpInsert = value; }
}
[XmlElement(ElementName = "CODE_OP_ID_ID")]
public int? CODE_OP_ID_ID
{
get { return _idOpId; }
set { _idOpId = value; }
}
[XmlElement(ElementName = "CODE_CUSTOMERID")]
public long? CODE_CUSTOMERID
{
get { return _customerId; }
set { _customerId = value; }
}
[XmlElement(ElementName = "CODE_CUSTOMERTYPEID")]
public long? CODE_CUSTOMERTYPEID
{
get { return _customerTypeId; }
set { _customerTypeId = value; }
}
[XmlElement(ElementName = "DATE_DOCUMENT_MODEL_INVALIDATED")]
public DateTime? DATE_DOCUMENT_MODEL_INVALIDATED
{
get { return _documentModelInvalidated; }
set { _documentModelInvalidated = value; }
}
[XmlElement(ElementName = "FLAG_VALIDATING")]
public bool FLAG_VALIDATING
{
get { return _flagValidating; }
set { _flagValidating = value; }
}
[XmlElement(ElementName = "CODE_CONTRACT_STATES_ID")]
public long CODE_CONTRACT_STATES_ID
{
get { return _contractStateId; }
set { _contractStateId = value; }
}
[XmlElement(ElementName = "DESC_CONTRACT_STATES")]
public string DESC_CONTRACT_STATES
{
get { return _contractState; }
set { _contractState = value; }
}
[XmlElement(ElementName = "CODE_CONTRACT_TYPE_ID")]
public long CODE_CONTRACT_TYPE_ID
{
get { return _contractTypeId; }
set { _contractTypeId = value; }
}
[XmlElement(ElementName = "DESC_CONTRACT_NUMBER")]
public string DESC_CONTRACT_NUMBER
{
get { return _contractNumber; }
set { _contractNumber = value; }
}
[XmlElement(ElementName = "DESC_CONTACT_NUMBER")]
public string DESC_CONTACT_NUMBER
{
get { return _customerNumber; }
set { _customerNumber = value; }
}
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_FOLDER_ID")]
public long? CODE_DOCUMENT_MODEL_FOLDER_ID
{
get { return _folderId; }
set { _folderId = value; }
}
[XmlElement(ElementName = "DocumentModelFolderName")]
public string DocumentModelFolderName
{
get { return _folderName; }
set { _folderName = value; }
}
[XmlElement(ElementName = "DESC_FILEREMOTEPATH")]
public string DESC_FILEREMOTEPATH
{
get { return _fileRemotePath; }
set { _fileRemotePath = value; }
}
#endregion
}
And this is the DocumentModelType Class
public class DocumentModelType : ObjBase
{
#region Attributi
private long _id;
private string _documentModelType;
private bool _flagDeleted;
private long _userId;
protected new HELPSI_Database HELPSI_Database = Common.HELPSI_Database.HELPSI_Anag;
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_TYPE_ID")]
public long CODE_DOCUMENT_MODEL_TYPE_ID
{
get { return _id; }
set { _id = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_MODEL_TYPE")]
public string DESC_DOCUMENT_MODEL_TYPE
{
get { return _documentModelType; }
set { _documentModelType = value; }
}
[XmlElement(ElementName = "FLAG_DELETED")]
public bool FLAG_DELETED
{
get { return _flagDeleted; }
set { _flagDeleted = value; }
}
[XmlElement(ElementName = "CODE_USER_ID")]
public long CODE_USER_ID
{
get { return _userId; }
set { _userId = value; }
}
#endregion
}
You should be using x => x.DocumentModelType.GetType().GetProperty(sidx.ToUpper()).GetValue(x.DocumentModelType, null) inside OrderBy clause. Here sidx should be DocumentStateDesc as you mentioned that you want order on this column.
Complete code will be like below.
List<DocumentModel> documentList;
if (contractid == -1)
documentList = helpsi.framework.core.CustomerProvider.DocumentModel.getAllDocumentModelListByCustomer(custid, custtypeid);
else
documentList = helpsi.framework.core.CustomerProvider.DocumentModel.getAllDocumentModelListGridByContract(contractid);
if (sord.Equals("asc"))
documentList = documentList.OrderBy(x => x.DocumentModelType.GetType().GetProperty(sidx.ToUpper()).GetValue(x.DocumentModelType, null)).ToList();
else
documentList = documentList.OrderByDescending(x => x.DocumentModelType.GetType().GetProperty(sidx.ToUpper()).GetValue(x.DocumentModelType, null)).ToList();
One quick and dirty fix is to introduce property in parent class that just returns the property value of another property. Just don't assign XmlElement attribute to it. If the classes are auto-generated you can't change them, but they are probably declared as partial, and then you can add this new property in additional class definition.
public string DocumentModelType_DocumentStateDesc { get => DocumentModelType.DocumentStateDesc; }
But if you want to have a general solution for several properties with several sub-properties then some sort of pathing is required. You could String.Split sidx on some delimiter like '\' or '.', use recursion, and then OrderBy the last item in the path.
Related
In the code below I hope that I specify correctly whats wrong. I need to be able to call item.departments.dept_Type and that should be possible because of the association that I have made. I don't need to create inner joins on a query to get the data if I understand correctly.
This is my PersonClass
namespace DATALAYER.DataHandler
{
[Table(Name = "People")]
public class Person
{
private int _DepartmentID;
public EntityRef<Department> _Department;
public Person() { this._Department = new EntityRef<Department>(); }
private int _ID;
[Column(IsPrimaryKey =true, Storage ="_ID")]
public int ID
{
get { return this._ID; }
set { this._ID = value; }
}
private string _p_FirstName;
[Column(Storage = "_p_FirstName")]
public string p_FirstName
{
get { return this._p_FirstName; }
set { this._p_FirstName = value; }
}
private string _LastName;
[Column(Storage = "_LastName")]
public string p_LastName
{
get { return this._LastName; }
set { this._LastName = value; }
}
private string _EmailAddress;
[Column(Storage = "_EmailAddress")]
public string p_EmailAddress
{
get { return this._EmailAddress; }
set { this._EmailAddress = value; }
}
private string _Password;
[Column(Storage = "_Password")]
public string p_Password
{
get { return this._Password; }
set { this._Password = value; }
}
private string _SSID;
[Column(Storage = "_SSID")]
public string p_SSID
{
get { return this._SSID; }
set { this._SSID = value; }
}
private string _DOB;
[Column(Storage = "_DOB")]
public string p_DOB
{
get { return this._DOB; }
set { this._DOB = value; }
}
private string _CellNumber;
[Column(Storage = "_CellNumber")]
public string p_CellNumber
{
get { return this._CellNumber; }
set { this._CellNumber = value; }
}
[Column(Storage = "_DepartmentID", DbType = "Int")]
public int p_Department_dept_ID
{
get { return this._DepartmentID; }
set { this._DepartmentID = value; }
}
[Association(Storage = "_DepartmentID", ThisKey = "p_Department_dept_ID")]
public Department Department
{
get { return this._Department.Entity; }
set { this._Department.Entity = value; }
}
}
}
This is my Department code
namespace DATALAYER.DataHandler
{
[Table(Name = "Departments")]
public class Department
{
//private EntitySet<Person> _Person;
//public Department()
//{
// this._Person = new EntitySet<Person>();
//}
private int _DepartmentID;
[Column(IsPrimaryKey = true, Storage = "_DepartmentID")]
public int dept_ID
{
get { return this._DepartmentID; }
set { this._DepartmentID = value; }
}
private string _deptType;
[Column(Storage = "_deptType")]
public string dept_Type
{
get { return this._deptType; }
set { this._deptType = value; }
}
//[Association(Storage = "_Person", OtherKey = "ID")]
//public EntitySet<Person> Persons
//{
// get { return this._Person; }
// set { this._Person.Assign(value); }
//}
}
}
Now the problem I'm thinking is that there is a problem with datatypes between the primary key of the person and a foreign key the departments. But Since they are both int I don't see how that can be a problem.
If someone can just explain my problem to cleary if Im wrong or something or help me with a solution pls.
Added this class
namespace DATALAYER.DataHandler
{
public class SHSdb2 : DataContext
{
public Table<Person> People;
public Table<Department> Department;
//public Table<Address> Address;
public SHSdb2(string connection) : base(connection) { }
}
}
Person table
Department table
Without this code it works but then I can only call stuff inside the table
[Column(Storage = "_DepartmentID", DbType = "Int")]
public int p_Department_dept_ID
{
get { return this._DepartmentID; }
set { this._DepartmentID = value; }
}
[Association(Storage = "_DepartmentID", ThisKey = "p_Department_dept_ID")]
public Department Department
{
get { return this._Department.Entity; }
set { this._Department.Entity = value; }
}
Seems like I fixed it with this not sure if its a fix or I just lucky if someone can still maybe explain this to me it would be much appreciated.
var personQuery =
from per in db.People
where per.p_FirstName == "Christian"
select per.Department;
I'm thinking by specifying that it needs to get the data from department it would allow it in the foreach.
I have in Xamarin.Forms XAML ListView that is being sourced by a typed ItemSource:
ObservableCollection<WorkOrderActivity> serviceList =
new ObservableCollection<WorkOrderActivity>();
servicelistview.ItemsSource = serviceList;
Here is my table:
public class WorkOrderActivity
{
string id;
int workordernumber;
string activity;
string service;
string activitylocation;
float actualquantity;
string reference;
DateTime arrivaltime;
DateTime departuretime;
string remarks;
bool complete;
bool done;
string uom;
int startgauge;
int endgauge;
int contactgauge;
[JsonProperty(PropertyName = "id")]
public string Id
{
get { return id; }
set { id = value; }
}
[JsonProperty(PropertyName = "workordernumber")]
public int WorkOrderNumber
{
get { return workordernumber; }
set { workordernumber = value; }
}
[JsonProperty(PropertyName = "activity")]
public string Activity
{
get { return activity; }
set { activity = value; }
}
[JsonProperty(PropertyName = "service")]
public string Service
{
get { return service; }
set { service = value; }
}
[JsonProperty(PropertyName = "arrivaltime" )]
public DateTime ArrivalTime
{
get { return arrivaltime; }
set { arrivaltime = value; }
}
[JsonProperty(PropertyName = "departuretime")]
public DateTime DepartureTime
{
get { return departuretime; }
set { departuretime = value; }
}
[JsonProperty(PropertyName = "activitylocation")]
public string ActivityLocation
{
get { return activitylocation; }
set { activitylocation = value; }
}
[JsonProperty(PropertyName = "actualquantity")]
public float ActualQuantity
{
get { return actualquantity; }
set { actualquantity = value; }
}
[JsonProperty(PropertyName = "startgauge")]
public int StartGauge
{
get { return startgauge; }
set { startgauge = value; }
}
[JsonProperty(PropertyName = "endgauge")]
public int EndGauge
{
get { return endgauge; }
set { endgauge = value; }
}
[JsonProperty(PropertyName = "contactgauge")]
public int ContactGauge
{
get { return contactgauge; }
set { contactgauge = value; }
}
[JsonProperty(PropertyName = "reference")]
public string Reference
{
get { return reference; }
set { reference = value; }
}
[JsonProperty(PropertyName = "remarks")]
public string Remarks
{
get { return remarks; }
set { remarks = value; }
}
[JsonProperty(PropertyName = "uom")]
public string UOM
{
get { return uom; }
set { uom = value; }
}
[JsonProperty(PropertyName = "done")]
public bool Done
{
get { return done; }
set { done = value; }
}
[JsonProperty(PropertyName = "complete")]
public bool Complete
{
get { return complete; }
set { complete = value; }
}
[Version]
public string Version { get; set; }
[CreatedAt]
public DateTimeOffset CreatedAt { get; set; }
[UpdatedAt]
public DateTimeOffset UpdatedAt { get; set; }
[Deleted]
public bool Deleted { get; set; }
}
The problem occurs when I select an item from the listview, I get the correct record, but the datetime fields only have date in them, the time is zero.
private void servicelistview_ItemTapped(object sender, ItemTappedEventArgs e)
{
var p = (WorkOrderActivity)e.Item;
When I display the record in the listview it comes up with the correct time and date, it just appears that when I cast the selected item as a WorkOrderActivity.
Any ideas?
DateTime.Date returns 00:00:00; from the DateTime.Date documentation:
// Returns:
// A new object with the same date as this instance, and the time value set to 12:00:00
// midnight (00:00:00).
Example:
var dt = new DateTime(2018, 01, 14, 1, 2, 3);
Debug.WriteLine(dt.Date);
Debug.WriteLine(dt.Hour + " " + dt.Minute + " " + dt.Second);
Output:
1/14/2018 12:00:00 AM
1 2 3
I'm trying to populate a DropDownList, but I have some troubles with the DataTextField and DataValueField. The drop-down doesn't show the elements of the list.
private void llenarProfesionales()
{
List<Profesional> profesionales = daoProfesionales.getAll();
DropDownProfesioanles.DataSource = profesionales;
DropDownProfesioanles.DataTextField = "nombre";
DropDownProfesioanles.DataValueField = "id";
DropDownProfesioanles.DataBind();
}
Here is my class profesional that extends usuario:
public class Profesional: Usuario
{
long idProfesional;
List<Servicio> listaServicios;
Profesion profesion;
Usuario usuar;
Decimal comision;
public Decimal Comision
{
get { return comision; }
set { comision = value; }
}
public Profesional()
{
}
public long IdProfesional
{
get { return idProfesional; }
set { idProfesional = value; }
}
public List<Servicio> ListaServicios
{
get { return listaServicios; }
set { listaServicios = value; }
}
public Profesion Profesion
{
get { return profesion; }
set { profesion = value; }
}
public Usuario Usuar
{
get { return usuar; }
set { usuar = value; }
}
}
Here is the class usuario:
public class Usuario
{
private long id;
private String nombre;
private String apellido;
private String telefono;
private String celular;
private Boolean activo;
private String user;
private String password;
public Usuario()
{
}
public Usuario(string nombre, string apellido, string telefono , string celular, string user, string password ,long id, bool activo) {
this.Id = id;
this.Nombre = nombre;
this.Apellido = apellido;
this.Telefono = telefono;
this.Celular = celular;
this.User = user;
this.password = password;
this.activo = activo;
}
public long Id
{
get { return id; }
set { id = value; }
}
public String Nombre
{
get { return nombre; }
set { nombre = value; }
}
public String Apellido
{
get { return apellido; }
set { apellido = value; }
}
public String Telefono
{
get { return telefono; }
set { telefono = value; }
}
public String Celular
{
get { return celular; }
set { celular = value; }
}
public String Password
{
get { return password; }
set { password = value; }
}
public Boolean Activo
{
get { return activo; }
set { activo = value; }
}
public String User
{
get { return user; }
set { user = value; }
}
}
Specify the public properties, not the private fields:
DropDownProfesioanles.DataTextField = "Nombre";
DropDownProfesioanles.DataValueField = "Id";
Also, there's no reason to define your class like this, where you define a public Usuario property, but also extend the Usuario class (so you'll have access to all of its properties, but they won't have any values since you're using the separate "Usuar" variable).
public class Profesional : Usuario
{
...
Usuario usuar;
...
public Usuario Usuar
{
get { return usuar; }
set { usuar = value; }
}
}
If you're going to use the public property, then don't extend the other class:
public class Profesional
{
...
Usuario usuar;
...
public Usuario Usuar
{
get { return usuar; }
set { usuar = value; }
}
}
thanks for the answers I solved adding this code to the Profesional
public String Nombre
{
get { return usuar.Nombre; }
set { usuar.Nombre = value; }
}
"[{\"active\":true,\"campaignId\":11401,\"createdtime\":1355919181000,\"description\":\"Ankit Demo Edited By Nirav\",\"enddate\":1363132800000,\"groupId\":10179,\"isdeleted\":false,\"lastmodifiedby\":10405,\"modifiedtime\":1362556187000,\"name\":\"Ankit Demo\",\"noofweek\":12,\"organizationId\":11153,\"startdate\":1355875200000,\"status\":2,\"userId\":11161},
{\"active\":true,\"campaignId\":21901,\"createdtime\":1358493958000,\"description\":\"sdadadasd\",\"enddate\":1359072000000,\"groupId\":10179,\"isdeleted\":false,\"lastmodifiedby\":10405,\"modifiedtime\":1358751277000,\"name\":\"NEW CAMP TEST\",\"noofweek\":1,\"organizationId\":10707,\"startdate\":1358467200000,\"status\":4,\"userId\":10405},
{\"active\":true,\"campaignId\":33601,\"createdtime\":1361441582000,\"description\":\"dasdsadasd\",\"enddate\":1363219200000,\"groupId\":10179,\"isdeleted\":false,\"lastmodifiedby\":10405,\"modifiedtime\":1361795632000,\"name\":\"BHAVIK UTC\",\"noofweek\":3,\"organizationId\":10707,\"startdate\":1361404800000,\"status\":2,\"userId\":10405}]"
I have Above Jsong String in my string variable ..and i want to convert this json string into an object of my custom class..i have created the custom class ..
following is the code in which i getingg the response in json from HttpWebResponse and converting in list object of my custom class
HttpWebResponse response = default(HttpWebResponse);
try
{
response = (HttpWebResponse)request.GetResponse();
// response.Close()
string sResult = null;
using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
{
sResult = responseReader.ReadToEnd();
}
response.Close();
Console.WriteLine(sResult);
List<Class1> myDeserializedObjList = (List<Class1>)Newtonsoft.Json.JsonConvert.DeserializeObject(Request[sResult], typeof(List<Class1>));
int counts= myDeserializedObjList.Count;
}
but its giving me error
Value cannot be null.
Parameter name: s
Can anyone Please guide me how to solve this problem?
this is my custom class to which i want to assign the objects from json string
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for Class1
/// </summary>
public class Class1
{
private Boolean active;
public Boolean Active
{
get { return active; }
set { active = value; }
}
private long campaignId;
public long CampaignId
{
get { return campaignId; }
set { campaignId = value; }
}
private long createdtime;
public long Createdtime
{
get { return createdtime; }
set { createdtime = value; }
}
private string description;
public string Description
{
get { return description; }
set { description = value; }
}
private long enddate;
public long Enddate
{
get { return enddate; }
set { enddate = value; }
}
private long groupId;
public long GroupId
{
get { return groupId; }
set { groupId = value; }
}
private Boolean isdeleted;
public Boolean Isdeleted
{
get { return isdeleted; }
set { isdeleted = value; }
}
private long modifiedtime;
public long Modifiedtime
{
get { return modifiedtime; }
set { modifiedtime = value; }
}
private long lastmodifiedby;
public long Lastmodifiedby
{
get { return lastmodifiedby; }
set { lastmodifiedby = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int noofweek;
public int Noofweek
{
get { return noofweek; }
set { noofweek = value; }
}
private long organizationId;
public long OrganizationId
{
get { return organizationId; }
set { organizationId = value; }
}
private long startdate;
public long Startdate
{
get { return startdate; }
set { startdate = value; }
}
private Boolean status;
public Boolean Status
{
get { return status; }
set { status = value; }
}
private long userId;
public long UserId
{
get { return userId; }
set { userId = value; }
}
public Class1()
{
}
}
If your Request[sResult] is the json string you mentionned.
Try
Newtonsoft.Json.JsonConvert.DeserializeObject<List<Class1>>(Request[sResult]);
Edit, i mean :
List<Class1> myDeserializedObjList =Newtonsoft.Json.JsonConvert.DeserializeObject<List<Class1>>(Request[sResult]);
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();