예제 #1
0
 public XlsxTableImporter(
     MappingOptions mappingOptions,
     IRowSaver <T> rowSaver,
     string sheetName = null) : base(mappingOptions, rowSaver)
 {
     _sheetName = sheetName;
 }
예제 #2
0
        void IMappingRule.Execute(IMappingSession session, MappingOptions options, object model, Type type, object source)
        {
            var destProperty = type.GetProperty(_propertyName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public) ?? type.GetProperty(_propertyName);

            var fieldset = source as ArchetypeFieldsetModel;

            if (fieldset == null)
            {
                return;
            }

            if (!fieldset.HasProperty(_propertyAlias) || !fieldset.HasValue(_propertyAlias))
            {
                return;
            }

            var srcValue = fieldset.GetValue <string>(_propertyAlias);

            var helper = new UmbracoHelper(UmbracoContext.Current);

            var node = _isMedia ? helper.TypedMedia(srcValue) : helper.TypedContent(srcValue);

            if (node == null)
            {
                //Orphan node reference, so ignore
                return;
            }

            var mappedNode = session.Map <TModel>(node).WithOptions(options).Single();

            destProperty.SetValue(model, mappedNode);
        }
        void IMappingRule.Execute(IMappingSession session, MappingOptions options, object model, Type type, object source)
        {
            var content = source as IPublishedContent;

            if (content == null)
            {
                throw new Exception("Expected source type IPublishedContent");
            }

            var destProperty = type.GetProperty(_propertyName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public) ?? type.GetProperty(_propertyName);

            var contentValue = _sourceProperty(content);

            if (destProperty.PropertyType.IsInstanceOfType(contentValue))
            {
                destProperty.SetValue(model, contentValue);
            }

            else
            {
                var convert = contentValue.TryConvertTo(destProperty.PropertyType);

                if (convert.Success)
                {
                    destProperty.SetValue(model, convert.Result);
                }
            }
        }
예제 #4
0
        public void ChangeDestinationBeforeMapTest()
        {
            var mappingConfiguration = new MappingConfiguration();

            mappingConfiguration.CreateMapping <PersonFrontModel, Person>(
                f => new Person
            {
                PersonId  = MappingOptions.Ignore(),
                Timestamp = MappingOptions.Ignore(),
                FirstName = MappingOptions.Ignore()
            },
                s => s.SourceNamingConvention(NamingConventionType.CamelCase)
                .DestinationNamingConvention(NamingConventionType.CamelCase)
                .BeforeMap((f, p) =>
            {
                if (p.PersonId == 0)
                {
                    p.PersonId = 10;
                }
                p.FirstName = "Brent";
            }));
            var frontModel = new PersonFrontModel();
            var newPerson  = mappingConfiguration.Convert(frontModel).To <Person>();

            Assert.AreEqual(10, newPerson.PersonId);
            Assert.AreEqual("Brent", newPerson.FirstName);
            var existingPerson = new Person {
                PersonId = 9
            };

            mappingConfiguration.MapData(frontModel, existingPerson);
            Assert.AreEqual(9, existingPerson.PersonId);
            Assert.AreEqual("Brent", existingPerson.FirstName);
        }
예제 #5
0
        public void IgnoreProperty()
        {
            var mapperConfiguration = new MappingConfiguration();

            mapperConfiguration.CreateMapping <Person, PersonReportModel>(p => new PersonReportModel
            {
                Name    = $"{p.FirstName} {p.LastName}",
                Age     = TestHelpers.CalculateAge(p.BirthDate),
                Address = MappingOptions.Ignore()
            });

            var reportModel = mapperConfiguration.Convert <Person, PersonReportModel>(TestData.People.JohnSmith);

            Assert.IsNull(reportModel.Address);
            const string doNotChange   = "DO NOT CHANGE THIS";
            var          existingModel = new PersonReportModel
            {
                Name        = "Test",
                Address     = doNotChange,
                City        = "Test",
                PhoneNumber = "Test",
                Age         = 5
            };

            mapperConfiguration.MapData(TestData.People.JohnSmith, existingModel);
            Assert.AreEqual(doNotChange, existingModel.Address);
        }
        void IMappingRule.Execute(IMappingSession session, MappingOptions options, object model, Type type, object source)
        {
            var content = source as IPublishedContent;

            if (content == null)
            {
                throw new Exception("Expected source type IPublishedContent");
            }

            var destProperty = type.GetProperty(_propertyName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public) ?? type.GetProperty(_propertyName);

            var componentModel = new T();

            //If component was not mapped inline, then we need to fetch it from the mapping registry
            if (_componentMapping == null)
            {
                _componentMapping = Populate.GetMappingForType(typeof(T));

                if (_componentMapping == null)
                {
                    throw new Exception($"No component mapper is defined for type: {typeof(T).FullName}");
                }
            }

            var rules = _componentMapping.GetRules();

            foreach (var rule in rules)
            {
                rule.Execute(session, options, componentModel, typeof(T), content);
            }

            destProperty.SetValue(model, componentModel);
        }
