Пример #1
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);
                }
            }
        }
Пример #2
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();
                }
            }
        }
        public void StringToType_NullableBooleanTrue_True()
        {
            var value = UniversalTypeConverter.StringToType <bool?>("true");

            value.HasValue.Should().BeTrue();
            value.Value.Should().BeTrue();
        }
Пример #4
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));
        }
Пример #5
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));
     }
 }
Пример #6
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);
        }
        public void StringToType_NullableBooleanStringEmpty_HasNoValue()
        {
            var value = UniversalTypeConverter.StringToType <bool?>("");

            value.HasValue.Should().BeFalse();
        }
        public void StringToType_BooleanStringEmpty_FormatExceptionThrown()
        {
            Action action = () => UniversalTypeConverter.StringToType <bool>("");

            action.ShouldThrow <FormatException>().WithMessage("String was not recognized as a valid Boolean.");
        }
        public void StringToType_true_True()
        {
            var value = UniversalTypeConverter.StringToType <bool>("true");

            value.Should().BeTrue();
        }
        public void StringToType_123_Int()
        {
            var value = UniversalTypeConverter.StringToType <int>("123");

            value.Should().Be(123);
        }
 // This is where the magic happens via https://github.com/t-bruning/UniversalTypeConverter
 public static bool TryConvert(object value, out T result) =>
 UniversalTypeConverter.TryConvertTo(value, out result);
