public static object GetResult(this Task task) { try { if (!task.IsCompleted) { task.Wait(); } if (task is Task <object> taskObj) { return(taskObj.Result); } var taskType = task.GetType(); if (!taskType.IsGenericType || taskType.FullName.Contains("VoidTaskResult")) { return(null); } var props = TypeProperties.Get(taskType); var fn = props.GetPublicGetter("Result"); return(fn?.Invoke(task)); } catch (TypeAccessException) { return(null); //return null for void Task's } catch (Exception ex) { throw ex.UnwrapIfSingleException(); } }
public static DataMemberAttribute GetWeakDataMember(this FieldInfo pi) { var attr = pi.AllAttributes().FirstOrDefault(x => x.GetType().Name == ReflectionExtensions.DataMember); if (attr != null) { var attrType = attr.GetType(); var accessor = TypeProperties.Get(attr.GetType()); var newAttr = new DataMemberAttribute { Name = (string)accessor.GetPublicGetter("Name")(attr), EmitDefaultValue = (bool)accessor.GetPublicGetter("EmitDefaultValue")(attr), IsRequired = (bool)accessor.GetPublicGetter("IsRequired")(attr), }; var order = (int)accessor.GetPublicGetter("Order")(attr); if (order >= 0) { newAttr.Order = order; //Throws Exception if set to -1 } return(newAttr); } return(null); }
private async Task <object> ExecAndReturnResponseAsync <Table>(object dto, IDbConnection db, Func <ExecContext, Task <ExecValue> > fn) { var responseType = HostContext.Metadata.GetOperation(dto.GetType())?.ResponseType; var responseProps = responseType == null ? null : TypeProperties.Get(responseType); var idProp = responseProps?.GetAccessor(Keywords.Id); var countProp = responseProps?.GetAccessor(Keywords.Count); var resultProp = responseProps?.GetAccessor(Keywords.Result); var rowVersionProp = responseProps?.GetAccessor(Keywords.RowVersion); var execValue = await fn(new ExecContext(idProp, resultProp, countProp, rowVersionProp)); if (responseType == null) { return(null); } object idValue = null; var response = responseType.CreateInstance(); if (idProp != null && execValue.Id != null) { idValue = execValue.Id.ConvertTo(idProp.PropertyInfo.PropertyType); idProp.PublicSetter(response, idValue); } if (countProp != null && execValue.RowsUpdated != null) { countProp.PublicSetter(response, execValue.RowsUpdated.ConvertTo(countProp.PropertyInfo.PropertyType)); } if (resultProp != null && execValue.Id != null) { var result = await db.SingleByIdAsync <Table>(execValue.Id); resultProp.PublicSetter(response, result.ConvertTo(resultProp.PropertyInfo.PropertyType)); } if (rowVersionProp != null) { if (AutoMappingUtils.IsDefaultValue(idValue)) { var modelDef = typeof(Table).GetModelMetadata(); var dtoIdGetter = TypeProperties.Get(dto.GetType()).GetPublicGetter(modelDef.PrimaryKey.Name); if (dtoIdGetter != null) { idValue = dtoIdGetter(dto); } } if (AutoMappingUtils.IsDefaultValue(idValue)) { throw new NotSupportedException($"Could not resolve Primary Key from '{dto.GetType().Name}' to be able to resolve RowVersion"); } var rowVersion = await db.GetRowVersionAsync <Table>(idValue); rowVersionProp.PublicSetter(response, rowVersion.ConvertTo(rowVersionProp.PropertyInfo.PropertyType)); } return(response); }
public override void Execute(IRequest req, IResponse res, object requestDto) { var errorViewGetter = TypeProperties.Get(requestDto.GetType()).GetPublicGetter(FieldName); if (errorViewGetter?.Invoke(requestDto) is string errorView) { req.SetErrorView(errorView); } }
/// <summary> /// Shortcut to get the ResponseStatus whether it's bare or inside a IHttpResult /// </summary> /// <param name="response"></param> /// <returns></returns> public static ResponseStatus GetResponseStatus(this object response) { if (response == null) return null; if (response is ResponseStatus status) return status; if (response is IHasResponseStatus hasResponseStatus) return hasResponseStatus.ResponseStatus; var statusGetter = TypeProperties.Get(response.GetType()).GetPublicGetter(nameof(ResponseStatus)); return statusGetter?.Invoke(response) as ResponseStatus; }
public static DataContractAttribute GetWeakDataContract(this Type type) { var attr = type.AllAttributes().FirstOrDefault(x => x.GetType().Name == DataContract); if (attr != null) { var attrType = attr.GetType(); var accessor = TypeProperties.Get(attr.GetType()); return(new DataContractAttribute { Name = (string)accessor.GetPublicGetter("Name")(attr), Namespace = (string)accessor.GetPublicGetter("Namespace")(attr), }); } return(null); }
internal static CrudContext Create <Table>(IRequest request, IDbConnection db, object dto, string operation) { var appHost = HostContext.AppHost; var requestType = dto?.GetType() ?? throw new ArgumentNullException(nameof(dto)); var responseType = appHost.Metadata.GetOperation(requestType)?.ResponseType; var responseProps = responseType == null ? null : TypeProperties.Get(responseType); return(new CrudContext { Operation = operation, Request = request ?? throw new ArgumentNullException(nameof(request)), Db = db ?? throw new ArgumentNullException(nameof(db)), Events = appHost.TryResolve <ICrudEvents>(), Dto = dto, ModelType = typeof(Table), RequestType = requestType, ModelDef = typeof(Table).GetModelMetadata(), ResponseType = responseType, IdProp = responseProps?.GetAccessor(Keywords.Id), CountProp = responseProps?.GetAccessor(Keywords.Count), ResultProp = responseProps?.GetAccessor(Keywords.Result), RowVersionProp = responseProps?.GetAccessor(Keywords.RowVersion), });
public static object GetResult(this Task task) { try { task.Wait(); var taskType = task.GetType(); if (!taskType.IsGenericType || taskType.FullName.Contains("VoidTaskResult")) return null; var fn = TypeProperties.Get(taskType).GetPublicGetter("Result"); return fn?.Invoke(task); } catch (TypeAccessException) { return null; //return null for void Task's } catch (Exception ex) { throw ex.UnwrapIfSingleException(); } }
public void PopulateRequestFromHeaders(object request, global::Grpc.Core.Metadata headers) { if (headers.Count == 0) { return; } var props = TypeProperties.Get(request.GetType()); var to = new Dictionary <string, object>(); foreach (var entry in headers) { var key = entry.Key.IndexOf('.') >= 0 && ( entry.Key.StartsWith("query.") || entry.Key.StartsWith("form.") || entry.Key.StartsWith("cookie.") || entry.Key.StartsWith("header.")) ? entry.Key.RightPart('.') : entry.Key; if (!props.PropertyMap.TryGetValue(key, out var accessor)) { continue; } var propName = accessor.PropertyInfo.Name; to[propName] = !entry.Key.EndsWith("-bin") ? (object)entry.Value : entry.ValueBytes; } if (to.Count > 0) { to.PopulateInstance(request); } }
internal GetMemberDelegate RequestIdGetter() => TypeProperties.Get(RequestType).GetPublicGetter(ModelDef.PrimaryKey.Name);
public static Dictionary <string, object> ToObjectDictionary( this object obj, Func <string, object, object> mapper) { if (obj == null) { return(null); } if (obj is Dictionary <string, object> alreadyDict) { if (mapper != null) { return(mapper.MapToDictionary(alreadyDict)); } return(alreadyDict); } if (obj is IDictionary <string, object> interfaceDict) { if (mapper != null) { return(mapper.MapToDictionary(interfaceDict)); } return(new Dictionary <string, object>(interfaceDict)); } var to = new Dictionary <string, object>(); if (obj is Dictionary <string, string> stringDict) { return(ConvertToDictionary(stringDict, mapper)); } if (obj is IDictionary d) { foreach (var key in d.Keys) { string k = key.ToString(); object v = d[key]; v = mapper?.Invoke(k, v) ?? v; to[k] = v; } return(to); } if (obj is NameValueCollection nvc) { for (var i = 0; i < nvc.Count; i++) { string k = nvc.GetKey(i); object v = nvc.Get(i); v = mapper?.Invoke(k, v) ?? v; to[k] = v; } return(to); } if (obj is IEnumerable <KeyValuePair <string, object> > objKvps) { return(ConvertToDictionary(objKvps, mapper)); } if (obj is IEnumerable <KeyValuePair <string, string> > strKvps) { return(ConvertToDictionary(strKvps, mapper)); } var type = obj.GetType(); if (type.GetKeyValuePairsTypes(out var keyType, out var valueType, out var kvpType) && obj is IEnumerable e) { var keyGetter = TypeProperties.Get(kvpType).GetPublicGetter("Key"); var valueGetter = TypeProperties.Get(kvpType).GetPublicGetter("Value"); foreach (var entry in e) { var key = keyGetter(entry); var value = valueGetter(entry); string k = key.ConvertTo <string>(); value = mapper?.Invoke(k, value) ?? value; to[k] = value; } return(to); } if (obj is KeyValuePair <string, object> objKvp) { string kk = nameof(objKvp.Key); object kv = objKvp.Key; kv = mapper?.Invoke(kk, kv) ?? kv; string vk = nameof(objKvp.Value); object vv = objKvp.Value; vv = mapper?.Invoke(vk, vv) ?? vv; return(new Dictionary <string, object> { [kk] = kv, [vk] = vv }); } if (obj is KeyValuePair <string, string> strKvp) { string kk = nameof(objKvp.Key); object kv = strKvp.Key; kv = mapper?.Invoke(kk, kv) ?? kv; string vk = nameof(strKvp.Value); object vv = strKvp.Value; vv = mapper?.Invoke(vk, vv) ?? vv; return(new Dictionary <string, object> { [kk] = kv, [vk] = vv }); } if (type.GetKeyValuePairTypes(out _, out var _)) { string kk = "Key"; object kv = TypeProperties.Get(type).GetPublicGetter("Key")(obj).ConvertTo <string>(); kv = mapper?.Invoke(kk, kv) ?? kv; string vk = "Value"; object vv = TypeProperties.Get(type).GetPublicGetter("Value")(obj); vv = mapper?.Invoke(vk, vv) ?? vv; return(new Dictionary <string, object> { [kk] = kv, [vk] = vv }); } if (!toObjectMapCache.TryGetValue(type, out var def)) { toObjectMapCache[type] = def = CreateObjectDictionaryDefinition(type); } foreach (var fieldDef in def.Fields) { string k = fieldDef.Name; object v = fieldDef.GetValueFn(obj); v = mapper?.Invoke(k, v) ?? v; to[k] = v; } return(to); }
public static Dictionary <string, object> ToObjectDictionary(this object obj) { if (obj == null) { return(null); } if (obj is Dictionary <string, object> alreadyDict) { return(alreadyDict); } if (obj is IDictionary <string, object> interfaceDict) { return(new Dictionary <string, object>(interfaceDict)); } var to = new Dictionary <string, object>(); if (obj is Dictionary <string, string> stringDict) { foreach (var entry in stringDict) { to[entry.Key] = entry.Value; } return(to); } if (obj is IDictionary d) { foreach (var key in d.Keys) { to[key.ToString()] = d[key]; } return(to); } if (obj is NameValueCollection nvc) { for (var i = 0; i < nvc.Count; i++) { to[nvc.GetKey(i)] = nvc.Get(i); } return(to); } if (obj is IEnumerable <KeyValuePair <string, object> > objKvps) { foreach (var kvp in objKvps) { to[kvp.Key] = kvp.Value; } return(to); } if (obj is IEnumerable <KeyValuePair <string, string> > strKvps) { foreach (var kvp in strKvps) { to[kvp.Key] = kvp.Value; } return(to); } var type = obj.GetType(); if (type.GetKeyValuePairsTypes(out var keyType, out var valueType, out var kvpType) && obj is IEnumerable e) { var keyGetter = TypeProperties.Get(kvpType).GetPublicGetter("Key"); var valueGetter = TypeProperties.Get(kvpType).GetPublicGetter("Value"); foreach (var entry in e) { var key = keyGetter(entry); var value = valueGetter(entry); to[key.ConvertTo <string>()] = value; } return(to); } if (obj is KeyValuePair <string, object> objKvp) { return new Dictionary <string, object> { { nameof(objKvp.Key), objKvp.Key }, { nameof(objKvp.Value), objKvp.Value } } } ; if (obj is KeyValuePair <string, string> strKvp) { return new Dictionary <string, object> { { nameof(strKvp.Key), strKvp.Key }, { nameof(strKvp.Value), strKvp.Value } } } ; if (type.GetKeyValuePairTypes(out _, out var _)) { return(new Dictionary <string, object> { { "Key", TypeProperties.Get(type).GetPublicGetter("Key")(obj).ConvertTo <string>() }, { "Value", TypeProperties.Get(type).GetPublicGetter("Value")(obj) }, }); } if (!toObjectMapCache.TryGetValue(type, out var def)) { toObjectMapCache[type] = def = CreateObjectDictionaryDefinition(type); } foreach (var fieldDef in def.Fields) { to[fieldDef.Name] = fieldDef.GetValueFn(obj); } return(to); }
internal static AutoCrudMetadata Create(Type dtoType) { if (cache.TryGetValue(dtoType, out var to)) { return(to); } to = new AutoCrudMetadata { DtoType = dtoType, ModelType = GetModelType(dtoType), DtoProps = TypeProperties.Get(dtoType), }; if (to.ModelType != null) { to.ModelDef = to.ModelType.GetModelMetadata(); } to.RowVersionGetter = to.DtoProps.GetPublicGetter(Keywords.RowVersion); var dtoAttrs = dtoType.AllAttributes(); foreach (var dtoAttr in dtoAttrs) { if (dtoAttr is AutoPopulateAttribute populateAttr) { to.PopulateAttrs ??= new List <AutoPopulateAttribute>(); to.PopulateAttrs.Add(populateAttr); } else if (dtoAttr is AutoFilterAttribute filterAttr) { to.AutoFilters ??= new List <AutoFilterAttribute>(); to.AutoFiltersDbFields ??= new List <QueryDbFieldAttribute>(); to.AutoFilters.Add(filterAttr); to.AutoFiltersDbFields.Add(ExprResult.ToDbFieldAttribute(filterAttr)); } } foreach (var pi in to.DtoProps.PublicPropertyInfos) { var allAttrs = pi.AllAttributes(); var propName = pi.Name; if (allAttrs.FirstOrDefault(x => x is AutoMapAttribute) is AutoMapAttribute mapAttr) { to.MapAttrs ??= new Dictionary <string, AutoMapAttribute>(); to.MapAttrs[propName] = mapAttr; propName = mapAttr.To; } if (allAttrs.FirstOrDefault(x => x is AutoUpdateAttribute) is AutoUpdateAttribute updateAttr) { to.UpdateAttrs ??= new Dictionary <string, AutoUpdateAttribute>(); to.UpdateAttrs[propName] = updateAttr; } if (allAttrs.FirstOrDefault(x => x is AutoDefaultAttribute) is AutoDefaultAttribute defaultAttr) { to.DefaultAttrs ??= new Dictionary <string, AutoDefaultAttribute>(); to.DefaultAttrs[propName] = defaultAttr; } if (pi.PropertyType.IsNullableType()) { to.NullableProps ??= new HashSet <string>(); to.NullableProps.Add(propName); } } return(cache[dtoType] = to); }