예제 #7
0
        void IMappingRule.Execute(IMappingSession session, MappingOptions options, object model, Type type, object source)
        {
            var content = source as IPublishedContent;

            if (content == null)
            {
                throw new Exception("Expected source type IPublishedContent");
            }

            if (_isLazy && (!options.IncludedProperties.ContainsKey(type) || !options.IncludedProperties[type].Contains(_propertyName)))
            {
                return;
            }

            var destProperty = type.GetProperty(_propertyName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public) ?? type.GetProperty(_propertyName);

            //set to empty list.  This will prevent loading the list again if the nested session.Map<> contains a circular reference
            destProperty.SetValue(model, new List <TModel>());

            var filtered = _filter(content);

            var collection = session.Map <TModel>(filtered).WithOptions(options).List();

            destProperty.SetValue(model, collection);
        }
예제 #8
0
        void IMappingRule.Execute(IMappingSession session, MappingOptions options, object model, Type type, object source)
        {
            var relatedContent = session.Map <TModel>(_filter(new UmbracoHelper(UmbracoContext.Current))).WithOptions(options).Single();

            var destProperty = type.GetProperty(_propertyName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public) ?? type.GetProperty(_propertyName);

            destProperty.SetValue(model, relatedContent);
        }
 public TaskInfo(long ID, byte[] WorkDll, string ReturnIP, int ReturnPort, ReduceOptions reduceOption = ReduceOptions.NONE, MappingOptions mapOption = MappingOptions.NONE)
     : this(reduceOption, mapOption)
 {
     this.ID = ID;
     this.WorkDLL = WorkDll;
     this.ReturnIP = ReturnIP;
     this.ReturnPort = ReturnPort;
 }
예제 #10
0
 public ArchetypeMappingExecutor(IMappingSession session, ArchetypeModel model, string dataType)
 {
     _session  = session;
     _model    = model;
     _type     = typeof(T);
     _results  = new List <T>();
     _options  = new MappingOptions();
     _dataType = dataType;
 }
예제 #11
0
 /// <summary>
 /// Subscribes to all keys or buttons of this device
 /// </summary>
 /// <param name="mappingOptions">Options for the subscription (block, callback to fire etc)</param>
 public void SubscribeAllButtons(MappingOptions mappingOptions)
 {
     AllButtonsMapping = mappingOptions;
     if (!mappingOptions.Concurrent && DeviceWorkerThread == null)
     {
         DeviceWorkerThread = new WorkerThread();
     }
     _isFiltered = true;
 }
예제 #12
0
 /// <summary>
 /// Subscribes to a single key or button of this device
 /// </summary>
 /// <param name="code">The ScanCode (keyboard) or Button Code (mouse) for the key or button</param>
 /// <param name="mappingOptions">Options for the subscription (block, callback to fire etc)</param>
 public void SubscribeSingleButton(ushort code, MappingOptions mappingOptions)
 {
     SingleButtonMappings.TryAdd(code, mappingOptions);
     if (!mappingOptions.Concurrent && !WorkerThreads.ContainsKey(code))
     {
         WorkerThreads.TryAdd(code, new WorkerThread());
     }
     _isFiltered = true;
 }
예제 #13
0
 public CsvTableImporter(
     MappingOptions mappingOptions,
     IRowSaver <T> rowSaver,
     string[] delimiters)
     : base(mappingOptions, rowSaver)
 {
     _encoding   = Encoding.UTF8;
     _delimiters = delimiters;
 }
예제 #14
0
        public void Can_Filter_Binding_Override_From_Assembly()
        {
            var mappingOptions = new MappingOptions();

            mappingOptions.AddBindingOverridesFromAssembly(GetType().Assembly, t => false);
            Assert.IsFalse(
                mappingOptions.Bindings.OfType <BindingApplicator <Source, Target> >().Any()
                );
        }
