public string GenerateMessageBody(string template, object model)
        {
            string result = null;

            try
            {
                var engine = EngineFactory.CreateEmbedded(model.GetType());
                //result = engine.ParseString(template, model);

                ITemplateSource   source    = new LoadedTemplateSource(template);
                ModelTypeInfo     modelInfo = new ModelTypeInfo(model.GetType());
                CompilationResult compiled  = engine.Core.CompileSource(source, modelInfo);
                compiled.EnsureSuccessful();

                TemplatePage page = engine.Activate(compiled.CompiledType);
                page.PageContext = new PageContext {
                    ModelTypeInfo = modelInfo
                };

                result = engine.RunTemplate(page, model);
            }
            catch (TemplateCompilationException tex)
            {
                throw new MessageGenerationException($"Error generating message from template! {tex.CompilationErrors.FirstOrDefault()}", tex);
            }
            catch (Exception ex)
            {
                throw new MessageGenerationException("Unexpected error generating message from template!", ex);
            }

            return(result);
        }
Exemplo n.º 2
0
        public void Return_Expando_TemplateType_On_AnonymousObjects()
        {
            var model = new { Title = "Johny" };
            var info  = new ModelTypeInfo(model.GetType());

            Assert.Equal(typeof(ExpandoObject), info.TemplateType);
        }
Exemplo n.º 3
0
        public static object ParseFieldValue(Type modelType, string field, string fieldValue)
        {
            if (String.IsNullOrWhiteSpace(fieldValue) || fieldValue == "*" || fieldValue == "NULL")
            {
                return(null);
            }

            var prop = modelType.GetProperty(field, BindingFlags.Public | BindingFlags.Instance);

            if (prop == null)
            {
                // if not corresponding property was found, it might be custom fields, they are all treated as string
                return(fieldValue);
            }

            if (TypeHelper.IsSimpleType(prop.PropertyType))
            {
                return(LuceneUtility.FromFieldStringValue(fieldValue, prop.PropertyType));
            }

            var propTypeInfo = ModelTypeInfo.GetTypeInfo(prop.PropertyType);

            if (propTypeInfo.IsDictionary)
            {
                return(LuceneUtility.FromFieldStringValue(fieldValue, propTypeInfo.DictionaryValueType));
            }
            else if (propTypeInfo.IsCollection)
            {
                return(LuceneUtility.FromFieldStringValue(fieldValue, propTypeInfo.ElementType));
            }

            return(null);
        }
Exemplo n.º 4
0
        private void InitializeGenerationParameters()
        {
            GenerationParameterValues.Clear();

            if (GetResearchType() == ResearchType.Collection ||
                GetResearchType() == ResearchType.Structural)
            {
                return;
            }

            if (generationType == GenerationType.Static)
            {
                GenerationParameterValues.Add(GenerationParameter.AdjacencyMatrix, null);
                return;
            }

            ModelTypeInfo info = ((ModelTypeInfo[])modelType.GetType().GetField(modelType.ToString()).GetCustomAttributes(typeof(ModelTypeInfo), false))[0];
            Type          t    = Type.GetType(info.Implementation, true);

            RequiredGenerationParameter[] gp = (RequiredGenerationParameter[])t.GetCustomAttributes(typeof(RequiredGenerationParameter), false);
            for (int i = 0; i < gp.Length; ++i)
            {
                GenerationParameter g = gp[i].Parameter;
                if (g != GenerationParameter.AdjacencyMatrix)
                {
                    GenerationParameterInfo[] gInfo = (GenerationParameterInfo[])g.GetType().GetField(g.ToString()).GetCustomAttributes(typeof(GenerationParameterInfo), false);
                    GenerationParameterValues.Add(g, gInfo[0].DefaultValue);
                }
            }
        }
Exemplo n.º 5
0
        public void Return_Current_FriendlyName()
        {
            var info = new ModelTypeInfo(typeof(TestViewModel));

            string expectedTypeName = "RazorLight.Tests.Models.TestViewModel";

            Assert.Equal(info.TemplateTypeName, expectedTypeName);
        }
