Example #1
0
        protected T ExecuteOrdinal <T>(String sql, IDictionary <String, Object> pars = null)
        {
            SQLiteConnection c      = null;
            SQLiteDataReader reader = null;

            try
            {
                c = Connect();

                SQLiteCommand command = new SQLiteCommand(sql, c);
                ParseParameters(pars, command);
                reader = command.ExecuteReader();
                if (reader.Read())
                {
                    var value = UniversalTypeConverter.Convert(reader[0], typeof(T));
                    return((T)value);
                }
                return(default(T));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (c != null)
                {
                    c.Close();
                }
            }
        }
Example #2
0
        public static void ReadProperties(XElement element, object instance)
        {
            var children = element.Descendants();

            if (children.Count() > 0)
            {
                var type     = instance.GetType();
                var property = type.GetProperty(element.Name.LocalName);
                if (property != null && property.CanRead && property.CanWrite && property.GetCustomAttribute <IgnoreAttribute>()?.Ignored != true)
                {
                    var value = property.GetValue(instance);
                    if (value == null)
                    {
                        property.SetValue(instance, property.PropertyType.CreateInstance());
                        value = property.GetValue(instance);
                    }
                    foreach (var child in children)
                    {
                        ReadProperties(child, value);
                    }
                    property.SetValue(instance, value);
                }
            }
            else
            {
                // Property
                var property = instance.GetType().GetProperty(element.Name.LocalName);
                if (property != null && property.CanRead && property.CanWrite && property.GetCustomAttribute <IgnoreAttribute>()?.Ignored != true)
                {
                    var value = UniversalTypeConverter.Convert(element.Value, property.PropertyType, CultureInfo.CurrentCulture, ConversionOptions.EnhancedTypicalValues);
                    property.SetValue(instance, value);
                }
            }
        }
Example #3
0
        public async Task <object> ConvertObjectAsync(ICommandContext context, Type type, string input)
        {
            var typeReader = GetDefaultTypeReader(type);
            var typeResult = await typeReader.ReadAsync(context, input, null).ConfigureAwait(false);

            if (typeResult.IsSuccess)
            {
                if (typeResult.Values.Count > 1)
                {
                    return(typeResult.Values.OrderByDescending(x => x.Score).Select(x => x.Value).ToArray());
                }
                return(typeResult.Values.OrderByDescending(a => a.Score).FirstOrDefault().Value);
            }
            // try default
            return(UniversalTypeConverter.Convert(input, type, CultureInfo.CurrentCulture, ConversionOptions.Default));
        }
Example #4
0
 private static object GetValue(SQLiteDataReader reader, Dictionary <string, PropertyInfo> setters, int i, string colName)
 {
     if (setters[colName].PropertyType == typeof(bool))
     {
         var result = (int)UniversalTypeConverter.Convert(reader[i], typeof(int));
         return(result == 1);
     }
     else if (setters[colName].PropertyType == typeof(byte[]))
     {
         return(GetBytes(reader, i));
     }
     else if (setters[colName].PropertyType == typeof(Guid))
     {
         Guid outguid;
         if (reader[i] == null || !Guid.TryParse(reader[i].ToString(), out outguid))
         {
             return(Guid.Empty);
         }
         return(outguid);
     }
     else if (setters[colName].PropertyType == typeof(DateTime))
     {
         DateTime d       = DateTime.UtcNow;
         Object   content = reader[i];
         if (content == null)
         {
             return(d);
         }
         if (!DateTime.TryParseExact(content.ToString(),
                                     @"yyyy-MM-dd\THH:mm:ss.fff\Z",
                                     CultureInfo.InvariantCulture,
                                     DateTimeStyles.AssumeUniversal, out d))
         {
             return(DateTime.UtcNow);
         }
         return(d);
     }
     else
     {
         return(UniversalTypeConverter.Convert(reader[i], setters[colName].PropertyType));
     }
 }