예제 #15
0
 /// <summary>
 /// Subscribes to Relative mouse movement
 /// </summary>
 /// <param name="mappingOptions">Options for the subscription (block, callback to fire etc)</param>
 /// <returns></returns>
 public void SubscribeMouseMoveRelative(MappingOptions mappingOptions)
 {
     _mouseMoveRelativeMapping = mappingOptions;
     if (!mappingOptions.Concurrent && !WorkerThreads.ContainsKey(8))
     {
         WorkerThreads.TryAdd(8, new WorkerThread());
     }
     _isFiltered = true;
 }
 protected override void ConfigureMapping(IFlashMapperBuilderConfigurator <IgnoreTestSource, Destination> configurator)
 {
     configurator.CreateMapping(s => new Destination
     {
         Data2      = MappingOptions.Ignore(),
         Data4      = MappingOptions.Ignore(),
         Data5      = s.Data3 > 0.5 ? s.Data5 : MappingOptions.Ignore(),
         Data7      = MappingOptions.Ignore(),
         EighthData = MappingOptions.Ignore()
     });
 }
예제 #17
0
 public void Initialize()
 {
     mappingConfiguration.CreateMapping <IgnoreTestSource, Destination>(s => new Destination
     {
         Data2      = MappingOptions.Ignore(),
         Data4      = MappingOptions.Ignore(),
         Data5      = s.Data3 > 0.5 ? s.Data5 : MappingOptions.Ignore(),
         Data7      = MappingOptions.Ignore(),
         EighthData = MappingOptions.Ignore()
     });
 }
예제 #18
0
        public void IgnoreToNullable()
        {
            var mapperConfiguration = new MappingConfiguration();

            mapperConfiguration.CreateMapping <Person, PersonViewModel>(p => new PersonViewModel
            {
                PersonId = MappingOptions.Ignore(),
            });
            var viewModel = mapperConfiguration.Convert(TestData.People.JohnSmith).To <PersonViewModel>();

            Assert.IsNull(viewModel.PersonId);
        }
예제 #19
0
 /// <summary>
 /// Unsubscribes from absolute mouse movement
 /// </summary>
 public void UnsubscribeMouseMoveAbsolute()
 {
     if (_mouseMoveAbsoluteMapping == null)
     {
         return;
     }
     if (!_mouseMoveAbsoluteMapping.Concurrent && WorkerThreads.ContainsKey(7))
     {
         WorkerThreads[7].Dispose();
         WorkerThreads.TryRemove(7, out _);
     }
     _mouseMoveAbsoluteMapping = null;
 }
예제 #20
0
 /// <summary>
 /// Unsubscribes from relative mouse movement
 /// </summary>
 public void UnsubscribeMouseMoveRelative()
 {
     if (_mouseMoveRelativeMapping == null)
     {
         return;
     }
     if (!_mouseMoveRelativeMapping.Concurrent && WorkerThreads.ContainsKey(8))
     {
         WorkerThreads[8].Dispose();
         WorkerThreads.TryRemove(8, out _);
     }
     _mouseMoveRelativeMapping = null;
 }
 protected override void ConfigureMapping(IFlashMapperBuilderConfigurator <PersonFrontModel, Person> configurator)
 {
     configurator.CreateMapping(f => new Person
     {
         Timestamp = MappingOptions.Ignore()
     })
     .AfterMap((f, p) =>
     {
         p.Height = height;
     })
     .SourceNamingConvention(NamingConventionType.CamelCase)
     .DestinationNamingConvention(NamingConventionType.CamelCase);
 }
예제 #22
0
 public void Set(MappingOption opt, string[] symbols, params dynamic[] @params)
 {
     if (!MappingOptions.ContainsKey(opt))
     {
         MappingOptions[opt] = new Dictionary <string, List <dynamic> >();
     }
     foreach (var smb in symbols)
     {
         if (!MappingOptions[opt].ContainsKey(smb))
         {
             MappingOptions[opt].Add(smb, @params.ToList());
         }
     }
 }
예제 #23
0
        /// <summary>
        /// Sets the status of a shardmapping
        /// </summary>
        /// <typeparam name="TMapping">Mapping type.</typeparam>
        /// <typeparam name="TUpdate">Update type.</typeparam>
        /// <typeparam name="TStatus">Status type.</typeparam>
        /// <param name="mapping">Mapping being added.</param>
        /// <param name="status">Status of <paramref name="mapping">mapping</paramref> being added.</param>
        /// <param name="getStatus">Delegate to construct new status from
        /// <paramref name="status">input status</paramref>.</param>
        /// <param name="createUpdate">Delegate to construct new update from new status returned by
        /// <paramref name="getStatus">getStatus</paramref>.</param>
        /// <param name="runUpdate">Delegate to perform update from the <paramref name="mapping">input mapping</paramref> and
        /// the update object returned by <paramref name="getStatus">createUpdate</paramref>.</param>
        /// <param name="lockOwnerId">Lock owner id of this mapping</param>
        /// <param name="options">Options for validation operations to perform on opened connection to affected shard.</param>
        /// <returns></returns>
        protected static TMapping SetStatus <TMapping, TUpdate, TStatus>(
            TMapping mapping,
            TStatus status,
            Func <TStatus, TStatus> getStatus,
            Func <TStatus, TUpdate> createUpdate,
            Func <TMapping, TUpdate, Guid, MappingOptions, TMapping> runUpdate,
            Guid lockOwnerId       = default(Guid),
            MappingOptions options = MappingOptions.Validate)
        {
            TStatus newStatus = getStatus(status);
            TUpdate update    = createUpdate(newStatus);

            return(runUpdate(mapping, update, lockOwnerId, options));
        }