Exemplo n.º 6
0
        public void Return_Correct_FriendlyName_On_Generic()
        {
            var model = new List <List <TestViewModel> >();
            var info  = new ModelTypeInfo(model.GetType());

            string expectedTypeName = "System.Collections.Generic.List<System.Collections.Generic.List<RazorLight.Tests.Models.TestViewModel>>";

            Assert.Equal(info.TemplateTypeName, expectedTypeName);
        }
Exemplo n.º 7
0
        public void Return_Dynamic_TemplateTypeName_On_AnonymousObjects()
        {
            var model = new { Title = "Jogny" };
            var info  = new ModelTypeInfo(model.GetType());

            string expectedTemplateType = "dynamic";

            Assert.Equal(info.TemplateTypeName, expectedTemplateType);
        }
Exemplo n.º 8
0
        public void Anonymous_Objects_Has_StrongType_False()
        {
            var model = new
            {
                Title = "Johny"
            };

            var info = new ModelTypeInfo(model.GetType());

            Assert.False(info.IsStrongType);
        }
Exemplo n.º 9
0
        public void Ensure_CompiledType_Is_TypeOf_TemplatePage()
        {
            var source    = new LoadedTemplateSource("Hello, @Model.Title");
            var model     = new { Title = "John" };
            var modelInfo = new ModelTypeInfo(model.GetType());

            Type type = testCore.CompileSource(source, modelInfo).CompiledType;
            var  page = Activator.CreateInstance(type);

            Assert.IsAssignableFrom <TemplatePage>(page);
        }
Exemplo n.º 10
0
        public void Ensure_CompileSource_Returns_Correct_CompilationResult()
        {
            var source    = new LoadedTemplateSource("Hello, @Model.Title");
            var model     = new { Title = "John" };
            var modelInfo = new ModelTypeInfo(model.GetType());

            CompilationResult result = testCore.CompileSource(source, modelInfo);

            Assert.NotNull(result);
            Assert.Null(result.CompilationFailures);
            Assert.NotNull(result.CompiledType);
        }