Example #5
0
        private TSettings ReloadSettings()
        {
            var settings = Activator.CreateInstance <TSettings>();

            var properties = from pi in typeof(TSettings).GetProperties()
                             where pi.CanWrite && pi.CanRead
                             let key = string.Concat(typeof(TSettings).Name, ".", pi.Name)
                                       let setting = _settingService.GetValue <string>(key, null, false, true)
                                                     where setting != null
                                                     where UniversalTypeConverter.CanConvert(setting, pi.PropertyType)
                                                     let value = UniversalTypeConverter.Convert(setting, pi.PropertyType)
                                                                 select new {
                PropertyInfo = pi,
                Value        = value
            };

            properties.ToList().ForEach(p => p.PropertyInfo.SetValue(settings, p.Value, null));

            return(settings);
        }
Example #6
0
        private object ToObject(object instance, XmlNode xmlNode, string nodeName = null)
        {
            Type                type                = instance.GetType();
            ClassMetaData       classMetaData       = MetaDataCache.Get(type);
            XmlMappingOperation xmlMappingOperation = xmlMapperAttribute.MappingOperation;

            if (classMetaData.ClassAttributeContext.ContainsAttribute <XmlMapperAttribute>())
            {
                XmlMapperAttribute xmlMapper = classMetaData.ClassAttributeContext.GetAttribute <XmlMapperAttribute>();
                xmlMappingOperation = xmlMapper.MappingOperation;
                if (nodeName == null)
                {
                    nodeName = xmlMapper.ParentNodeName;
                    xmlNode  = xmlNode.SelectSingleNode($"//{nodeName}");
                }
            }

            foreach (IFieldPropertyInfo property in classMetaData.Properties)
            {
                string      propertyName = property.Name;
                System.Type propertyType = property.Type;

                if (classMetaData.HasPropertyAttributeContext <PropertyAttributeContext>(property))
                {
                    PropertyAttributeContext propertyAttributeContext = classMetaData.GetAttributeContextForProperty <PropertyAttributeContext>(property);

                    if (propertyAttributeContext.HasIgnoreAttribute)
                    {
                        continue;
                    }

                    propertyName = propertyAttributeContext.HasNameAttribute ? propertyAttributeContext.NameAttribute.Name : propertyName;
                }

                object propertyValue = GetNodeValue(xmlMappingOperation, xmlNode, nodeName, propertyName);

                if (classMetaData.HasPropertyAttributeContext <XmlPropertyAttributeContext>(property))
                {
                    XmlPropertyAttributeContext xmlPropertyAttributeContext = classMetaData.GetAttributeContextForProperty <XmlPropertyAttributeContext>(property);

                    if (xmlPropertyAttributeContext.HasXmlListAttribute)
                    {
                        XmlListAttribute xmlList = xmlPropertyAttributeContext.XmlListAttribute;
                        XmlNodeList      results = xmlNode.SelectNodes($"//{nodeName}/{propertyName}/{xmlList.NodeName}");
                        if (results.Count > 0)
                        {
                            object childInstance = CollectionXmlNodeListToObject(results, propertyType);
                            property.SetValue(instance, childInstance);
                        }
                        continue;
                    }
                    else if (xmlPropertyAttributeContext.HasXmlDictionaryAttribute)
                    {
                        XmlDictionaryAttribute xmlList = xmlPropertyAttributeContext.XmlDictionaryAttribute;
                        XmlNodeList            results = xmlNode.SelectNodes($"//{nodeName}/{propertyName}/*");
                        if (results.Count > 0)
                        {
                            object childInstance = DictionaryXmlNodeListToObject(results, propertyType);
                            property.SetValue(instance, childInstance);
                        }
                        continue;
                    }
                    else if (xmlPropertyAttributeContext.HasXmlFlattenHierarchyAttribute)
                    {
                        object childInstance = Activator.CreateInstance(propertyType);
                        childInstance = ToObject(childInstance, xmlNode, nodeName);
                        property.SetValue(instance, childInstance);
                        continue;
                    }
                    else if (xmlPropertyAttributeContext.HasXmlPropertyConverterAttribute && propertyValue != null)
                    {
                        XmlPropertyConverterAttribute converter = xmlPropertyAttributeContext.XmlPropertyConverterAttribute;
                        try
                        {
                            propertyValue = converter.ConvertToSourceType(propertyValue);
                        }
                        catch (Exception ex)
                        {
                            throw new XmlPropertyConverterException("XmlPropertyConverter threw an exception", ex);
                        }
                    }
                }
                else
                {
                    if (propertyType.IsDictionary())
                    {
                        XmlNodeList results = xmlNode.SelectNodes($"//{nodeName}/{propertyName}/*");
                        if (results.Count > 0)
                        {
                            object childInstance = DictionaryXmlNodeListToObject(results, propertyType);
                            property.SetValue(instance, childInstance);
                        }
                        continue;
                    }
                    else if (propertyType.IsCollection())
                    {
                        string      listItemNodeName = propertyType.GenericTypeArguments[0].Name;
                        XmlNodeList results          = xmlNode.SelectNodes($"//{nodeName}/{propertyName}/{listItemNodeName}");
                        if (results.Count > 0)
                        {
                            object childInstance = CollectionXmlNodeListToObject(results, propertyType);
                            property.SetValue(instance, childInstance);
                        }
                        continue;
                    }
                    if (propertyType.IsClass && MetaDataCache.Contains(propertyType))
                    {
                        // TODO: Dont think this will work
                        object  childInstance = Activator.CreateInstance(propertyType);
                        XmlNode results       = xmlNode.SelectSingleNode($"//{nodeName}/{propertyName}");
                        if (results != null)
                        {
                            childInstance = ToObject(childInstance, results, propertyName);
                            property.SetValue(instance, childInstance);
                        }
                        continue;
                    }
                }

                if (propertyValue == null)
                {
                    continue;
                }

                property.SetValue(instance, UniversalTypeConverter.Convert(propertyValue, propertyType));
            }

            return(instance);
        }