Пример #12
0
        public ActionResult updateMarkers(FormCollection collection)
        {
            if (bFirstCall)
            {
                //First time called since last web site restart - log selected <appSettings> values...
                bFirstCall = false;

                dblogcontext.clearParameters();
                dblogcontext.clearReturns();

                dblogcontext.addParameter("ServiceUrl", ConfigurationManager.AppSettings["ServiceUrl"]);
                dblogcontext.addParameter("ServiceUrl_1_1_EndPoint", ConfigurationManager.AppSettings["ServiceUrl1_1_EndPoint"]);
                dblogcontext.addParameter("ByuUrl", ConfigurationManager.AppSettings["ByuUrl"]);
                dblogcontext.addParameter("MaxClustercount", ConfigurationManager.AppSettings["MaxClustercount"].ToString());
                dblogcontext.addParameter("maxAllowedTimeseriesReturn", ConfigurationManager.AppSettings["maxAllowedTimeseriesReturn"].ToString());
                dblogcontext.addParameter("maxCombinedExportValues", ConfigurationManager.AppSettings["maxCombinedExportValues"].ToString());
                dblogcontext.addParameter("blobContainer", ConfigurationManager.AppSettings["blobContainer"]);
                dblogcontext.addParameter("aspnet:MaxJsonDeserializerMembers", ConfigurationManager.AppSettings["aspnet:MaxJsonDeserializerMembers"].ToString());
                dblogcontext.addParameter("currentVersion", ConfigurationManager.AppSettings["currentVersion"].ToString());

                DateTime dtNow = DateTime.UtcNow;
                dblogcontext.createLogEntry(System.Web.HttpContext.Current, dtNow, dtNow, "updateMarkers(...)", "first call - selected appSettings values...", Level.Info);
            }

            var    searchSettings = new SearchSettings();
            string markerjSON     = string.Empty;

            //get map geometry
            double xMin, xMax, yMin, yMax;
            int    zoomLevel;

            int CLUSTERWIDTH       = 50;                                                                              //Cluster region width, all pin within this area are clustered
            int CLUSTERHEIGHT      = 50;                                                                              //Cluster region height, all pin within this area are clustered
            int CLUSTERINCREMENT   = 5;                                                                               //increment for clusterwidth
            int MINCLUSTERDISTANCE = 25;
            int MAXCLUSTERCOUNT    = Convert.ToInt32(ConfigurationManager.AppSettings["MaxClustercount"].ToString()); //maximum ammount of clustered markers

            UniversalTypeConverter.TryConvertTo <double>(collection["xMin"], out xMin);
            UniversalTypeConverter.TryConvertTo <double>(collection["xMax"], out xMax);
            UniversalTypeConverter.TryConvertTo <double>(collection["yMin"], out yMin);
            UniversalTypeConverter.TryConvertTo <double>(collection["yMax"], out yMax);
            Box box = new Box(xMin, xMax, yMin, yMax);

            UniversalTypeConverter.TryConvertTo <int>(collection["zoomLevel"], out zoomLevel);
            var activeWebservices = new List <WebServiceNode>();

            //Attempt to retrieve filtered timeseries ids, if indicated
            string strFilterAndSearchCriteria = collection["filterAndSearchCriteria"];

            clientFilterAndSearchCriteria filterAndSearchCriteria = null;

            if (!String.IsNullOrWhiteSpace(strFilterAndSearchCriteria))
            {
                filterAndSearchCriteria = JsonConvert.DeserializeObject <clientFilterAndSearchCriteria>(strFilterAndSearchCriteria);
            }

            //if it is a new request
            if (collection["isNewRequest"].ToString() == "true")
            {
                bool canConvert = false;

                var        keywords      = Regex.Split(collection["keywords"], @"##");
                var        tileWidth     = 10;
                var        tileHeight    = 10;
                List <int> webServiceIds = null;
                try
                {
                    //Increase date range by one day to accomodate one day searches, if indicated...
                    //Set begin date time to 00:00:00, set end date time to 23:59:59
                    searchSettings.DateSettings.StartDate = Convert.ToDateTime(collection["startDate"]);
                    searchSettings.DateSettings.StartDate = searchSettings.DateSettings.StartDate.Date.AddHours(0).AddMinutes(0).AddSeconds(0);

                    searchSettings.DateSettings.EndDate = Convert.ToDateTime(collection["endDate"]);
                    if (searchSettings.DateSettings.StartDate.Date == searchSettings.DateSettings.EndDate.Date)
                    {
                        searchSettings.DateSettings.EndDate = searchSettings.DateSettings.EndDate.Date.AddDays(1);
                    }
                    searchSettings.DateSettings.EndDate = searchSettings.DateSettings.EndDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59);

                    //Convert to int Array
                    if (collection["services"].Length > 0)
                    {
                        webServiceIds = collection["services"].Split(',').Select(s => Convert.ToInt32(s)).ToList();
                    }

                    var dataWorker = new DataWorker();

                    var allWebservices = dataWorker.getWebServiceList();


                    //filter list
                    if (webServiceIds != null)
                    {
                        activeWebservices = dataWorker.filterWebservices(allWebservices, webServiceIds);
                    }
                    Session["webServiceList"] = allWebservices;

                    //Clear parameters...
                    dblogcontext.clearParameters();
                    dberrorcontext.clearParameters();

                    //Add call parameters...
                    dblogcontext.addParameter("box", box);
                    dberrorcontext.addParameter("box", box);
                    if (1 == keywords.Length && "" == keywords[0])
                    {
                        dblogcontext.addParameter("keywords", "All");
                        dberrorcontext.addParameter("keywords", "All");
                    }
                    else
                    {
                        StringBuilder sb1 = new StringBuilder();
                        foreach (string keyword in keywords)
                        {
                            sb1.AppendFormat("{0}, ", keyword);
                        }

                        dblogcontext.addParameter("keywords", sb1.ToString());
                        dberrorcontext.addParameter("keywords", sb1.ToString());
                    }

                    dblogcontext.addParameter("tileWidth", tileWidth);
                    dberrorcontext.addParameter("tileWidth", tileWidth);

                    dblogcontext.addParameter("tileHeight", tileHeight);
                    dberrorcontext.addParameter("tileHeight", tileHeight);

                    dblogcontext.addParameter("startDate", searchSettings.DateSettings.StartDate);
                    dberrorcontext.addParameter("startDate", searchSettings.DateSettings.StartDate);

                    dblogcontext.addParameter("endDate", searchSettings.DateSettings.EndDate);
                    dberrorcontext.addParameter("endDate", searchSettings.DateSettings.EndDate);

                    if (0 >= activeWebservices.Count)
                    {
                        dblogcontext.addParameter("activeWebServices", "All");
                        dberrorcontext.addParameter("activeWebServices", "All");
                    }
                    else
                    {
                        StringBuilder sb1 = new StringBuilder();
                        activeWebservices.ForEach(wsn => sb1.AppendFormat("{0},", wsn.Title));

                        dblogcontext.addParameter("activeWebServices", sb1.ToString());
                        dberrorcontext.addParameter("activeWebServices", sb1.ToString());
                    }

                    DateTime startDtUtc = DateTime.UtcNow;

                    var series = dataWorker.getSeriesData(box, keywords.ToArray(), tileWidth, tileHeight,
                                                          searchSettings.DateSettings.StartDate,
                                                          searchSettings.DateSettings.EndDate,
                                                          activeWebservices);
                    DateTime endDtUtc = DateTime.UtcNow;

                    //Clear returns
                    dblogcontext.clearReturns();

                    //Add returned series count...
                    dblogcontext.addReturn("seriesCount", series.Count);

                    //Create log entry...
                    dblogcontext.createLogEntry(System.Web.HttpContext.Current, startDtUtc, endDtUtc, "updateMarkers(...)", "calls dataWorker.getSeriesData(...)", Level.Info);

                    var list = new List <TimeSeriesViewModel>();

                    if (!EnvironmentContext.LocalEnvironment())
                    {
                        //Non-local environment - do not attempt to create debug files...
                        //Watch out for similar loop code in 'else' block...
                        if (series.Count > 0)
                        {
                            for (int i = 0; i < series.Count; i++)
                            {
                                var tvm = new TimeSeriesViewModel();
                                tvm = mapDataCartToTimeseries(series[i], i);
                                list.Add(tvm);
                            }
                        }
                    }
                    else
                    {
                        //Local environment - create debug files, if indicated...
#if (DEBUG)
                        //BCC - Test - write data cart and time series objects to files...
                        using (System.IO.StreamWriter swSdc = System.IO.File.CreateText(@"C:\CUAHSI\SeriesDataCart.json"))
                        {
                            using (System.IO.StreamWriter swTsvm = System.IO.File.CreateText(@"C:\CUAHSI\TimeSeriesViewModel.json"))
                            {
                                JsonSerializer jsonser = new JsonSerializer();

                                swSdc.Write('[');                                       //Write start of array...
                                swTsvm.Write('[');
#endif
                        //Watch out for similar loop code in 'if' block...
                        if (series.Count > 0)
                        {
                            for (int i = 0; i < series.Count; i++)
                            {
                                var tvm = new TimeSeriesViewModel();
                                tvm = mapDataCartToTimeseries(series[i], i);
                                list.Add(tvm);
#if (DEBUG)
                                jsonser.Serialize(swSdc, series[i]);
                                jsonser.Serialize(swTsvm, tvm);

                                if ((i + 1) < series.Count)
                                {
                                    swSdc.Write(',');                                                           //Separate array element...
                                    swTsvm.Write(',');
                                }
#endif
                            }
                        }
#if (DEBUG)
                        swSdc.Write(']');                                               //Write end of array...
                        swTsvm.Write(']');
                    }
                }
#endif
                    }

                    var markerClustererHelper = new MarkerClustererHelper();

                    //save list for later
                    Session["Series"] = list;

                    //transform list int clusteredpins
                    var pins = transformSeriesDataCartIntoClusteredPin(list, filterAndSearchCriteria);

                    var clusteredPins = markerClustererHelper.clusterPins(pins, CLUSTERWIDTH, CLUSTERHEIGHT, CLUSTERINCREMENT, zoomLevel, MAXCLUSTERCOUNT, MINCLUSTERDISTANCE);
                    Session["ClusteredPins"] = clusteredPins;

                    var centerPoint = new LatLong(0, 0);
                    markerjSON = markerClustererHelper.createMarkersGEOJSON(clusteredPins, zoomLevel, centerPoint, "");
                }

                catch (Exception ex)
                {
                    //NOTE: Override 'standard' IIS error handling since we are using 'standard' HTTP error codes - RequestEntityTooLarge and RequestTimeout...
                    //Sources:	http://stackoverflow.com/questions/22071211/when-performing-post-via-ajax-bad-request-is-returned-instead-of-the-json-resul
                    //			http://stackoverflow.com/questions/3993941/in-iis7-5-what-module-removes-the-body-of-a-400-bad-request/4029197#4029197
                    //			http://weblog.west-wind.com/posts/2009/Apr/29/IIS-7-Error-Pages-taking-over-500-Errors

                    //Find the 'inner-most' exception...
                    while (null != ex.InnerException)
                    {
                        ex = ex.InnerException;
                    }

                    if (typeof(WebException) == ex.GetType())
                    {
                        //Web exception - return the error message...
                        WebException wex = (WebException)ex;

                        Response.StatusCode             = (int)wex.Status;
                        Response.StatusDescription      = wex.Message;
                        Response.TrySkipIisCustomErrors = true;                         //Tell IIS to use your error text not the 'standard' error text!!
                        //ALSO clues jQuery to add the parsed responseJSON object to the jqXHR object!!
                        dberrorcontext.createLogEntry(System.Web.HttpContext.Current, DateTime.UtcNow, "updateMarkers(...)", wex, "Web Exception: " + wex.Message);

                        return(Json(new { Message = wex.Message }, "application/json"));
                    }
                    else if (typeof(System.InvalidOperationException) == ex.GetType())
                    {
                        //Recover the returned error message...
                        Response.StatusCode             = (int)HttpStatusCode.RequestEntityTooLarge;
                        Response.StatusDescription      = ex.Message;
                        Response.TrySkipIisCustomErrors = true;                         //Tell IIS to use your error text not the 'standard' error text!!
                        //ALSO clues jQuery to add the parsed responseJSON object to the jqXHR object!!
                        dberrorcontext.createLogEntry(System.Web.HttpContext.Current, DateTime.UtcNow, "updateMarkers(...)", ex, "NON-Web Exception" + ex.Message);

                        return(Json(new { Message = ex.Message }, "application/json"));
                    }
                    else
                    {
                        //Assume a timeout has occurred...
                        string message = "The execution of the search took too long. Please limit search area and/or Keywords.";
                        Response.StatusCode             = (int)HttpStatusCode.RequestTimeout;
                        Response.StatusDescription      = message;
                        Response.TrySkipIisCustomErrors = true;                         //Tell IIS to use your error text not the 'standard' error text!!
                        //ALSO clues jQuery to add the parsed responseJSON object to the jqXHR object!!
                        dberrorcontext.createLogEntry(System.Web.HttpContext.Current, DateTime.UtcNow, "updateMarkers(...)", ex, "Defaults to timeout exception: " + message);

                        return(Json(new { Message = message }, "application/json"));
                    }
                }

                //var session2 =(List<BusinessObjects.Models.SeriesDataCartModel.SeriesDataCart>) Session["Series"];
            }
            else
            {
                //BCC - 19-Nov-2015 - GitHub Issues #67 - Application unresponsive after session timeout and zoom out...
                var retrievedSeries = (List <TimeSeriesViewModel>)Session["Series"];

                if (null != retrievedSeries)                    //If a session timeout has occurred, the new session object will not contain the 'Series' element!!
                {
                    var markerClustererHelper = new MarkerClustererHelper();
                    //transform list int clusteredpins
                    var pins = transformSeriesDataCartIntoClusteredPin(retrievedSeries, filterAndSearchCriteria);

                    var clusteredPins = markerClustererHelper.clusterPins(pins, CLUSTERWIDTH, CLUSTERHEIGHT, CLUSTERINCREMENT, zoomLevel, MAXCLUSTERCOUNT, MINCLUSTERDISTANCE);
                    Session["ClusteredPins"] = clusteredPins;

                    var centerPoint = new LatLong(0, 0);
                    markerjSON = markerClustererHelper.createMarkersGEOJSON(clusteredPins, zoomLevel, centerPoint, "");
                }
                else
                {
                    //Likely session timeout - return a Request Timeout error (408)...
                    string message = "User session has expired!!";

                    Response.StatusCode             = (int)HttpStatusCode.RequestTimeout;
                    Response.StatusDescription      = message;
                    Response.TrySkipIisCustomErrors = true;                     //Tell IIS to use your error text not the 'standard' error text!!

                    return(Json(new { Message = message }, "application/json"));
                }
            }
            return(Json(markerjSON));
        }
Пример #13
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);
        }
Пример #14
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)));
        }