Exemplo n.º 11
0
        public void should_recognize_both_normal_and_collection_properties()
        {
            var prop = new ModelTypeInfo(typeof(MyClass).GetProperty("Name").PropertyType);

            Assert.False(prop.IsCollection);
            Assert.Null(prop.ElementType);
            Assert.False(prop.IsDictionary);
            Assert.Null(prop.DictionaryKeyType);
            Assert.Null(prop.DictionaryValueType);

            prop = new ModelTypeInfo(typeof(MyClass).GetProperty("Prices").PropertyType);
            Assert.True(prop.IsCollection);
            Assert.Equal(typeof(decimal), prop.ElementType);
            Assert.False(prop.IsDictionary);
            Assert.Null(prop.DictionaryKeyType);
            Assert.Null(prop.DictionaryValueType);

            prop = new ModelTypeInfo(typeof(MyClass).GetProperty("Rates").PropertyType);
            Assert.True(prop.IsCollection);
            Assert.Equal(typeof(int), prop.ElementType);
            Assert.False(prop.IsDictionary);
            Assert.Null(prop.DictionaryKeyType);
            Assert.Null(prop.DictionaryValueType);

            prop = new ModelTypeInfo(typeof(MyClass).GetProperty("Categories").PropertyType);
            Assert.True(prop.IsCollection);
            Assert.Equal(typeof(String), prop.ElementType);
            Assert.False(prop.IsDictionary);
            Assert.Null(prop.DictionaryKeyType);
            Assert.Null(prop.DictionaryValueType);

            prop = new ModelTypeInfo(typeof(MyClass).GetProperty("PricesByType").PropertyType);
            Assert.True(prop.IsCollection);
            Assert.Equal(typeof(KeyValuePair <string, decimal>), prop.ElementType);
            Assert.True(prop.IsDictionary);
            Assert.Equal(typeof(string), prop.DictionaryKeyType);
            Assert.Equal(typeof(decimal), prop.DictionaryValueType);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Parses a string
        /// </summary>
        /// <param name="content">Template to parse</param>
        /// <param name="model">Template model</param>
        /// <param name="modelType">Type of the model</param>
        /// <returns></returns>
        public static string ParseString(this IRazorLightEngine engine, string content, object model, Type modelType)
        {
            if (string.IsNullOrEmpty(content))
            {
                throw new ArgumentNullException(nameof(content));
            }

            ITemplateSource templateSource = new LoadedTemplateSource(content);

            ModelTypeInfo     modelTypeInfo = new ModelTypeInfo(modelType);
            CompilationResult result        = engine.Core.CompileSource(templateSource, modelTypeInfo);

            result.EnsureSuccessful();

            TemplatePage page = engine.Activate(result.CompiledType);

            page.PageContext = new PageContext()
            {
                ModelTypeInfo = modelTypeInfo
            };

            return(engine.RunTemplate(page, model));
        }
Exemplo n.º 13
0
        protected virtual void MapComplexProperty(PropertyInfo targetProperty, PropertyInfo sourceProperty, object sourcePropValue, object source, object target, Type sourceType, Type targetType, string propertyPath, MappingContext context)
        {
            object targetPropValue = targetProperty.GetValue(target, null);

            if (context.VisitedObjects.Contains(targetPropValue))
            {
                return;
            }

            var targetPropTypeInfo = ModelTypeInfo.GetTypeInfo(targetProperty.PropertyType);

            if (targetPropTypeInfo.IsCollection)
            {
                var sourcePropTypeInfo = ModelTypeInfo.GetTypeInfo(sourceProperty.PropertyType);

                if (targetPropTypeInfo.IsDictionary)
                {
                    if (sourcePropTypeInfo.IsDictionary)
                    {
                        // Map between dictionaries
                        var targetDic = Activator.CreateInstance(typeof(Dictionary <,>).MakeGenericType(targetPropTypeInfo.DictionaryKeyType, targetPropTypeInfo.DictionaryValueType)) as IDictionary;
                        targetProperty.SetValue(target, targetDic, null);

                        var sourceDic = sourcePropValue as IDictionary;
                        foreach (var key in sourceDic.Keys)
                        {
                            targetDic.Add(key, sourceDic[key]);
                        }
                    }
                    else if (sourcePropTypeInfo.IsCollection)
                    {
                        // source collection element: Name or Key field -> dictionary key, Value field -> dictionary value
                        var keyProp = sourcePropTypeInfo.ElementType.GetProperty("Key", BindingFlags.Public | BindingFlags.Instance);
                        if (keyProp == null)
                        {
                            keyProp = sourcePropTypeInfo.ElementType.GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
                        }

                        if (keyProp != null)
                        {
                            var valueProp = sourcePropTypeInfo.ElementType.GetProperty("Value", BindingFlags.Public | BindingFlags.Instance);
                            if (valueProp != null)
                            {
                                var targetDic = Activator.CreateInstance(typeof(Dictionary <,>).MakeGenericType(targetPropTypeInfo.DictionaryKeyType, targetPropTypeInfo.DictionaryValueType)) as IDictionary;
                                foreach (var item in sourcePropValue as IEnumerable)
                                {
                                    var key   = keyProp.GetValue(item, null);
                                    var value = valueProp.GetValue(item, null);
                                    targetDic.Add(key, value);
                                }

                                targetProperty.SetValue(target, targetDic, null);
                            }
                        }
                    }
                }
                else // List or Array
                {
                    var sourceElementType = sourcePropTypeInfo.ElementType;

                    var elementMapper = GetMapperOrDefault(sourceElementType, targetPropTypeInfo.ElementType);
                    if (elementMapper == null)
                    {
                        return;
                    }

                    var targetList = Activator.CreateInstance(typeof(List <>).MakeGenericType(targetPropTypeInfo.ElementType));
                    var addMethod  = targetList.GetType().GetMethod("Add", BindingFlags.Public | BindingFlags.Instance, null, new[] { targetPropTypeInfo.ElementType }, null);

                    var sourceList    = sourcePropValue as IEnumerable;
                    var elementPrefix = propertyPath + ".";
                    var totalElements = 0;

                    foreach (var sourceElement in sourceList)
                    {
                        var targetElement = elementMapper.Map(sourceElement, Activator.CreateInstance(targetPropTypeInfo.ElementType), sourceElementType, targetPropTypeInfo.ElementType, elementPrefix, context);
                        addMethod.Invoke(targetList, new[] { targetElement });
                        totalElements++;
                    }

                    if (!Object.ReferenceEquals(targetList, targetPropValue))
                    {
                        if (targetProperty.PropertyType.IsArray)
                        {
                            var array = Array.CreateInstance(targetPropTypeInfo.ElementType, totalElements);
                            var i     = 0;
                            foreach (var item in targetList as IEnumerable)
                            {
                                array.SetValue(item, i);
                                i++;
                            }

                            targetProperty.SetValue(target, array, null);
                        }
                        else
                        {
                            targetProperty.SetValue(target, targetList, null);
                        }
                    }
                }
            }
            else
            {
                var mapper = GetMapperOrDefault(sourceProperty.PropertyType, targetProperty.PropertyType);
                if (mapper != null)
                {
                    if (targetPropValue == null)
                    {
                        targetPropValue = Activator.CreateInstance(targetProperty.PropertyType);
                    }

                    targetPropValue = mapper.Map(sourcePropValue, targetPropValue, sourceProperty.PropertyType, targetProperty.PropertyType, propertyPath + ".", context);

                    targetProperty.SetValue(target, targetPropValue, null);
                }
            }
        }
Exemplo n.º 14
0
        private ReadSubscription CreateConsumerSubscription(ModelTypeInfo typeInfo, Func <IConsumerFactory> consumerFactoryBuilder)
        {
            bool useConsumerFactory = consumerFactoryBuilder != null;

            TypeDeliveryResolver   resolver           = new TypeDeliveryResolver();
            TypeDeliveryDescriptor consumerDescriptor = resolver.Resolve(typeInfo.ConsumerType, null);
            TypeDeliveryDescriptor modelDescriptor    = resolver.Resolve(typeInfo.ModelType, Configurator);
            var target = GetTarget(typeInfo.Source, consumerDescriptor, modelDescriptor);

            object consumerInstance = useConsumerFactory ? null : Activator.CreateInstance(typeInfo.ConsumerType);

            ConsumerExecuter executer = null;

            switch (typeInfo.Source)
            {
            case ReadSource.Queue:
            {
                Type executerType        = typeof(QueueConsumerExecuter <>);
                Type executerGenericType = executerType.MakeGenericType(typeInfo.ModelType);
                executer = (ConsumerExecuter)Activator.CreateInstance(executerGenericType,
                                                                      typeInfo.ConsumerType,
                                                                      consumerInstance,
                                                                      consumerFactoryBuilder);
                break;
            }

            case ReadSource.Direct:
            {
                Type executerType        = typeof(DirectConsumerExecuter <>);
                Type executerGenericType = executerType.MakeGenericType(typeInfo.ModelType);
                executer = (ConsumerExecuter)Activator.CreateInstance(executerGenericType,
                                                                      typeInfo.ConsumerType,
                                                                      consumerInstance,
                                                                      consumerFactoryBuilder);
                break;
            }

            case ReadSource.Request:
            {
                Type executerType        = typeof(RequestHandlerExecuter <,>);
                Type executerGenericType = executerType.MakeGenericType(typeInfo.ModelType, typeInfo.ResponseType);
                executer = (ConsumerExecuter)Activator.CreateInstance(executerGenericType,
                                                                      typeInfo.ConsumerType,
                                                                      consumerInstance,
                                                                      consumerFactoryBuilder);
                break;
            }
            }

            if (executer != null)
            {
                executer.Resolve(Configurator);
            }

            ReadSubscription subscription = new ReadSubscription
            {
                Source           = typeInfo.Source,
                Queue            = target.Item1,
                ContentType      = target.Item2,
                MessageType      = typeInfo.ModelType,
                ResponseType     = typeInfo.ResponseType,
                Action           = null,
                ConsumerExecuter = executer
            };

            return(subscription);
        }
Exemplo n.º 15
0
        public static object ToModel(Document document, Type modelType)
        {
            var model = Activator.CreateInstance(modelType);

            foreach (var prop in modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (TypeHelper.IsSimpleType(prop.PropertyType))
                {
                    var field = document.GetField(prop.Name);
                    if (field != null)
                    {
                        var propValue = LuceneUtility.FromFieldStringValue(field.StringValue, prop.PropertyType);
                        prop.SetValue(model, propValue, null);
                    }
                }
                else
                {
                    var propTypeInfo = ModelTypeInfo.GetTypeInfo(prop.PropertyType);
                    if (propTypeInfo.IsCollection)
                    {
                        if (propTypeInfo.IsDictionary)
                        {
                            var propValue = prop.GetValue(model, null);
                            if (propValue == null)
                            {
                                propValue = Activator.CreateInstance(typeof(Dictionary <,>).MakeGenericType(propTypeInfo.DictionaryKeyType, propTypeInfo.DictionaryValueType));
                                prop.SetValue(model, propValue, null);
                            }

                            var dic    = propValue as IDictionary;
                            var fields = document.GetFields().Where(f => f.Name.StartsWith(prop.Name));

                            // Property type is IDictionary<TKey, TValue>
                            if (TypeHelper.IsSimpleType(propTypeInfo.DictionaryValueType))
                            {
                                foreach (var field in fields)
                                {
                                    string propName;
                                    string dicKey;

                                    if (TryParseDictionaryFieldName(field.Name, out propName, out dicKey))
                                    {
                                        var fieldValue = LuceneUtility.FromFieldStringValue(field.StringValue, propTypeInfo.DictionaryValueType);
                                        dic.Add(dicKey, fieldValue);
                                    }
                                }
                            }
                            else // Property type is IDictionary<TKey, IList<TValue>> or IDictionary<TKey, ISet<TValue>>
                            {
                                var dicValueTypeInfo = ModelTypeInfo.GetTypeInfo(propTypeInfo.DictionaryValueType);
                                if (dicValueTypeInfo.IsCollection && TypeHelper.IsSimpleType(dicValueTypeInfo.ElementType))
                                {
                                    Type       newDicValueType  = null;
                                    MethodInfo hashsetAddMethod = null;
                                    if (dicValueTypeInfo.IsSet)
                                    {
                                        newDicValueType  = typeof(HashSet <>).MakeGenericType(dicValueTypeInfo.ElementType);
                                        hashsetAddMethod = GetAddMethod(newDicValueType, dicValueTypeInfo.ElementType);
                                    }
                                    else
                                    {
                                        newDicValueType = typeof(List <>).MakeGenericType(dicValueTypeInfo.ElementType);
                                    }

                                    foreach (var field in fields)
                                    {
                                        string propName;
                                        string dicKey;

                                        if (TryParseDictionaryFieldName(field.Name, out propName, out dicKey))
                                        {
                                            var fieldValue = LuceneUtility.FromFieldStringValue(field.StringValue, dicValueTypeInfo.ElementType);
                                            if (!dic.Contains(dicKey))
                                            {
                                                dic.Add(dicKey, Activator.CreateInstance(newDicValueType));
                                            }

                                            var list = dic[dicKey];

                                            if (dicValueTypeInfo.IsSet) // is HashSet<>
                                            {
                                                hashsetAddMethod.Invoke(list, new[] { fieldValue });
                                            }
                                            else // is IList<>
                                            {
                                                (list as IList).Add(fieldValue);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else // Property is collection but not dictionary
                        {
                            var fields = document.GetFields(prop.Name);
                            if (fields.Length == 0)
                            {
                                continue;
                            }

                            var list = Activator.CreateInstance(typeof(List <>).MakeGenericType(propTypeInfo.ElementType)) as IList;

                            foreach (var field in fields)
                            {
                                var fieldValue = LuceneUtility.FromFieldStringValue(field.StringValue, propTypeInfo.ElementType);
                                list.Add(fieldValue);
                            }

                            if (prop.PropertyType.IsArray)
                            {
                                prop.SetValue(model, list.OfType <object>().ToArray(), null);
                            }
                            else
                            {
                                prop.SetValue(model, list, null);
                            }
                        }
                    }
                }
            }

            return(model);
        }
Exemplo n.º 16
0
        static IEnumerable <IFieldable> ToFields(object container, PropertyInfo property)
        {
            var fieldAttr = property.GetCustomAttribute <FieldAttribute>(false) ?? new FieldAttribute(Field.Index.NOT_ANALYZED, Field.Store.YES);
            var propType  = ModelTypeInfo.GetTypeInfo(property.PropertyType);

            if (propType.IsSimpleType)
            {
                var propValue = property.GetValue(container, null);
                yield return(fieldAttr.CreateLuceneField(property.Name, propValue));
            }
            else
            {
                if (propType.IsCollection)
                {
                    if (propType.IsDictionary)
                    {
                        if (!TypeHelper.IsSimpleType(propType.DictionaryKeyType))
                        {
                            throw new NotSupportedException("Not support complex dictionary key.");
                        }

                        if (TypeHelper.IsSimpleType(propType.DictionaryValueType))
                        {
                            var dic = property.GetValue(container, null) as IDictionary;
                            foreach (DictionaryEntry entry in dic)
                            {
                                var fieldName = GetDictionaryFieldName(property.Name, entry.Key.ToString());
                                yield return(fieldAttr.CreateLuceneField(fieldName, entry.Value));
                            }
                        }
                        else
                        {
                            var valueTypeInfo = ModelTypeInfo.GetTypeInfo(propType.DictionaryValueType);
                            if (valueTypeInfo.IsCollection && !valueTypeInfo.IsDictionary && TypeHelper.IsSimpleType(valueTypeInfo.ElementType))
                            {
                                var dic = property.GetValue(container, null) as IDictionary;
                                foreach (DictionaryEntry entry in dic)
                                {
                                    var fieldName = GetDictionaryFieldName(property.Name, entry.Key.ToString());
                                    var values    = entry.Value as IEnumerable;
                                    foreach (var value in values)
                                    {
                                        yield return(fieldAttr.CreateLuceneField(fieldName, value));
                                    }
                                }
                            }
                            else
                            {
                                throw new NotSupportedException("Not support dictionary property with value type other than simple type and simple type collection.");
                            }
                        }
                    }
                    else
                    {
                        if (!TypeHelper.IsSimpleType(propType.ElementType))
                        {
                            throw new NotSupportedException("Not support complex collection element.");
                        }

                        var items = property.GetValue(container, null) as IEnumerable;
                        if (items != null)
                        {
                            foreach (var item in items)
                            {
                                yield return(fieldAttr.CreateLuceneField(property.Name, item));
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 17
0
        public void Real_Object_Is_StrongType_True()
        {
            var info = new ModelTypeInfo(typeof(TestViewModel));

            Assert.True(info.IsStrongType);
        }
Exemplo n.º 18
0
        public void Return_Same_Type_On_StrongType()
        {
            var info = new ModelTypeInfo(typeof(TestViewModel));

            Assert.Equal(typeof(TestViewModel), info.TemplateType);
        }