Example #7
0
        public static FeedResult <TChannel, TItem> ParseRss <TChannel, TItem>(string url)
            where TItem : FeedItem, new()
            where TChannel : FeedChannel, new()
        {
            var channel = new TChannel();
            var items   = new List <TItem>();

            try
            {
                XDocument doc         = XDocument.Load(url);
                var       propChannel = typeof(TChannel).GetProperties().Where(p => p.GetCustomAttribute <FeedElementAttribute>()?.Ignore != true).ToList();
                var       propItem    = typeof(TItem).GetProperties().Where(p => p.GetCustomAttribute <FeedElementAttribute>()?.Ignore != true).ToList();

                var namespaces = doc.Root.Attributes().Where(e => e.IsNamespaceDeclaration).Select(e => new FeedNamespace()
                {
                    Namespace = e.Name.LocalName,
                    Url       = e.Value
                });
                var rssElements     = doc.Root.Descendants().First(i => i.Name.LocalName == "channel").Elements();
                var channelElements = rssElements.Where(e => e.Name.LocalName != "item");
                var itemsElements   = rssElements.Where(e => e.Name.LocalName == "item");

                foreach (var property in propChannel)
                {
                    try
                    {
                        object value = null;
                        var    names = property.GetCustomAttribute <FeedElementAttribute>()?.Names ?? new[] { property.Name };
                        foreach (var name in names)
                        {
                            try
                            {
                                value = GetValueFromElements(name, channelElements, namespaces);
                                if (value != null)
                                {
                                    break;
                                }
                            }
                            catch { }
                        }
                        try
                        {
                            property.SetValue(channel, UniversalTypeConverter.Convert(value, property.PropertyType, ConversionOptions.None | ConversionOptions.AllowDefaultValueIfNull));
                        }
                        catch { }
                    }
                    catch { }
                }
                foreach (var elements in itemsElements.Select(e => e.Elements()))
                {
                    try
                    {
                        var item = new TItem();
                        foreach (var property in propItem)
                        {
                            object value = null;
                            var    names = property.GetCustomAttribute <FeedElementAttribute>()?.Names ?? new[] { property.Name };
                            foreach (var name in names)
                            {
                                try
                                {
                                    value = GetValueFromElements(name, elements, namespaces);
                                    if (value != null)
                                    {
                                        break;
                                    }
                                }
                                catch { }
                            }
                            try
                            {
                                property.SetValue(item, UniversalTypeConverter.Convert(value, property.PropertyType, ConversionOptions.None | ConversionOptions.AllowDefaultValueIfNull));
                            }
                            catch { }
                        }
                        items.Add(item);
                    }
                    catch { }
                }
            }
            catch { }
            return(new FeedResult <TChannel, TItem>(FeedType.RSS, channel, items.OrderBy(e => e.PublishDate)));
        }