I have following Json
"{\"Message\":\"The content you are deleting is associated with some other mashups.\",\"MashupList\":{\"70592\":\"low Frame Rated test\",\"70851\":\"low Frame Rated test\"}}"
I am unable to deserilize the MashupList part of this json. 70592 and 70851 are not the fixed attibutes they can be changed
what i have done so far
[DataContract]
public class CustomBaseAffectedMashupsResponse
{
[DataMember(Name = "MashupList")]
public MashupList MashupsList { get; set; }
[DataMember(Name = "Message")]
public String Message { get; set; }
}
[DataContract]
public class MashupList
{
[DataMember]
public List<String> MashupTitle { get; set; }
}
And the deserialize method
public static T Deserialise<T>(string json )
{
T obj = default(T);
try {
obj = JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
return obj;
} catch (Exception Exception)
{
return obj;
}
}
it is not giving any error but i dont know why it does not deserilize MashupList part
I don't have enough reputation to comment so i am adding comment here it does not show any error but does not deserialize the
"MashupList\":{\"70592\":\"low Frame Rated test\",\"70851\":\"low Frame Rated test\"}
The MashupList property's type should be Dictionary<string, string>.
You don't need the MashupList class.
The keys are the numbers - 70592, 70592. The values are the strings, e.g. low Frame Rated test.
class CustomBaseAffectedMashupsResponse
{
public Dictionary<string, string> MashupList { get; set; }
public string Message { get; set; }
}
Related
I am using CQRS. I select my Entities IEnumerator from database and i want to map this to my Dto class.
My Dto class:
public class XCollectionDto
{
public IEnumerable<XReadDto> Entries { get; init; } = Enumerable.Empty<XReadDto>();
}
My mapper class:
public class XReadMapper : IEntityToDtoMapper<X, XCollectionDto>
{
public XCollectionDto Map(IEnumerable <X> source, XCollectionDto target)
{
//todo
Here i want to map source to target Entries list
}
}
How can i do that, without a for loop? I am not using AutoMaper, the mapping is manual
I think you could accompish your purpose with C# reflection
I created the two class for test:
public class somemodel
{
public int Id { get; set; }
public string Name { get; set; }
public List<int> Numlist { get; set; }
}
public class somemodelDTO
{
public int Id { get; set; }
public string SomeName { get; set; }
public List<int> Numlist { get; set; }
}
the method to bind properties of somemodelDTO which have the same name with properties of somemodel:
private static somemodelDTO GetMap<somemodel, somemodelDTO>(somemodel some)
{
somemodelDTO somemDTO = Activator.CreateInstance<somemodelDTO>();
var typesource = some.GetType();
var typedestination = typeof(somemodelDTO);
foreach(var sp in typesource.GetProperties())
{
foreach( var dp in typedestination.GetProperties())
{
if(sp.Name==dp.Name)
{
dp.SetValue(somemDTO, sp.GetValue(some, null), null);
}
}
}
return somemDTO;
}
The result:
I'm trying to map objects with AutoMapper. I've created the HTTP POST controller method, which should create the new Part object to database. It should add data to both entities, Part and PartAvailabilites. Database is already existing and is scaffolded by EF Core. The error I'm receiving is:
AutoMapper created this type map for you, but your types cannot be mapped using the current configuration Part -> PartDto (Destination member list)PartManagement.Entities.Part -> PartManagement.Dto.PartDto (Unmapped properties:Balance)"
Does anyone know what could be the problem with this mapping? I tried to do the mapping in several ways but none of them is working.
Here is my mapping:
CreateMap<PartDto, PartEntity>()
.ForMember(dest => dest.FkPartAvailability,
opts => opts.MapFrom(src => new PartAvailabilities
{
Balance = src.Balance
}));
Example JSON request:
{
"name": "testPart",
"catalogNumber": 12345,
"balance": 10
}
Here are my entity classes:
public class Part
{
public long Id { get; set; }
public int PartNumber { get; set; }
public string Name { get; set; }
public PartAvailabilities FkPartAvailability { get; set; }
}
public class PartAvailabilities
{
public PartAvailabilities()
{
Parts = new HashSet<Part>();
}
public long Id { get; set; }
public decimal Balance { get; set; }
public ICollection<Part> Parts { get; set; }
}
public class PartDto
{
public string Name { get; set; }
public int PartNumber { get; set; }
public decimal Balance { get; set; }
}
This is Create method in the ManagementService class:
public async Task<PartDto> Create(PartDto request)
{
var part = _mapper.Map<PartDto, PartEntity>(request);
var createdPart = partRepository.Add(part);
await partRepository.UnitOfWork.SaveChangesAsync();
return _mapper.Map<PartDto>(createdPart);
}
And here is HttpPost method from controller:
[HttpPost]
public async Task<IActionResult> Part_Create([FromBody] PartDto request)
{
PartDto createdPart;
try
{
if (request != null)
{
createdPart = await _partManagementService.Create(request);
return Ok(request);
}
}
catch(Exception ex)
{
return BadRequest(ex.Message);
}
return Ok(new string[] { "Part created" });
}
The message is trying to tell you that there is no map between Part and PartDto. AM will create a map for you, but that map is not valid, because PartDto.Balance cannot be mapped. So you have to create the map and tell AM how to map Balance. Things might be easier to understand if you set CreateMissingTypeMaps to false.
I'm having problems resolving this error message. I've looked at some other answers on here and changed some things but I still receive this error:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Clocker.Models.PeopleLocationForUser]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
This is my class:
namespace Clocker.Models
{
public class PeopleLocationForUser
{
string locationPeople { get; set; }
public users users { get; set; }
}
public class users
{
public int EB_Counter { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int TATokenValue { get; set; }
}
}
This is the method that errors on the deserialize line:
public static async Task<PeopleLocationForUser> GetPeopleLocationForUser(string UserName, int LocationId)
{
Uri uri = new Uri(URL + "GetPeopleLocationForUser" + "?username=" + UserName + "&locationid=" + LocationId);
HttpClient myClient = new HttpClient();
var response = await myClient.GetAsync(uri);
var content = await response.Content.ReadAsStringAsync();
var test = JsonConvert.DeserializeObject<List<PeopleLocationForUser>>(content);
//return something when it's working
return null;
}
This is the start of the Json data:
{"result":true,"locationPeople":[{"EB_Counter":101,"FirstName":"RSS","LastName":"13.11.1","TATokenValue":"TS_101_1_RSS_SWIPE"},{"EB_Counter":102,"FirstName":"RSS","LastName":"13.11.2","TATokenValue":"TS_102_1_RSS_SWIPE"},{"EB_Counter":93,"FirstName":"RSS","LastName":"13.7.1","TATokenValue":"TS_93_1_RSS_SWIPE"},{"EB_Counter":94,"FirstName":"RSS","LastName":"13.7.10","TATokenValue":"TS_94_1_RSS_SWIPE"},{"EB_Counter":95,"FirstName":"RSS","LastName":"13.8.2","TATokenValue":"TS_95_1_RSS_SWIPE"},{"EB_Counter":99,"FirstName":"RSS","LastName":"13.9.2","TATokenValue":"TS_99_1_RSS_SWIPE"},
This is what my Json data looks like when it arrives:
I hope you can help. The end result is that I'm trying to get this data into a list so I can use it in a Xamarin ListView.
You are receiving list and in the class you are expecting just one instance of user, this is how the class should be:
public class LocationPeople
{
public int EB_Counter { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string TATokenValue { get; set; }
}
public class RootObject
{
public bool result { get; set; }
public List<LocationPeople> locationPeople { get; set; }
}
var test = JsonConvert.DeserializeObject<RootObject>(content);
Am Trying to Print out a student Identity Card using crystal report but all what i could get was this error popping up The data source object is invalid.
Guys please help me to check on this code if am making any mistake...
this is the model
public class CardModel
{
// Properties
public string Department { get; set; }
public string ExpiryDate { get; set; }
public string FirstName { get; set; }
public Sex Gender { get; set; }
public Guid Id { get; set; }
public string MiddleName { get; set; }
public string RegistrationNo { get; set; }
public byte[] SecuritySign { get; set; }
public byte[] StudentPhoto { get; set; }
public string Surname { get; set; }
}
public static class CardModelExtention
{
public static CardModel ToCardModel(this Student identity)
{
return new CardModel
{
Id = identity.Id,
FirstName = identity.FirstName,
MiddleName = identity.MiddleName,
Surname = identity.Surname,
StudentPhoto = identity.Photo.RawPhoto,
SecuritySign = identity.SecuritySignature.RawSignature,
Gender = identity.Sex,
ExpiryDate = identity.ExpiryDate,
Department = identity.Department.DepartmentName,
RegistrationNo = identity.RegistrationNo
};
}
}
and here is the service am using to pull the information from database
public class StudentService : IStudentService
{
ERMUoW _ow;
public StudentService()
{
_ow = new ERMUoW();
}
public CardModel GetStudentById(Guid id)
{
CardModel obj3 = new CardModel();
Student student = _ow.Students.GetAllIncluding(new Expression<Func<Student, object>>[] { st => st.Photo, st => st.Signature, st => st.SecuritySignature, st => st.Department }).Where(x => x.Id == id).SingleOrDefault();
var cardInfo = student.ToCardModel();
return cardInfo;
}
}
public interface IStudentService
{
CardModel GetStudentById(Guid id);
}
This is it and everything around here is working fine and am getting the data very well but when I send it to the method in my contrller that generate the identity card I get that error message
this is the code that generate the card using crytal report
public ActionResult PrintCard(Guid id)
{
var student = _studentCardService.GetStudentById(id);
ReportDocument read = new ReportDocument();
read.Load(Server.MapPath("~/Reports/rpt_StudentCard.rpt"));
read.SetDataSource(student);
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
try
{
Stream stream = read.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "StudentIdentityCard.pdf");
}
catch (Exception ex)
{
throw ex;
}
}
I will really Appreciate your help thank you...
The data source have to be a List of elements... not a single element.
I keep coming across an i18n requirement where my data (not my UI) needs to be internationalized.
public class FooEntity
{
public long Id { get; set; }
public string Code { get; set; } // Some values might not need i18n
public string Name { get; set } // but e.g. this needs internationalized
public string Description { get; set; } // and this too
}
What are some approaches I could use?
Some things I've tried:-
1) Store a resource key in the db
public class FooEntity
{
...
public string NameKey { get; set; }
public string DescriptionKey { get; set; }
}
Pros: No need for complicated queries to get a translated entity. System.Globalization handles fallbacks for you.
Cons: Translations can't easily be managed by an admin user (have to deploy resource files whenever my Foos change).
2) Use a LocalizableString entity type
public class FooEntity
{
...
public int NameId { get; set; }
public virtual LocalizableString Name { get; set; }
public int NameId { get; set; }
public virtual LocalizableString Description { get; set; }
}
public class LocalizableString
{
public int Id { get; set; }
public ICollection<LocalizedString> LocalizedStrings { get; set; }
}
public class LocalizedString
{
public int Id { get; set; }
public int ParentId { get; set; }
public virtual LocalizableString Parent { get; set; }
public int LanguageId { get; set; }
public virtual Language Language { get; set; }
public string Value { get; set; }
}
public class Language
{
public int Id { get; set; }
public string Name { get; set; }
public string CultureCode { get; set; }
}
Pros: All localised strings in the same table. Validation can be performed per-string.
Cons: Queries are horrid. Have to .Include the LocalizedStrings table once for each localizable string on the parent entity. Fallbacks are hard and involve extensive joining. Haven't found a way to avoid N+1 when retrieving e.g. data for a table.
3) Use a parent entity with all the invariant properties and child entities containing all the localized properties
public class FooEntity
{
...
public ICollection<FooTranslation> Translations { get; set; }
}
public class FooTranslation
{
public long Id { get; set; }
public int ParentId { get; set; }
public virtual FooEntity Parent { get; set; }
public int LanguageId { get; set; }
public virtual Language Language { get; set; }
public string Name { get; set }
public string Description { get; set; }
}
public class Language
{
public int Id { get; set; }
public string Name { get; set; }
public string CultureCode { get; set; }
}
Pros: Not as hard (but still too hard!) to get a full translation of an entity into memory.
Cons: Double the number of entities. Can't handle partial translations of an entity - especially the case where, say, Name is coming from es but Description is coming from es-AR.
I have three requirements for a solution
Users can edit entities, languages, and translations at runtime
Users can supply partial translations with missing strings coming from a fallback as per System.Globalization
Entities can be brought into memory without running into e.g. N+1 issues
Why don't you take the best of both worlds?
Have a CustomResourceManager that handles the loading of resources and picking the right culture and use a CustomResourceReader that uses whatever backing store you like. A basic implementation could look like this, relying on convention of the Resourceky being Typename_PropertyName_PropertyValue. If for some reason the structure of the backingstore(csv/excel/mssql/table structure) need to change you only have the change the implementation of the ResourceReader.
As an added bonus I also got the real/transparent proxy going.
ResourceManager
class MyRM:ResourceManager
{
readonly Dictionary<CultureInfo, ResourceSet> sets = new Dictionary<CultureInfo, ResourceSet>();
public void UnCache(CultureInfo ci)
{
sets.Remove(ci):
}
protected override ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
{
ResourceSet set;
if (!sets.TryGetValue(culture, out set))
{
IResourceReader rdr = new MyRR(culture);
set = new ResourceSet(rdr);
sets.Add(culture,set);
}
return set;
}
// sets Localized values on properties
public T GetEntity<T>(T obj)
{
var entityType = typeof(T);
foreach (var prop in entityType.GetProperties(
BindingFlags.Instance
| BindingFlags.Public)
.Where(p => p.PropertyType == typeof(string)
&& p.CanWrite
&& p.CanRead))
{
// FooEntity_Name_(content of Name field)
var key = String.Format("{0}_{1}_{2}",
entityType.Name,
prop.Name,
prop.GetValue(obj,null));
var val = GetString(key);
// only set if a value was found
if (!String.IsNullOrEmpty(val))
{
prop.SetValue(obj, val, null);
}
}
return obj;
}
}
ResourceReader
class MyRR:IResourceReader
{
private readonly Dictionary<string, string> _dict;
public MyRR(CultureInfo ci)
{
_dict = new Dictionary<string, string>();
// get from some storage (here a hardcoded Dictionary)
// You have to be able to deliver a IDictionaryEnumerator
switch (ci.Name)
{
case "nl-NL":
_dict.Add("FooEntity_Name_Dutch", "nederlands");
_dict.Add("FooEntity_Name_German", "duits");
break;
case "en-US":
_dict.Add("FooEntity_Name_Dutch", "The Netherlands");
break;
case "en":
_dict.Add("FooEntity_Name_Dutch", "undutchables");
_dict.Add("FooEntity_Name_German", "german");
break;
case "": // invariant
_dict.Add("FooEntity_Name_Dutch", "dutch");
_dict.Add("FooEntity_Name_German", "german?");
break;
default:
Trace.WriteLine(ci.Name+" has no resources");
break;
}
}
public System.Collections.IDictionaryEnumerator GetEnumerator()
{
return _dict.GetEnumerator();
}
// left out not implemented interface members
}
Usage
var rm = new MyRM();
var f = new FooEntity();
f.Name = "Dutch";
var fl = rm.GetEntity(f);
Console.WriteLine(f.Name);
Thread.CurrentThread.CurrentUICulture = new CultureInfo("nl-NL");
f.Name = "Dutch";
var dl = rm.GetEntity(f);
Console.WriteLine(f.Name);
RealProxy
public class Localizer<T>: RealProxy
{
MyRM rm = new MyRM();
private T obj;
public Localizer(T o)
: base(typeof(T))
{
obj = o;
}
public override IMessage Invoke(IMessage msg)
{
var meth = msg.Properties["__MethodName"].ToString();
var bf = BindingFlags.Public | BindingFlags.Instance ;
if (meth.StartsWith("set_"))
{
meth = meth.Substring(4);
bf |= BindingFlags.SetProperty;
}
if (meth.StartsWith("get_"))
{
// get the value...
meth = meth.Substring(4);
var key = String.Format("{0}_{1}_{2}",
typeof (T).Name,
meth,
typeof (T).GetProperty(meth, BindingFlags.Public | BindingFlags.Instance
|BindingFlags.GetProperty).
GetValue(obj, null));
// but use it for a localized lookup (rm is the ResourceManager)
var val = rm.GetString(key);
// return the localized value
return new ReturnMessage(val, null, 0, null, null);
}
var args = new object[0];
if (msg.Properties["__Args"] != null)
{
args = (object[]) msg.Properties["__Args"];
}
var res = typeof (T).InvokeMember(meth,
bf
, null, obj, args);
return new ReturnMessage(res, null, 0, null, null);
}
}
Real/Transparent proxy usage
var f = new FooEntity();
f.Name = "Dutch";
var l = new Localizer<FooEntity>(f);
var fp = (FooEntity) l.GetTransparentProxy();
fp.Name = "Dutch"; // notice you can use the proxy as is,
// it updates the actual FooEntity
var localizedValue = fp.Name;
First one is worthy if you have static content in database. For example if you have categories that relatively are not going to be changed by user. You can change them at next deploy. I do not like this solution personally. I do not consider this as a nice solution. This is just an escape of the problem.
Second one is the best but can cause a problem when you have two or more localizable fields in one entity. You can simplify it a bit and hard code languages on it like this
public class LocalizedString
{
public int Id { get; set; }
public string EnglishText { get; set; }
public string ItalianText { get; set; }
public string ArmenianText { get; set; }
}
Third one is not a good one neither. From this structure I can't be sure that all nodes (literals, lines, strings etc.) translated in specific culture.
Do not generalize too much. Each problem is kind of specialized and it needs specialized solution too. Too much generalization makes unjustified issues.