예제 #24
0
        void IMappingRule.Execute(IMappingSession session, MappingOptions options, object model, Type type, object source)
        {
            var content = source as IPublishedContent;

            if (content == null)
            {
                throw new Exception("Expected source type IPublishedContent");
            }

            var relatedContent = session.Map <TModel>(_filter(content)).WithOptions(options).Single();

            var destProperty = type.GetProperty(_propertyName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public) ?? type.GetProperty(_propertyName);

            destProperty.SetValue(model, relatedContent);
        }
예제 #25
0
 /// <summary>
 /// Unsubscribes from a SubscribeAll for this device
 /// </summary>
 public void UnsubscribeAllButtons()
 {
     if (AllButtonsMapping == null)
     {
         return;
     }
     // Stop DeviceWorkerThread
     if (!AllButtonsMapping.Concurrent && DeviceWorkerThread != null)
     {
         DeviceWorkerThread.Dispose();
         DeviceWorkerThread = null;
     }
     AllButtonsMapping = null;
     DisableFilterIfNeeded();
 }
        void IMappingRule.Execute(IMappingSession session, MappingOptions options, object model, Type type, object source)
        {
            if (_isLazy && (!options.IncludedProperties.ContainsKey(type) || !options.IncludedProperties[type].Contains(_propertyName)))
            {
                return;
            }

            var filtered = _filter(new UmbracoHelper(UmbracoContext.Current));

            var collection = session.Map <TModel>(filtered).WithOptions(options).List();

            var destProperty = type.GetProperty(_propertyName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public) ?? type.GetProperty(_propertyName);

            destProperty.SetValue(model, collection);
        }
예제 #27
0
        /// <summary>
        /// Initialize the mapper and scan for profiles
        /// </summary>
        /// <param name="options"></param>
        public static void Initialize(MappingOptions options = MappingOptions.ScanCurrentAssembly)
        {
            var type = typeof(Profile);

            if (options.BitwiseHasFlag(MappingOptions.ScanAllAssemblies))
            {
                // scan all known assemblies in the app domain
                Initialize(AppDomain.CurrentDomain.GetAssemblies());
            }
            else
            {
                // scan the current calling assembly for profiles
                Initialize(new Assembly[] { Assembly.GetCallingAssembly() });
            }
        }
예제 #28
0
        void IMappingRule.Execute(IMappingSession session, MappingOptions options, object model, Type type, object source)
        {
            var dataTypeService = UmbracoContext.Current.Application.Services.DataTypeService;
            var destProperty    = type.GetProperty(_propertyName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public) ?? type.GetProperty(_propertyName);

            ArchetypeModel      srcValue;
            IDataTypeDefinition dataTypeDefinition;

            if (source is ArchetypeFieldsetModel)
            {
                var fieldSet = source as ArchetypeFieldsetModel;
                var property = fieldSet.Properties.FirstOrDefault(x => x.Alias == _propertyAlias);

                srcValue           = fieldSet.GetValue <ArchetypeModel>(_propertyAlias);
                dataTypeDefinition = dataTypeService.GetDataTypeDefinitionById(property.DataTypeId);
            }

            else
            {
                var content     = source as IPublishedContent;
                var srcProperty = content.GetProperty(_propertyAlias);

                if (srcProperty == null)
                {
                    return;
                }

                var propertyType = content.ContentType.GetPropertyType(_propertyAlias);

                dataTypeDefinition = dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeId);

                srcValue = srcProperty.Value as ArchetypeModel;
            }

            if (srcValue == null)
            {
                return;
            }

            if (!srcValue.Any())
            {
                return;
            }

            var archetypeModel = session.Map <T>(srcValue, dataTypeDefinition.Name).Single();

            destProperty.SetValue(model, archetypeModel);
        }
