I'm trying to addsome Data Annotation using a Partial Class.
As you can see I added a Test Property to my Partial Class so I can test if it really match with the other partials
(as following this article http://msdn.microsoft.com/en-us/library/ee256141.aspx)
It seems that my class is a naked partial class so I'm not sure what I'm doing wrong here.
The problem is the MetaData do not apply to the Partial Class (so the Partial Class is ignored)
Could you please help me out? Thanks
using System;
using System.Collections.Generic;
namespace MyProject.Models
{
public partial class ReAdvSlot
{
// Poco
public int AdvSlotId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsPublished { get; set; }
public string Code { get; set; }
public string Notes { get; set; }
}
}
using System.ComponentModel.DataAnnotations;
namespace MyProject.Models
{
[MetadataType(typeof(ReAdvSlotMetaData))]
public partial class ReAdvSlot
{
public class ReAdvSlotMetaData
{
public int AdvSlotId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsPublished { get; set; }
public string Code { get; set; }
public string Notes { get; set; }
public string TestProperty { get; set; } // TEST PROPERTY
}
}
}
The partial class is not ignored. If you were to put Test property into the actual partial class instead of the metadata, you would see it in the class definition.
namespace MyProject.Models
{
public partial class ReAdvSlot
{
public int AdvSlotId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsPublished { get; set; }
public string Code { get; set; }
public string Notes { get; set; }
}
}
}
namespace MyProject.Models
{
[MetadataType(typeof(ReAdvSlotMetaData))]
public partial class ReAdvSlot
{
public string TestProperty { get; set; } // TEST PROPERTY here instead
}
public class ReAdvSlotMetaData
{
[Required] //Example of defining metadata
public int AdvSlotId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsPublished { get; set; }
public string Code { get; set; }
public string Notes { get; set; }
}
}
Related
I have 3 different lists in "UrnikPrevozov" class, I want to populate them with data from JSON for each list, but I am not quite sure how to correctly do it. Any help would be greatly appreciated.
This is my json:
{
"UrnikAvtobus": [
{
"Linija": 34,
"Trajanje": "01:15:00",
"Voznik": "Rojko Mulic",
"Vstop": "Velenje",
"Izstop": "Maribor",
"CenaVozovnice": 2.90
}
],
"UrnikAvto": [
{
"Znamka": "MERCEDES",
"Registerska": "LJ 455-AA",
"Vinjeta": 0,
"Vstop": "Maribor",
"Izstop": "Velenje",
"CenaVozovnice": 5.40
}
],
"UrnikKombi": [
{
"Sedezi": 8,
"Odhod": "2022-12-12T09:15:00",
"Prihod": "2022-12-12T12:31:00",
"Vstop": "Maribor",
"Izstop": "Ljubljana",
"CenaVozovnice": 3.70
}
]
}
My UrnikPrevozov class where I want to bind the data to the lists:
public class UrnikPrevozov : Prevoz
{
public List<AvtobusniPrevoz> UrnikBus { get; set; }
public List<AvtoPrevoz> UrnikAvto { get; set; }
public List<KombiPrevoz> UrnikKombi { get; set; }
}
This is how I read my json:
public void LoadJson()
{
string data = File.ReadAllText("./Data/data.json");
var urniki = JsonConvert.DeserializeObject<UrnikPrevozov>(data);
}
AvtoPrevoz class
public class AvtoPrevoz : Prevoz
{
public string Znamka { get; set; }
public string Registerska { get; set; }
public Vinjeta Vinjeta { get; set; }
public AvtoPrevoz(string znamka, string registerska, Vinjeta vinjeta, string vstop, string izstop, double cenaVozovnice) : base(vstop, izstop, cenaVozovnice)
{
Znamka = znamka;
Registerska = registerska;
Vinjeta = vinjeta;
}
}
Prevoz class
public abstract class Prevoz
{
public string Vstop { get; set; }
public string Izstop { get; set; }
public double CenaVozovnice { get; set; }
protected Prevoz(string vstop, string izstop, double cenaVozovnice)
{
Vstop = vstop;
Izstop = izstop;
CenaVozovnice = cenaVozovnice;
}
}
Method call in main:
UrnikPrevozov urnik = new UrnikPrevozov();
urnik.LoadJson();
Your UrnikPrevozov class should not be inheriting Prevoz since it does not need the fields Prevoz has. And you would need parameterless constructors for all your classes.
Update: Full working code:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using System.IO;
public class Program
{
public static void Main()
{
string json = File.ReadAllText("./Data/data.json");
UrnikPrevozov urnik = JsonConvert.DeserializeObject<UrnikPrevozov>(json);
Console.WriteLine(urnik.UrnikAvto.First().Vstop);
}
}
public class AvtobusniPrevoz : Prevoz
{
public int Linija { get; set; }
public string Trajanje { get; set; }
public string Voznik { get; set; }
}
public class AvtoPrevoz : Prevoz
{
public string Znamka { get; set; }
public string Registerska { get; set; }
public int Vinjeta { get; set; }
}
public class KombiPrevoz : Prevoz
{
public int Sedezi { get; set; }
public DateTime Odhod { get; set; }
public DateTime Prihod { get; set; }
}
public abstract class Prevoz
{
public string Vstop { get; set; }
public string Izstop { get; set; }
public double CenaVozovnice { get; set; }
}
public class UrnikPrevozov
{
public List<AvtobusniPrevoz> UrnikBus { get; set; }
public List<AvtoPrevoz> UrnikAvto { get; set; }
public List<KombiPrevoz> UrnikKombi { get; set; }
}
you have a typo in UrnikPrevozov class , replace UrnikBus by UrnikAvtobus, also you don't need any base class here. After this everything will be working properly (tested in Visual Studio)
public class UrnikPrevozov
{
public List<AvtobusniPrevoz> UrnikAvtobus { get; set; }
public List<AvtoPrevoz> UrnikAvto { get; set; }
public List<KombiPrevoz> UrnikKombi { get; set; }
}
I have following two class structures, its CASADetialsResponse as follows,
public class CASADetialsResponse
{
public string status { get; set; }
public string message { get; set; }
public List<object> validation { get; set; }
public Data data { get; set; }
}
public class LinkedCard
{
public string cardNumber { get; set; }
}
public class JointParty
{
public string jointName { get; set; }
}
public class Account
{
public string accountNumber { get; set; }
public string accountNickName { get; set; }
public List<LinkedCard> linkedCards { get; set; }
public List<JointParty> jointParty { get; set; }
public List<object> productValidation { get; set; }
}
public class Transaction
{
public string accountNumber { get; set; }
public string valueDate { get; set; }
public string transactionDetails { get; set; }
public string postDate { get; set; }
}
public class Data
{
public Account account { get; set; }
public List<Transaction> transactions { get; set; }
}
And the CASADetails class structure as follows,
public class CASADetails
{
public string status { get; set; }
public string message { get; set; }
public List<object> validation { get; set; }
public Data data { get; set; }
}
public class LinkedCard
{
public string cardNumber { get; set; }
}
public class JointParty
{
public string jointName { get; set; }
}
public class Account
{
public string accountNumber { get; set; }
public string accountNickName { get; set; }
public List<LinkedCard> linkedCards { get; set; }
public List<JointParty> jointParty { get; set; }
public List<object> productValidation { get; set; }
}
public class Transaction
{
public string accountNumber { get; set; }
public string valueDate { get; set; }
public string transactionDetails { get; set; }
public string postDate { get; set; }
}
public class Data
{
public Account account { get; set; }
public List<Transaction> transactions { get; set; }
}
When I use _mapper.Map<CASADetialsResponse>(casaResponse); I'm getting this error:
Error mapping types:
Mapping types:
CASADetails -> CASADetialsResponse
AccountManagement.Domain.CASADetails -> AccountManagement.Application.Dtos.CASADetails.CASADetialsResponse
Type Map configuration:
CASADetails -> CASADetialsResponse
AccountManagement.Domain.CASADetails -> AccountManagement.Application.Dtos.CASADetails.CASADetialsResponse
Destination Member:
data
This is how I map the two classes,
public class CASADetailsProfile : Profile
{
public CASADetailsProfile()
{
// Source -> Target
CreateMap<CASADetialsRequest, CASADetails>();
CreateMap<CASADetails, CASADetialsResponse>();
}
}
I just commented the public Data data { get; set; } from the both classes, and without any error its worked. I think problem is with that line. may I know the reason? please help me
The namespace for Data class is different, even though their content is the same.
Delete these
and refer to source Data class namespace or
If you don't want to delete them, add the following configuration
public class CASADetailsProfile: Profile
{
public CASADetailsProfile()
{
// Source -> Target
CreateMap<CASADetialsRequest, CASADetails>();
CreateMap<CASADetails, CASADetialsResponse>();
CreateMap<Sources.Data, Destinations.Data>();
CreateMap<Sources.Account, Destinations.Account>();
CreateMap<Sources.Transaction, Destinations.Transaction>();
CreateMap<Sources.LinkedCard, Destinations.LinkedCard>();
CreateMap<Sources.JointParty, Destinations.JointParty>();
}
}
Change Sources namespace and Destinations namespace to the namespace that you have
I am using the SharePoint REST API to do a search. I am pulling back the JSON results and reading them as follows:
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(querystring);
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json; odata=verbose";
endpointRequest.UseDefaultCredentials = true;
HttpWebResponse endpointResponse =(HttpWebResponse)endpointRequest.GetResponse();
Stream webStream = endpointResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
var results = responseReader.ReadToEnd();
This works fine, I can see the results in JSON format. So I created a class from the JSON in VS 2017 and here is the classes created from the JSON (this was done automatically with File=>Paste Special=>Paste JSON As Classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class SharePointRESTResults
{
public class Rootobject
{
public D d { get; set; }
}
public class D
{
public Query query { get; set; }
}
public class Query
{
public __Metadata __metadata { get; set; }
public int ElapsedTime { get; set; }
public Primaryqueryresult PrimaryQueryResult { get; set; }
public Properties1 Properties { get; set; }
public Secondaryqueryresults SecondaryQueryResults { get; set; }
public string SpellingSuggestion { get; set; }
public Triggeredrules TriggeredRules { get; set; }
}
public class __Metadata
{
public string type { get; set; }
}
public class Primaryqueryresult
{
public __Metadata1 __metadata { get; set; }
public Customresults CustomResults { get; set; }
public string QueryId { get; set; }
public string QueryRuleId { get; set; }
public object RefinementResults { get; set; }
public Relevantresults RelevantResults { get; set; }
public object SpecialTermResults { get; set; }
}
public class __Metadata1
{
public string type { get; set; }
}
public class Customresults
{
public __Metadata2 __metadata { get; set; }
public object[] results { get; set; }
}
public class __Metadata2
{
public string type { get; set; }
}
public class Relevantresults
{
public __Metadata3 __metadata { get; set; }
public object GroupTemplateId { get; set; }
public object ItemTemplateId { get; set; }
public Properties Properties { get; set; }
public object ResultTitle { get; set; }
public object ResultTitleUrl { get; set; }
public int RowCount { get; set; }
public Table Table { get; set; }
public int TotalRows { get; set; }
public int TotalRowsIncludingDuplicates { get; set; }
}
public class __Metadata3
{
public string type { get; set; }
}
public class Properties
{
public Result[] results { get; set; }
}
public class Result
{
public __Metadata4 __metadata { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class __Metadata4
{
public string type { get; set; }
}
public class Table
{
public __Metadata5 __metadata { get; set; }
public Rows Rows { get; set; }
}
public class __Metadata5
{
public string type { get; set; }
}
public class Rows
{
public Result1[] results { get; set; }
}
public class Result1
{
public __Metadata6 __metadata { get; set; }
public Cells Cells { get; set; }
}
public class __Metadata6
{
public string type { get; set; }
}
public class Cells
{
public Result2[] results { get; set; }
}
public class Result2
{
public __Metadata7 __metadata { get; set; }
public string Key { get; set; }
public object Value { get; set; }
public string ValueType { get; set; }
}
public class __Metadata7
{
public string type { get; set; }
}
public class Properties1
{
public Result3[] results { get; set; }
}
public class Result3
{
public __Metadata8 __metadata { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class __Metadata8
{
public string type { get; set; }
}
public class Secondaryqueryresults
{
public __Metadata9 __metadata { get; set; }
public object[] results { get; set; }
}
public class __Metadata9
{
public string type { get; set; }
}
public class Triggeredrules
{
public __Metadata10 __metadata { get; set; }
public object[] results { get; set; }
}
public class __Metadata10
{
public string type { get; set; }
}
}
}
So I now am trying to deserialize the results as follows:
SharePointRESTResults resultX = JsonConvert.DeserializeObject<SharePointRESTResults>(results());
The results I need should be in the Result2 Class. The problem I have is that this line is setting resultX = to "ConsoleApplication1.SharePointRESTResults" and nothing more. I looked in the JSON Serializing and Deserializing here: JSON Documentation but still cannot get the results into the class so I can pull out the data. I appreciate any help.
The main points are -
The Account Declaration.
JsonProperty attribute.
NOTE : If you have an object Which keys can change, Then you need to use a
Dictionary<string, T>
. A regular class won't work for that; neither will a
List<T>
.
Here's that I have in my WPF application:
public static class MappingCreator
{
public static void CreateMaps()
{
Mapper.CreateMap<SO.Services.Data.ServiceModel.Types.Customer, Customer>();
Mapper.CreateMap<List<SO.Services.Data.ServiceModel.Types.CustomerSearchResult>, List<CustomerSearchResult>>();
Mapper.AssertConfigurationIsValid();
}
}
CreateMaps() is called once on application start.
DTO:
namespace SO.Services.Data.ServiceModel.Types
{
[DataContract]
public class CustomerSearchResult
{
[DataMember]
public int CustomerId { get; set; }
[DataMember]
public string AccountType { get; set; }
[DataMember]
public string ShortName { get; set; }
[DataMember]
public string LegacyName { get; set; }
[DataMember]
public string LegacyContactName { get; set; }
[DataMember]
public string City { get; set; }
[DataMember]
public string StateAbbreviation { get; set; }
[DataMember]
public string Country { get; set; }
[DataMember]
public string PostalCode { get; set; }
}
}
Model:
namespace SO.Models
{
public class CustomerSearchResult : BindableBase
{
public int CustomerId { get; set; }
public string AccountType { get; set; }
public string ShortName { get; set; }
public string LegacyName { get; set; }
public string LegacyContactName { get; set; }
public string City { get; set; }
public string StateAbbreviation { get; set; }
public string Country { get; set; }
public string PostalCode { get; set; }
}
}
Extension method:
public static class DtoMappingExtensions
{
public static List<CustomerSearchResult> ToModels(this List<SO.Services.Data.ServiceModel.Types.CustomerSearchResult> customerSearchList)
{
return Mapper.Map<List<SO.Services.Data.ServiceModel.Types.CustomerSearchResult>, List<CustomerSearchResult>>(customerSearchList);
}
}
I call a servicestack service which returns a List<SO.Services.Data.ServiceModel.Types.CustomerSearchResult> ... when I use the ToModels extension method against it, it returns a List with 0 records, even though the source list had 25k or so records.
I'm stumped.
In your CreateMaps() you would specify the object mappings, not the list mapping.
Mapper.CreateMap<SO.Services.Data.ServiceModel.Types.CustomerSearchResult, CustomerSearchResult>().ReverseMap();
And then in your ToModels() you do
Mapper.Map<List<CustomerSearchResult>, List<SO.Services.Data.ServiceModel.Types.CustomerSearchResult>>(customerSearchList);
I think the problem is here in this line.
Mapper.CreateMap<List<SO.Services.Data.ServiceModel.Types.CustomerSearchResult>, List<CustomerSearchResult>>();
this statement has no need because the AutoMapper will handle the Mapping of the list automatically when you Map the Classes.
I think you should replace the previous statement with this one
Mapper.CreateMap<SO.Services.Data.ServiceModel.Types.CustomerSearchResult, CustomerSearchResult>();
I haven't done anything with JSON before... so I am probably just missing a step.
Here is an example of the JSON I want to deserialise:
{"item":{"icon":"http://services.runescape.com/m=itemdb_rs/4765_obj_sprite.gif?id=4798","icon_large":"http://services.runescape.com/m=itemdb_rs/4765_obj_big.gif?id=4798","id":4798,"type":"Ammo","typeIcon":"http://www.runescape.com/img/categories/Ammo","name":"Adamant brutal","description":"Blunt adamantite arrow...ouch","current":{"trend":"neutral","price":237},"today":{"trend":"neutral","price":0},"members":"true","day30":{"trend":"positive","change":"+1.0%"},"day90":{"trend":"negative","change":"-0.0%"},"day180":{"trend":"positive","change":"+0.0%"}}}
I put this into "Json 2 C#" and ended up creating this new .cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RSTool.Models
{
public class Current
{
public string trend { get; set; }
public int price { get; set; }
}
public class Today
{
public string trend { get; set; }
public int price { get; set; }
}
public class Day30
{
public string trend { get; set; }
public string change { get; set; }
}
public class Day90
{
public string trend { get; set; }
public string change { get; set; }
}
public class Day180
{
public string trend { get; set; }
public string change { get; set; }
}
public class Item
{
public string icon { get; set; }
public string icon_large { get; set; }
public int id { get; set; }
public string type { get; set; }
public string typeIcon { get; set; }
public string name { get; set; }
public string description { get; set; }
public Current current { get; set; }
public Today today { get; set; }
public string members { get; set; }
public Day30 day30 { get; set; }
public Day90 day90 { get; set; }
public Day180 day180 { get; set; }
}
public class RootObject
{
public Item item { get; set; }
}
}
So, I have the class. I can retrieve the JSON from its location as a string, but I really have no idea how to deserialise it... I have installed Newtonsoft.Json and have tried using PopulateObject and also Deserializer but not with any luck...
Assuming that my JSON is stored as a string called "json", how would I go about storing that query and then retrieving the item name, for example?
Use:
var deserialized = JsonConvert.DeserializeObject<RootObject>(json);
I just tested this successfully given the code you supplied.
You can then access properties of object as normal:
MessageBox.Show(deserialized.item.name);