static Action<IDbCommand, bool> GetBindByName(Type commandType) { if (commandType == null) return null; // GIGO Action<IDbCommand, bool> action; if (Link<Type, Action<IDbCommand, bool>>.TryGet(bindByNameCache, commandType, out action)) { return action; } var prop = commandType.GetProperty("BindByName", BindingFlags.Public | BindingFlags.Instance); action = null; ParameterInfo[] indexers; MethodInfo setter; if (prop != null && prop.CanWrite && prop.PropertyType == typeof(bool) && ((indexers = prop.GetIndexParameters()) == null || indexers.Length == 0) && (setter = prop.GetSetMethod()) != null ) { var method = new DynamicMethod(commandType.GetOperationName() + "_BindByName", null, new Type[] { typeof(IDbCommand), typeof(bool) }); var il = method.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Castclass, commandType); il.Emit(OpCodes.Ldarg_1); il.EmitCall(OpCodes.Callvirt, setter, null); il.Emit(OpCodes.Ret); action = (Action<IDbCommand, bool>)method.CreateDelegate(typeof(Action<IDbCommand, bool>)); } // cache it Link<Type, Action<IDbCommand, bool>>.TryAdd(ref bindByNameCache, commandType, ref action); return action; }
public Message EmptyResponse(Message requestMsg, Type requestType) { var responseType = AssemblyUtils.FindType(requestType.FullName + "Response"); var response = (responseType ?? WebRequestUtils.GetErrorResponseDtoType(requestType)).CreateInstance(); return requestMsg.Headers.Action == null ? Message.CreateMessage(requestMsg.Version, null, response) : Message.CreateMessage(requestMsg.Version, requestType.GetOperationName() + "Response", response); }
protected override string CreateMessage(Type dtoType) { try { var requestObj = AutoMappingUtils.PopulateWith(Activator.CreateInstance(dtoType)); using (var ms = MemoryStreamFactory.GetStream()) { HostContext.ContentTypes.SerializeToStream( new BasicRequest { ContentType = this.ContentType }, requestObj, ms); return Encoding.UTF8.GetString(ms.ToArray()); } } catch (Exception ex) { var error = $"Error serializing type '{dtoType.GetOperationName()}' with custom format '{this.ContentFormat}'"; Log.Error(error, ex); return $"{{Unable to show example output for type '{dtoType.GetOperationName()}' using the custom '{this.ContentFormat}' filter}}{ex.Message}"; } }
public static void WithMatchingAttributes(IServiceRoutes routes, Type requestType, string allowedVerbs) { var membersWithAttribute = (from p in requestType.GetPublicProperties() let attributes = p.AllAttributes<Attribute>() where attributes.Any(a => AttributeNamesToMatch.Contains(a.GetType().GetOperationName())) select "{{{0}}}".Fmt(p.Name)).ToList(); if (membersWithAttribute.Count == 0) return; membersWithAttribute.Insert(0, "/{0}".Fmt(requestType.GetOperationName())); var restPath = membersWithAttribute.Join("/"); routes.Add(requestType, restPath: restPath, verbs: allowedVerbs, priority: AutoGenPriority); }
public static void WithMatchingPropertyNames(IServiceRoutes routes, Type requestType, string allowedVerbs) { var membersWithName = (from property in requestType.GetPublicProperties().Select(p => p.Name) from name in PropertyNamesToMatch where property.Equals(name, StringComparison.InvariantCultureIgnoreCase) select "{{{0}}}".Fmt(property)).ToList(); if (membersWithName.Count == 0) return; membersWithName.Insert(0, "/{0}".Fmt(requestType.GetOperationName())); var restPath = membersWithName.Join("/"); routes.Add(requestType, restPath: restPath, verbs: allowedVerbs, priority: AutoGenPriority); }
public ServiceExecFn GetService(Type requestType) { ServiceExecFn handlerFn; if (!requestExecMap.TryGetValue(requestType, out handlerFn)) { throw new NotImplementedException(string.Format("Unable to resolve service '{0}'", requestType.GetOperationName())); } return handlerFn; }
/// <summary> /// Gets the name of the base most type in the heirachy tree with the same. /// /// We get an exception when trying to create a schema with multiple types of the same name /// like when inheriting from a DataContract with the same name. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public static Type GetBaseTypeWithTheSameName(Type type) { var typesWithSameName = new Stack<Type>(); var baseType = type; do { if (baseType.GetOperationName() == type.GetOperationName()) typesWithSameName.Push(baseType); } while ((baseType = baseType.BaseType) != null); return typesWithSameName.Pop(); }
public MetadataType ToType(Type type) { if (type == null) return null; if (type.IsGenericType()) type = type.GetGenericTypeDefinition(); var metaType = new MetadataType { Name = type.GetOperationName(), Namespace = type.Namespace, GenericArgs = type.IsGenericType() ? GetGenericArgs(type) : null, Implements = ToInterfaces(type), Attributes = ToAttributes(type), Properties = ToProperties(type), IsNested = type.IsNested ? true : (bool?)null, IsEnum = type.IsEnum() ? true : (bool?)null, IsEnumInt = JsConfig.TreatEnumAsInteger || type.IsEnumFlags() ? true : (bool?)null, IsInterface = type.IsInterface() ? true : (bool?)null, IsAbstract = type.IsAbstract() ? true : (bool?)null, }; if (type.BaseType() != null && type.BaseType() != typeof(object) && !type.IsEnum() && !type.HasInterface(typeof(IService))) { metaType.Inherits = ToTypeName(type.BaseType()); } if (type.GetTypeWithInterfaceOf(typeof(IReturnVoid)) != null) { metaType.ReturnVoidMarker = true; } else { var genericMarker = type != typeof(IReturn<>) ? type.GetTypeWithGenericTypeDefinitionOf(typeof(IReturn<>)) : null; if (genericMarker != null) { var returnType = genericMarker.GetGenericArguments().First(); metaType.ReturnMarkerTypeName = ToTypeName(returnType); } } var routeAttrs = HostContext.AppHost.GetRouteAttributes(type).ToList(); if (routeAttrs.Count > 0) { metaType.Routes = routeAttrs.ConvertAll(x => new MetadataRoute { Path = x.Path, Notes = x.Notes, Summary = x.Summary, Verbs = x.Verbs, }); } metaType.Description = type.GetDescription(); var dcAttr = type.GetDataContract(); if (dcAttr != null) { metaType.DataContract = new MetadataDataContract { Name = dcAttr.Name, Namespace = dcAttr.Namespace, }; } if (type.IsEnum()) { metaType.EnumNames = new List<string>(); metaType.EnumValues = new List<string>(); var isDefaultLayout = true; var values = Enum.GetValues(type); for (var i = 0; i < values.Length; i++) { var value = values.GetValue(i); var name = value.ToString(); var enumValue = Convert.ToInt64(value).ToString(); if (enumValue != i.ToString()) isDefaultLayout = false; metaType.EnumNames.Add(name); metaType.EnumValues.Add(enumValue); } if (isDefaultLayout) metaType.EnumValues = null; } var innerTypes = type.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic); foreach (var innerType in innerTypes) { if (metaType.InnerTypes == null) metaType.InnerTypes = new List<MetadataTypeName>(); metaType.InnerTypes.Add(new MetadataTypeName { Name = innerType.GetOperationName(), Namespace = innerType.Namespace, GenericArgs = innerType.IsGenericType() ? innerType.GetGenericArguments().Select(x => x.GetOperationName()).ToArray() : null, }); } return metaType; }
public MetadataTypeName ToTypeName(Type type) { if (type == null) return null; return new MetadataTypeName { Name = type.GetOperationName(), Namespace = type.Namespace, GenericArgs = type.IsGenericType() ? type.GetGenericArguments().Select(x => x.GetOperationName()).ToArray() : null, }; }
public void AssertServiceRestrictions(Type requestType, RequestAttributes actualAttributes) { if (!appHost.Config.EnableAccessRestrictions) return; if ((RequestAttributes.InProcess & actualAttributes) == RequestAttributes.InProcess) return; RestrictAttribute restrictAttr; var hasNoAccessRestrictions = !requestServiceAttrs.TryGetValue(requestType, out restrictAttr) || restrictAttr.HasNoAccessRestrictions; if (hasNoAccessRestrictions) { return; } var failedScenarios = StringBuilderCache.Allocate(); foreach (var requiredScenario in restrictAttr.AccessibleToAny) { var allServiceRestrictionsMet = (requiredScenario & actualAttributes) == actualAttributes; if (allServiceRestrictionsMet) { return; } var passed = requiredScenario & actualAttributes; var failed = requiredScenario & ~(passed); failedScenarios.AppendFormat("\n -[{0}]", failed); } var internalDebugMsg = (RequestAttributes.InternalNetworkAccess & actualAttributes) != 0 ? "\n Unauthorized call was made from: " + actualAttributes : ""; throw new UnauthorizedAccessException( string.Format("Could not execute service '{0}', The following restrictions were not met: '{1}'" + internalDebugMsg, requestType.GetOperationName(), StringBuilderCache.ReturnAndFree(failedScenarios))); }
public ServiceExecFn GetService(Type requestType) { ServiceExecFn handlerFn; if (!requestExecMap.TryGetValue(requestType, out handlerFn)) { if (requestType.IsArray) { var elType = requestType.GetElementType(); if (requestExecMap.TryGetValue(elType, out handlerFn)) { return CreateAutoBatchServiceExec(handlerFn); } } throw new NotImplementedException(string.Format("Unable to resolve service '{0}'", requestType.GetOperationName())); } return handlerFn; }
public void RegisterRestPaths(Type requestType) { var attrs = appHost.GetRouteAttributes(requestType); foreach (RouteAttribute attr in attrs) { var restPath = new RestPath(requestType, attr.Path, attr.Verbs, attr.Summary, attr.Notes); var defaultAttr = attr as FallbackRouteAttribute; if (defaultAttr != null) { if (appHost.Config.FallbackRestPath != null) throw new NotSupportedException(string.Format( "Config.FallbackRestPath is already defined. Only 1 [FallbackRoute] is allowed.")); appHost.Config.FallbackRestPath = (httpMethod, pathInfo, filePath) => { var pathInfoParts = RestPath.GetPathPartsForMatching(pathInfo); return restPath.IsMatch(httpMethod, pathInfoParts) ? restPath : null; }; continue; } if (!restPath.IsValid) throw new NotSupportedException(string.Format( "RestPath '{0}' on Type '{1}' is not Valid", attr.Path, requestType.GetOperationName())); RegisterRestPath(restPath); } }
public MetadataType ToType(Type type) { if (type == null) return null; var metaType = new MetadataType { Name = type.GetOperationName(), Namespace = type.Namespace, GenericArgs = type.IsGenericType ? type.GetGenericArguments().Select(x => x.GetOperationName()).ToArray() : null, Attributes = ToAttributes(type), Properties = ToProperties(type), }; if (type.BaseType != null && type.BaseType != typeof(object)) { metaType.Inherits = new MetadataTypeName { Name = type.BaseType.GetOperationName(), GenericArgs = type.BaseType.IsGenericType ? type.BaseType.GetGenericArguments().Select(x => x.GetOperationName()).ToArray() : null }; } if (type.GetTypeWithInterfaceOf(typeof(IReturnVoid)) != null) { metaType.ReturnVoidMarker = true; } else { var genericMarker = type.GetTypeWithGenericTypeDefinitionOf(typeof(IReturn<>)); if (genericMarker != null) { metaType.ReturnMarkerTypeName = ToTypeName(genericMarker.GetGenericArguments().First()); } } var routeAttrs = HostContext.AppHost.GetRouteAttributes(type).ToList(); if (routeAttrs.Count > 0) { metaType.Routes = routeAttrs.ConvertAll(x => new MetadataRoute { Path = x.Path, Notes = x.Notes, Summary = x.Summary, Verbs = x.Verbs, }); } metaType.Description = type.GetDescription(); var dcAttr = type.GetDataContract(); if (dcAttr != null) { metaType.DataContract = new MetadataDataContract { Name = dcAttr.Name, Namespace = dcAttr.Namespace, }; } return metaType; }
public ServiceExecFn GetService(Type requestType) { ServiceExecFn handlerFn; if (!requestExecMap.TryGetValue(requestType, out handlerFn)) { if (requestType.IsArray) { var elType = requestType.GetElementType(); if (requestExecMap.TryGetValue(elType, out handlerFn)) { return (req, dtos) => from object dto in (IEnumerable)dtos select handlerFn(req, dto); } } throw new NotImplementedException(string.Format("Unable to resolve service '{0}'", requestType.GetOperationName())); } return handlerFn; }
public ExecOnceOnly(IRedisClientsManager redisManager, Type forType, string correlationId) : this(redisManager, "hash:nx:" + forType.GetOperationName(), correlationId) { }
public static Message CreateResponseMessage(object response, MessageVersion msgVersion, Type requestType, bool noMsgAction) { var useXmlSerializerResponse = response != null && response.GetType().HasAttribute<XmlSerializerFormatAttribute>(); if (useXmlSerializerResponse) { return noMsgAction ? Message.CreateMessage(msgVersion, null, response, new XmlSerializerWrapper(response.GetType())) : Message.CreateMessage(msgVersion, requestType.GetOperationName() + "Response", response, new XmlSerializerWrapper(response.GetType())); } return noMsgAction ? Message.CreateMessage(msgVersion, null, response) : Message.CreateMessage(msgVersion, requestType.GetOperationName() + "Response", response); }
public ExecOnceOnly(IRedisClientsManager redisManager, Type forType, Guid? correlationId) : this(redisManager, "hash:nx:" + forType.GetOperationName(), (correlationId.HasValue ? correlationId.Value.ToString("N") : null)) { }
public static void WithRequestDtoName(IServiceRoutes routes, Type requestType, string allowedVerbs) { routes.Add(requestType, restPath: "/{0}".Fmt(requestType.GetOperationName()), verbs: allowedVerbs, priority:AutoGenPriority); }
public void RegisterService(ITypeFactory serviceFactoryFn, Type serviceType) { var processedReqs = new HashSet<Type>(); if (IsServiceType(serviceType)) { foreach (var mi in serviceType.GetActions()) { var requestType = mi.GetParameters()[0].ParameterType; if (processedReqs.Contains(requestType)) continue; processedReqs.Add(requestType); RegisterServiceExecutor(requestType, serviceType, serviceFactoryFn); var returnMarker = requestType.GetTypeWithGenericTypeDefinitionOf(typeof(IReturn<>)); var responseType = returnMarker != null ? returnMarker.GetGenericArguments()[0] : mi.ReturnType != typeof(object) && mi.ReturnType != typeof(void) ? mi.ReturnType : AssemblyUtils.FindType(requestType.FullName + ResponseDtoSuffix); RegisterRestPaths(requestType); appHost.Metadata.Add(serviceType, requestType, responseType); if (typeof(IRequiresRequestStream).IsAssignableFrom(requestType)) { this.RequestTypeFactoryMap[requestType] = req => { var restPath = req.GetRoute(); var request = RestHandler.CreateRequest(req, restPath, req.GetRequestParams(), requestType.CreateInstance()); var rawReq = (IRequiresRequestStream)request; rawReq.RequestStream = req.InputStream; return rawReq; }; } if (Log.IsDebugEnabled) Log.DebugFormat("Registering {0} service '{1}' with request '{2}'", responseType != null ? "Reply" : "OneWay", serviceType.GetOperationName(), requestType.GetOperationName()); } } }