예제 #29
0
        /// <summary>
        /// Returns true if object name should be ignored
        /// </summary>
        /// <param name="name">Property or field name</param>
        /// <param name="path">Full path to object</param>
        /// <param name="options">Comparison options</param>
        /// <param name="ignorePropertiesOrPaths">List of names or paths to ignore</param>
        /// <returns></returns>
        private bool IgnoreObjectName(string name, string path, MappingOptions options, ICollection <string> ignorePropertiesOrPaths, IEnumerable <CustomAttributeData> attributes = null)
        {
            var ignoreByNameOrPath = ignorePropertiesOrPaths?.Contains(name) == true || ignorePropertiesOrPaths?.Contains(path) == true;

            if (ignoreByNameOrPath)
            {
                return(true);
            }
#if FEATURE_CUSTOM_ATTRIBUTES
            if (attributes?.Any(x => !options.BitwiseHasFlag(MappingOptions.DisableIgnoreAttributes) && (_ignoreAttributes.Contains(x.AttributeType) || _ignoreAttributes.Contains(x.AttributeType.Name))) == true)
#else
            if (attributes?.Any(x => !options.BitwiseHasFlag(MappingOptions.DisableIgnoreAttributes) && (_ignoreAttributes.Contains(x.Constructor.DeclaringType) || _ignoreAttributes.Contains(x.Constructor.DeclaringType.Name))) == true)
#endif
            { return(true); }
            return(false);
        }
예제 #30
0
        public void MappingOptionsConstructorTest()
        {
            var mapperOrder = new Type[]
            {
                typeof(AttributeMapper <,>),
                typeof(ManualMapper <,>),
                typeof(ConventionMapper <,>),
            };

            var target      = new MappingOptions(mapperOrder);
            var targetOrder = target.MapperOrder.ToArray();

            for (var i = 0; i < mapperOrder.Length; ++i)
            {
                Assert.AreEqual(mapperOrder[i], targetOrder[i]);
            }
        }
예제 #31
0
        public void MappingOptionsConstructorTest()
        {
            var mapperOrder = new[]
            {
                typeof (AttributeMapper<,>),
                typeof (ManualMapper<,>),
                typeof (ConventionMapper<,>)
            };

            var target = new MappingOptions(mapperOrder);
            Type[] targetOrder = target.MapperOrder.ToArray();

            for (int i = 0; i < mapperOrder.Length; ++i)
            {
                Assert.AreEqual(mapperOrder[i], targetOrder[i]);
            }
        }
예제 #32
0
        protected virtual IMapper <TSource, TTarget> CreateMapper(Type[] innerMappers)
        {
            IMappingRepository repo = null;

            if (innerMappers != null)
            {
                var options = new MappingOptions(innerMappers);
                repo = new MappingRepository(options);
            }
            else
            {
                repo = new MappingRepository();
            }

            var mapper = repo.ResolveMapper <TSource, TTarget>();

            this.AddMappingActions(mapper);
            return(mapper);
        }
        private void FillDictionaryWithMappings(dynamic path, string keyChain, Dictionary<string, string> allPaths, MappingOptions mappingOptions)
        {
            Dictionary<string, object> values = path.ToObject<Dictionary<string, object>>();

            foreach (string key in values.Keys)
            {
                if (values[key] is string)
                {
                    // Ignore everything besides XPaths (for example URLs)
                    if (!IsValidXPath(values[key].ToString()) && mappingOptions == MappingOptions.OnlyXPath)
                        continue;

                    allPaths.Add(keyChain + "/" + key, values[key].ToString());
                }
                else
                {
                    FillDictionaryWithMappings(values[key], keyChain + "/" + key, allPaths, mappingOptions);
                }
            }
        }
		void IMappingRule.Execute(MappingSession session, MappingOptions options, object model,
			Type type, object source) {
			var content = source as IPublishedContent;

			if (content == null) {
				throw new Exception("Expected source type IPublishedContent");
			}

			var destProperty = type.GetProperty(_propertyName, BindingFlags.DeclaredOnly |
				BindingFlags.Instance | BindingFlags.Public) ?? type.GetProperty(_propertyName);

			var contentValue = _sourceProperty(content);

			if (destProperty.PropertyType.IsInstanceOfType(contentValue)) {
				destProperty.SetValue(model, contentValue);
			} else {
				var convert = contentValue.TryConvertTo(destProperty.PropertyType);

				if (convert.Success) {
					destProperty.SetValue(model, convert.Result);
				}
			}
		}
 public TaskInfo(ReduceOptions reduceOption, MappingOptions mapOption)
 {
     this.reduceOption = reduceOption;
     this.mapOption = mapOption;
 }