private void DiscoverPropertyMappings() { lock (this) { // in a multi-threaded environment, this CAN be true, so we need to check again if (!mappingsDiscovered) { if (Options.AutoAddPropertiesWithSameName) { // TODO: allow to ignore properties! PropertyInfo[] sourceProps = SourceType.GetProperties(); foreach (PropertyInfo destProp in DestinationType.GetProperties()) { PropertyInfo sourceProp = sourceProps.FirstOrDefault(_ => _.Name == destProp.Name); if (sourceProp != null) { mappings.Add(destProp, (object source) => sourceProp.GetValue(source)); } } } // todo: the current mappings won't be on PropertyInfo, Func<object, object>. Now it's the time to convert them! mappingsDiscovered = true; } } }
public PrismicMappingContext(string documentType = null) { _destination = new T(); DestinationType = _destination.GetType(); var destinationProperties = DestinationType.GetProperties(); DestinationMappings = GetPropertyMappings(destinationProperties); if (!string.IsNullOrWhiteSpace(documentType)) { DocumentType = documentType; return; } var docType = DestinationType.GetCustomAttribute <PrismicDocumentAttribute>(); if (docType == null) { throw new Exception("Prismic DocumentAttribute is required"); } if (string.IsNullOrWhiteSpace(docType.Name)) { throw new Exception("Document name is required"); } DocumentType = docType.Name; }
private bool CheckIfDestinationIsComplex() { return(DestinationType .GetProperties() .Any(x => x.PropertyType.IsClass && !PrimitiveTypes.Contains(x.PropertyType))); }
private TDestination SetValues(TSource source) { var sourceProperties = typeof(TSource).GetProperties(); var destinationProperties = DestinationType.GetProperties(); TDestination destination = Activator.CreateInstance <TDestination>(); foreach (var sourceProperty in sourceProperties) { var propertyName = sourceProperty.Name.ToLower(); try { if ((sourceProperty.PropertyType.IsClass || sourceProperty.PropertyType.IsValueType) && !PrimitiveTypes.Contains(sourceProperty.PropertyType)) { var destinationComplexProperties = destinationProperties .Where(x => x.Name.ToLower().StartsWith(propertyName)); if (destinationComplexProperties.Any()) { if (destinationComplexProperties.Count() == 1) { var destinationComplexProperty = destinationComplexProperties.First(); if (destinationComplexProperty.PropertyType == sourceProperty.PropertyType && destinationComplexProperty.Name.ToLower() == propertyName) { var sourceValue = sourceProperty.GetValue(source); destinationComplexProperty.SetValue(destination, sourceValue); continue; } } SetComplexProperties(source, destination, sourceProperty, destinationComplexProperties, 1); } } else { var destinationProperty = destinationProperties .FirstOrDefault(x => x.Name.ToLower() == propertyName && x.PropertyType == sourceProperty.PropertyType); if (destinationProperty != null) { var sourceValue = sourceProperty.GetValue(source); destinationProperty.SetValue(destination, sourceValue); } } } catch (Exception) { continue; } } return(destination); }