public void Aggregate(PropertyResult other) { if (_numberType != null) { if (other._isNullNumber) { return; } Debug.Assert(other._numberType != null); switch (_numberType.Value) { case NumberParseResult.Double: ResultValue = DoubleValue += other.DoubleValue; break; case NumberParseResult.Long: ResultValue = LongValue += other.LongValue; break; default: throw new ArgumentOutOfRangeException($"Unknown number type: {_numberType.Value}"); } } else if (_isNullNumber) { _numberType = other._numberType; ResultValue = other.ResultValue; DoubleValue = other.DoubleValue; LongValue = other.LongValue; _isNullNumber = false; } }
/// <inheritdoc /> public override bool TryGetValue(out object value, System.Diagnostics.TraceEventCache cache, string source, System.Diagnostics.TraceEventType eventType, int id, string formatOrMessage, object[] data) { object result = null; if (_wrappedPropertyReader.TryGetValue(out result, cache, source, eventType, id, formatOrMessage, data)) { PropertyResult pr = _fastPropertyGetter.GetValue(result); value = pr.Data; return(pr.ObjectMatched); } value = null; return(false); }
public SearchResult Search(string searchTerm, MarketResult market, int limit) { SearchResult toRet = new SearchResult(); SearchRequest searchRequest = new SearchRequest(); searchRequest.limit = limit; searchRequest.searchTerm = searchTerm; searchRequest.market = new Market(); searchRequest.market.market = market.Market; searchRequest.market.state = market.State; var request = new RestRequest("search", DataFormat.Json); request.AddJsonBody(searchRequest); var response = client.Post(request); var json = response.Content; var searchResponse = JsonConvert.DeserializeObject <SearchResponse>(json); toRet.MgmtShown = searchResponse.mgmtShowing; toRet.MgmtCount = searchResponse.mgmtTotal; toRet.PropertyShown = searchResponse.propertiesShowing; toRet.PropertyCount = searchResponse.propertiesTotal; foreach (var mg in searchResponse.mgmts) { MgmtResult mr = new MgmtResult(); mr.Name = mg.name; mr.Market = mg.market; mr.State = mg.state; toRet.Mgmts.Add(mr); } foreach (var p in searchResponse.properties) { PropertyResult pr = new PropertyResult(); pr.Name = p.name; if (!String.IsNullOrWhiteSpace(p.formerName) && p.formerName != p.name) { pr.Name += " (" + p.formerName + ")"; } pr.Address = p.streetAddress; pr.City = p.city; pr.Market = p.market; pr.State = p.state; toRet.Properties.Add(pr); } return(toRet); }
public void Aggregate(PropertyResult other) { if (_numberType != null) { switch (_numberType.Value) { case NumberParseResult.Double: ResultValue = DoubleValue += other.DoubleValue; break; case NumberParseResult.Long: ResultValue = LongValue += other.LongValue; break; default: throw new ArgumentOutOfRangeException($"Unknown number type: {_numberType.Value}"); } } }
public static async Task <List <Listing> > Deserialize() { var location = await GetLocation(); //Console.WriteLine(location); string url = "https://api.zoopla.co.uk/api/v1/property_listings.json?latitude=" + location.Latitude + "&longitude=" + location.Longitude + "&radius=10&order_by=age&listing_status=sale&page_size=50&description_style=1&api_key=INSERT_API_HERE"; //json source var client = new WebClient(); var content = client.DownloadString(url); //connect to web service and retrieve json PropertyResult result = JsonConvert.DeserializeObject <PropertyResult>(content); var listingResult = result.listing; //Analytics.TrackEvent("Loading JSON"); return(listingResult); }
/// <summary> /// Searches the objects in the "data" parameter for in an instance of the specified sourceType /// and, if found, attempts to retrieve the value of the specified Property. /// </summary> /// <param name="value">Return value</param> /// <param name="cache">Unused</param> /// <param name="source">Unused</param> /// <param name="eventType">Unused</param> /// <param name="id">Unused</param> /// <param name="formatOrMessage">Unused</param> /// <param name="data">Data to be searched</param> /// <returns>False if no match found, true otherwise</returns> public override bool TryGetValue(out object value, TraceEventCache cache, string source, TraceEventType eventType, int id, string formatOrMessage, object[] data) { value = null; if (null == data) { return(false); } foreach (object obj in data) { PropertyResult result = _fastPropertyGetter.GetValue(obj); if (result.ObjectMatched) { value = result.Data; return(result.ObjectMatched); } } return(false); }
internal static PublishedContentSet <IPublishedContent> ConvertSearchResultToPublishedContent(this IEnumerable <SearchResult> results, ContextualPublishedCache cache) { //TODO: The search result has already returned a result which SHOULD include all of the data to create an IPublishedContent, // however this is currently not the case: // http://examine.codeplex.com/workitem/10350 var list = new List <IPublishedContent>(); var set = new PublishedContentSet <IPublishedContent>(list); foreach (var result in results.OrderByDescending(x => x.Score)) { var content = cache.GetById(result.Id); if (content == null) { continue; // skip if this doesn't exist in the cache } // need to extend the content as we're going to add a property to it, // and we should not ever do it to the content we get from the cache, // precisely because it is cached and shared by all requests. // but we cannot wrap it because we need to respect the type that was // returned by the cache, in case the cache can create real types. // so we have to ask it to please extend itself. list.Add(content); var extend = set.MapContent(content); var property = new PropertyResult("examineScore", result.Score, Guid.Empty, PropertyResultType.CustomProperty); extend.AddProperty(property); } return(set); }
protected override AggregationResult AggregateOn(List <BlittableJsonReaderObject> aggregationBatch, TransactionOperationContext indexContext, CancellationToken token) { var aggregatedResultsByReduceKey = new Dictionary <BlittableJsonReaderObject, Dictionary <string, PropertyResult> >(ReduceKeyComparer.Instance); foreach (var obj in aggregationBatch) { token.ThrowIfCancellationRequested(); using (obj) { var aggregatedResult = new Dictionary <string, PropertyResult>(); foreach (var propertyName in obj.GetPropertyNames()) { if (_indexDefinition.TryGetField(propertyName, out var indexField)) { switch (indexField.Aggregation) { case AggregationOperation.None: if (obj.TryGet(propertyName, out object groupByValue) == false) { throw new InvalidOperationException($"Could not read group by value of '{propertyName}' property"); } aggregatedResult[propertyName] = new PropertyResult { ResultValue = groupByValue }; break; case AggregationOperation.Count: case AggregationOperation.Sum: object value; if (obj.TryGetMember(propertyName, out value) == false) { throw new InvalidOperationException($"Could not read numeric value of '{propertyName}' property"); } double doubleValue; long longValue; var numberType = BlittableNumber.Parse(value, out doubleValue, out longValue); var aggregate = new PropertyResult(numberType); switch (numberType) { case NumberParseResult.Double: aggregate.ResultValue = aggregate.DoubleValue = doubleValue; break; case NumberParseResult.Long: aggregate.ResultValue = aggregate.LongValue = longValue; break; default: throw new ArgumentOutOfRangeException($"Unknown number type: {numberType}"); } aggregatedResult[propertyName] = aggregate; break; //case FieldMapReduceOperation.None: default: throw new ArgumentOutOfRangeException($"Unhandled field type '{indexField.Aggregation}' to aggregate on"); } } if (_indexDefinition.GroupByFields.ContainsKey(propertyName) == false) { // we want to reuse existing entry to get a reduce key if (obj.Modifications == null) { obj.Modifications = new DynamicJsonValue(obj); } obj.Modifications.Remove(propertyName); } } var reduceKey = indexContext.ReadObject(obj, "reduce key"); if (aggregatedResultsByReduceKey.TryGetValue(reduceKey, out Dictionary <string, PropertyResult> existingAggregate) == false) { aggregatedResultsByReduceKey.Add(reduceKey, aggregatedResult); } else { reduceKey.Dispose(); foreach (var propertyResult in existingAggregate) { propertyResult.Value.Aggregate(aggregatedResult[propertyResult.Key]); } } } } var resultObjects = new List <Document>(aggregatedResultsByReduceKey.Count); foreach (var aggregationResult in aggregatedResultsByReduceKey) { aggregationResult.Key.Dispose(); var djv = new DynamicJsonValue(); foreach (var aggregate in aggregationResult.Value) { djv[aggregate.Key] = aggregate.Value.ResultValue; } resultObjects.Add(new Document { Data = indexContext.ReadObject(djv, "map/reduce") }); } return(new AggregatedDocuments(resultObjects)); }
/// <summary> /// Returns the value from the property result and ensure it is filtered through the razor data type converters /// </summary> /// <param name="propResult"></param> /// <param name="result">The value result for the property</param> /// <returns>true if getting the property data was successful</returns> private bool TryGetPropertyData(PropertyResult propResult, out object result) { if (propResult == null) throw new ArgumentNullException("propResult"); //special casing for true/false properties //int/decimal are handled by ConvertPropertyValueByDataType //fallback is stringT if (n.NodeTypeAlias == null && propResult.Alias == null) { throw new ArgumentNullException("No node alias or property alias available. Unable to look up the datatype of the property you are trying to fetch."); } //contextAlias is the node which the property data was returned from //Guid dataType = ContentType.GetDataType(data.ContextAlias, data.Alias); var dataType = GetDataType(propResult.ContextAlias, propResult.Alias); var staticMapping = UmbracoSettings.RazorDataTypeModelStaticMapping .FirstOrDefault(mapping => mapping.Applies(dataType, propResult.ContextAlias, propResult.Alias)); if (staticMapping != null) { var dataTypeType = Type.GetType(staticMapping.TypeName); if (dataTypeType != null) { object valueOutput = null; if (TryCreateInstanceRazorDataTypeModel(dataType, dataTypeType, propResult.Value, out valueOutput)) { result = valueOutput; return true; } LogHelper.Warn<DynamicNode>(string.Format("Failed to create the instance of the model binder")); } else { LogHelper.Warn<DynamicNode>(string.Format("staticMapping type name {0} came back as null from Type.GetType; check the casing, assembly presence, assembly framework version, namespace", staticMapping.TypeName)); } } if (RazorDataTypeModelTypes != null && RazorDataTypeModelTypes.Any(model => model.Key.Item1 == dataType) && dataType != Guid.Empty) { var razorDataTypeModelDefinition = RazorDataTypeModelTypes.Where(model => model.Key.Item1 == dataType).OrderByDescending(model => model.Key.Item2).FirstOrDefault(); if (!(razorDataTypeModelDefinition.Equals(default(KeyValuePair<System.Tuple<Guid, int>, Type>)))) { Type dataTypeType = razorDataTypeModelDefinition.Value; object valueResult = null; if (TryCreateInstanceRazorDataTypeModel(dataType, dataTypeType, propResult.Value, out valueResult)) { result = valueResult; return true; } LogHelper.Warn<DynamicNode>(string.Format("Failed to create the instance of the model binder")); } else { LogHelper.Warn<DynamicNode>(string.Format("Could not get the dataTypeType for the RazorDataTypeModel")); } } result = propResult.Value; //convert the string value to a known type var returnVal = ConvertPropertyValueByDataType(ref result, propResult.Alias, dataType); return returnVal; }
public DictionaryPublishedContent( IDictionary <string, string> valueDictionary, Func <int, IPublishedContent> getParent, Func <int, XPathNavigator, IEnumerable <IPublishedContent> > getChildren, Func <DictionaryPublishedContent, string, IPublishedProperty> getProperty, XPathNavigator nav, bool fromExamine) { if (valueDictionary == null) { throw new ArgumentNullException("valueDictionary"); } if (getParent == null) { throw new ArgumentNullException("getParent"); } if (getProperty == null) { throw new ArgumentNullException("getProperty"); } _getParent = new Lazy <IPublishedContent>(() => getParent(ParentId)); _getChildren = new Lazy <IEnumerable <IPublishedContent> >(() => getChildren(Id, nav)); _getProperty = getProperty; LoadedFromExamine = fromExamine; ValidateAndSetProperty(valueDictionary, val => _id = int.Parse(val), "id", "nodeId", "__NodeId"); //should validate the int! ValidateAndSetProperty(valueDictionary, val => _key = Guid.Parse(val), "key"); // wtf are we dealing with templates for medias?! ValidateAndSetProperty(valueDictionary, val => _templateId = int.Parse(val), "template", "templateId"); ValidateAndSetProperty(valueDictionary, val => _sortOrder = int.Parse(val), "sortOrder"); ValidateAndSetProperty(valueDictionary, val => _name = val, "nodeName", "__nodeName"); ValidateAndSetProperty(valueDictionary, val => _urlName = val, "urlName"); ValidateAndSetProperty(valueDictionary, val => _documentTypeAlias = val, "nodeTypeAlias", UmbracoContentIndexer.NodeTypeAliasFieldName); ValidateAndSetProperty(valueDictionary, val => _documentTypeId = int.Parse(val), "nodeType"); ValidateAndSetProperty(valueDictionary, val => _writerName = val, "writerName"); ValidateAndSetProperty(valueDictionary, val => _creatorName = val, "creatorName", "writerName"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _writerId = int.Parse(val), "writerID"); ValidateAndSetProperty(valueDictionary, val => _creatorId = int.Parse(val), "creatorID", "writerID"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _path = val, "path", "__Path"); ValidateAndSetProperty(valueDictionary, val => _createDate = ParseDateTimeValue(val), "createDate"); ValidateAndSetProperty(valueDictionary, val => _updateDate = ParseDateTimeValue(val), "updateDate"); ValidateAndSetProperty(valueDictionary, val => _level = int.Parse(val), "level"); ValidateAndSetProperty(valueDictionary, val => { int pId; ParentId = -1; if (int.TryParse(val, out pId)) { ParentId = pId; } }, "parentID"); _contentType = PublishedContentType.Get(PublishedItemType.Media, _documentTypeAlias); _properties = new Collection <IPublishedProperty>(); //handle content type properties //make sure we create them even if there's no value foreach (var propertyType in _contentType.PropertyTypes) { var alias = propertyType.PropertyTypeAlias; _keysAdded.Add(alias); string value; const bool isPreviewing = false; // false :: never preview a media var property = valueDictionary.TryGetValue(alias, out value) == false || value == null ? new XmlPublishedProperty(propertyType, isPreviewing) : new XmlPublishedProperty(propertyType, isPreviewing, value); _properties.Add(property); } //loop through remaining values that haven't been applied foreach (var i in valueDictionary.Where(x => _keysAdded.Contains(x.Key) == false && // not already processed IgnoredKeys.Contains(x.Key) == false)) // not ignorable { if (i.Key.InvariantStartsWith("__")) { // no type for that one, dunno how to convert IPublishedProperty property = new PropertyResult(i.Key, i.Value, PropertyResultType.CustomProperty); _properties.Add(property); } else { // this is a property that does not correspond to anything, ignore and log LogHelper.Warn <PublishedMediaCache>("Dropping property \"" + i.Key + "\" because it does not belong to the content type."); } } }
// note: I'm not sure this class fully complies with IPublishedContent rules especially // I'm not sure that _properties contains all properties including those without a value, // neither that GetProperty will return a property without a value vs. null... @zpqrtbnk public DictionaryPublishedContent( IDictionary <string, string> valueDictionary, Func <DictionaryPublishedContent, IPublishedContent> getParent, Func <DictionaryPublishedContent, IEnumerable <IPublishedContent> > getChildren, Func <DictionaryPublishedContent, string, IPublishedProperty> getProperty, bool fromExamine) { if (valueDictionary == null) { throw new ArgumentNullException("valueDictionary"); } if (getParent == null) { throw new ArgumentNullException("getParent"); } if (getProperty == null) { throw new ArgumentNullException("getProperty"); } _getParent = getParent; _getChildren = getChildren; _getProperty = getProperty; LoadedFromExamine = fromExamine; ValidateAndSetProperty(valueDictionary, val => _id = int.Parse(val), "id", "nodeId", "__NodeId"); //should validate the int! ValidateAndSetProperty(valueDictionary, val => _templateId = int.Parse(val), "template", "templateId"); ValidateAndSetProperty(valueDictionary, val => _sortOrder = int.Parse(val), "sortOrder"); ValidateAndSetProperty(valueDictionary, val => _name = val, "nodeName", "__nodeName"); ValidateAndSetProperty(valueDictionary, val => _urlName = val, "urlName"); ValidateAndSetProperty(valueDictionary, val => _documentTypeAlias = val, "nodeTypeAlias", UmbracoContentIndexer.NodeTypeAliasFieldName); ValidateAndSetProperty(valueDictionary, val => _documentTypeId = int.Parse(val), "nodeType"); ValidateAndSetProperty(valueDictionary, val => _writerName = val, "writerName"); ValidateAndSetProperty(valueDictionary, val => _creatorName = val, "creatorName", "writerName"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _writerId = int.Parse(val), "writerID"); ValidateAndSetProperty(valueDictionary, val => _creatorId = int.Parse(val), "creatorID", "writerID"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _path = val, "path", "__Path"); ValidateAndSetProperty(valueDictionary, val => _createDate = ParseDateTimeValue(val), "createDate"); ValidateAndSetProperty(valueDictionary, val => _updateDate = ParseDateTimeValue(val), "updateDate"); ValidateAndSetProperty(valueDictionary, val => _level = int.Parse(val), "level"); ValidateAndSetProperty(valueDictionary, val => { int pId; ParentId = -1; if (int.TryParse(val, out pId)) { ParentId = pId; } }, "parentID"); _contentType = PublishedContentType.Get(PublishedItemType.Media, _documentTypeAlias); _properties = new Collection <IPublishedProperty>(); //loop through remaining values that haven't been applied foreach (var i in valueDictionary.Where(x => !_keysAdded.Contains(x.Key))) { IPublishedProperty property; // must ignore that one if (i.Key == "version") { continue; } if (i.Key.InvariantStartsWith("__")) { // no type for tha tone, dunno how to convert property = new PropertyResult(i.Key, i.Value, Guid.Empty, PropertyResultType.CustomProperty); } else { // use property type to ensure proper conversion var propertyType = _contentType.GetPropertyType(i.Key); property = new XmlPublishedProperty(propertyType, false, i.Value); // false :: never preview a media } _properties.Add(property); } }