public RouteHandler( string service, string template, object instance, MethodInfo method, IServiceProvider locator, IWireSerialization serialization) { this.Service = "/" + service.ToLowerInvariant(); this.Template = template; this.Pattern = new UriPattern(template == "*" ? "/*" : template); var methodParams = method.GetParameters(); TotalParams = methodParams.Length; WithStream = TotalParams != 0 && methodParams[TotalParams - 1].ParameterType == typeof(Stream); var lamParams = new ParameterExpression[5]; lamParams[0] = Expression.Parameter(typeof(string[]), "strArr"); lamParams[1] = Expression.Parameter(typeof(IRequestContext), "request"); lamParams[2] = Expression.Parameter(typeof(IResponseContext), "response"); lamParams[3] = Expression.Parameter(typeof(Stream), "input"); lamParams[4] = Expression.Parameter(typeof(ChunkedMemoryStream), "output"); var expArgs = new Expression[TotalParams]; var argInd = 0; for (int i = 0; i < TotalParams; i++) { var mp = methodParams[i]; if (mp.ParameterType == typeof(IRequestContext)) { expArgs[i] = lamParams[1]; } else if (mp.ParameterType == typeof(IResponseContext)) { expArgs[i] = lamParams[2]; } else if (i < TotalParams - 1 || !WithStream) { expArgs[i] = Expression.ArrayIndex(lamParams[0], Expression.Constant(argInd++)); } else { expArgs[i] = lamParams[3]; } } var mce = Expression.Call(Expression.Constant(instance, instance.GetType()), method, expArgs); if (typeof(IHtmlView).IsAssignableFrom(method.ReturnType)) { mce = Expression.Call(null, RenderFunc.Method, mce, lamParams[2], lamParams[4]); } else if (!typeof(Stream).IsAssignableFrom(method.ReturnType) && method.ReturnType != typeof(void)) { var ws = Expression.Constant(serialization); mce = Expression.Call(null, SerializeFunc.Method, ws, lamParams[1], lamParams[2], mce, lamParams[4]); } var lambda = Expression.Lambda <Func <string[], IRequestContext, IResponseContext, Stream, ChunkedMemoryStream, Stream> >(mce, lamParams); Invocation = lambda.Compile(); }
public static Either <object> ParseGenericSpecification <TFormat>(this IWireSerialization serializer, Either <Type> domainType, Stream data) { if (domainType.IsFailure) { return(domainType.Error); } var genSer = serializer.GetSerializer <TFormat>(); var specType = typeof(GenericSpecification <,>).MakeGenericType(domainType.Result, typeof(TFormat)); try { var arg = ParseObject(serializer, typeof(Dictionary <string, List <KeyValuePair <int, TFormat> > >), data, true, null); if (arg.IsFailure) { return(arg.Error); } return(Activator.CreateInstance(specType, genSer, arg.Result)); } catch (Exception ex) { if (ex.InnerException != null) { ex = ex.InnerException; } var specArg = new Dictionary <string, List <KeyValuePair <int, TFormat> > >(); specArg["URI"] = new List <KeyValuePair <int, TFormat> >(new[] { new KeyValuePair <int, TFormat>(1, genSer.Serialize("1001")) }); return(@"Error deserializing specification. " + ex.Message + @" Example: " + serializer.SerializeToString(specArg)); } }
public CommandConverter( IRestApplication application, IObjectFactory objectFactory, IProcessingEngine processingEngine, IWireSerialization serialization, ISerialization <Stream> protobuf, ISerialization <XElement> xml, ISerialization <StreamReader> json) { Contract.Requires(application != null); Contract.Requires(objectFactory != null); Contract.Requires(processingEngine != null); Contract.Requires(serialization != null); Contract.Requires(protobuf != null); Contract.Requires(xml != null); Contract.Requires(json != null); this.Application = application; this.ObjectFactory = objectFactory; this.ProcessingEngine = processingEngine; this.Serialization = serialization; this.Protobuf = protobuf; this.Xml = xml; this.Json = json; }
public ExecuteCommand(IObjectFactory objectFactory, IWireSerialization serialization, ILoggerProvider loggerProvider) { this.objectFactory = objectFactory; this.serialization = serialization; this.streamingContext = new StreamingContext(StreamingContextStates.All, objectFactory); this.logger = loggerProvider.CreateLogger(typeof(ExecuteCommand <T>).FullName); }
private void ConfigureService(IServiceProvider locator, IWireSerialization serialization, string name, Type type) { var instance = locator.GetService(type); foreach (var i in new[] { type }.Union(type.GetInterfaces())) { foreach (var m in i.GetMethods()) { var inv = (WebInvokeAttribute[])m.GetCustomAttributes(typeof(WebInvokeAttribute), false); var get = (WebGetAttribute[])m.GetCustomAttributes(typeof(WebGetAttribute), false); var route = (RouteAttribute[])m.GetCustomAttributes(typeof(RouteAttribute), false); foreach (var at in inv) { var rh = new RouteHandler(name, at.UriTemplate, instance, true, m, locator, serialization); Add(at.Method, rh); } foreach (var at in get) { var rh = new RouteHandler(name, at.UriTemplate, instance, true, m, locator, serialization); Add("GET", rh); } foreach (var at in route) { var rh = new RouteHandler(name, at.Path, instance, at.IsAsync, m, locator, serialization); Add(at.Method, rh); } } } }
public static object Deserialize( IWireSerialization serialization, Stream input, Type target, string contentType, StreamingContext context) { return(serialization.Deserialize(input, target, contentType, context)); }
public RestApplication( IProcessingEngine processingEngine, IObjectFactory objectFactory, IWireSerialization serialization) { this.ProcessingEngine = processingEngine; this.ObjectFactory = objectFactory; this.Serialization = serialization; }
private static string SerializeToString(this IWireSerialization serializer, object instance) { using (var cms = ChunkedMemoryStream.Create()) { var ct = serializer.Serialize(instance, ThreadContext.Request.Accept, cms); ThreadContext.Response.ContentType = ct; return(cms.GetReader().ReadToEnd()); } }
/// <summary> /// Deserialize typesafe object without providing context information. /// .NET objects or value objects don't require context so they can be deserialized /// without IServiceLocator in context. /// </summary> /// <typeparam name="T">object type</typeparam> /// <param name="serialization">serialization service</param> /// <param name="source">serialized object in specified format</param> /// <param name="contentType">MIME type specifying the format</param> /// <returns>deserialized object</returns> public static T Deserialize <T>( this IWireSerialization serialization, Stream source, string contentType) { Contract.Requires(serialization != null); return((T)serialization.Deserialize(source, typeof(T), contentType, default(StreamingContext))); }
private static string SerializeToString(this IWireSerialization serializer, object instance) { using (var ms = new MemoryStream()) { var ct = serializer.Serialize(instance, ThreadContext.Request.Accept, ms); ThreadContext.Response.ContentType = ct; var sr = new StreamReader(ms); return(sr.ReadToEnd()); } }
protected BaseServerCommand(IServiceProvider locator, IDataContext context, IDatabaseQuery databaseQuery, IDomainModel domainModel, IWireSerialization serialization, ICommandConverter converter) { //TODO Is it bad to have a base Command like this that injects many of these: this.locator = locator; this.context = context; this.databaseQuery = databaseQuery; this.domainModel = domainModel; this.serialization = serialization; this.converter = converter; }
public static Try <object> ParseObject( IWireSerialization serializer, Try <Type> maybeType, Stream data, bool canCreate, IServiceProvider locator, HttpContext context) { if (maybeType.IsFailure) { return(Try <object> .Error); } var type = maybeType.Result; if (type == null) { return(Try <object> .Empty); } if (data == null) { if (canCreate == false) { return(Try.Fail <object>(@"{0} must be provided. Example: {1}".With(type.FullName, serializer.EmptyInstanceString(type, context)), context.Response)); } try { return(Activator.CreateInstance(type)); } catch (Exception ex) { return(Try.Fail <object>(@"Can't create instance of {0}. Data must be provided. Error: {1}. Example: {2}".With(type.FullName, ex.Message, serializer.EmptyInstanceString(type, context)), context.Response)); } } try { //TODO: deserialize async var sc = new StreamingContext(StreamingContextStates.All, locator); //TODO: objects deserialized here will have global scope access. Do OnDeserialized again later in scope return(serializer.Deserialize(data, type, context.Request.ContentType, sc)); } catch (TargetInvocationException tie) { var ex = tie.InnerException ?? tie; return(Try.Fail <object>(@"Can't deserialize {0}. Error: {1}. Example: {2}".With(type.FullName, ex.Message, serializer.EmptyInstanceString(type, context)), context.Response)); } catch (Exception ex) { return(Try.Fail <object>(@"Can't deserialize {0}. Error: {1}. Example: {2}".With(type.FullName, ex.Message, serializer.EmptyInstanceString(type, context)), context.Response)); } }
public RestApplication( IProcessingEngine processingEngine, IObjectFactory objectFactory, IWireSerialization serialization, IPluginRepository <IServerCommand> commandsRepository) { this.ProcessingEngine = processingEngine; this.ObjectFactory = objectFactory; this.Serialization = serialization; this.CommandsRepository = commandsRepository; }
public CrudCommands( IServiceLocator locator, ICommandConverter converter, IDomainModel domainModel, IWireSerialization serialization) { this.Locator = locator; this.Converter = converter; this.DomainModel = domainModel; this.Serialization = serialization; }
public CrudCommands( IServiceProvider locator, ICommandConverter converter, IDomainModel domainModel, IWireSerialization serialization) { this.Locator = locator; this.Converter = converter; this.DomainModel = domainModel; this.Serialization = serialization; }
public CachingDomainCommands( IDomainModel domainModel, DomainCommands domainCommands, IServiceProvider locator, IWireSerialization serialization) { this.DomainModel = domainModel; this.DomainCommands = domainCommands; this.Locator = locator; this.Serialization = serialization; }
public CommandConverter( RestApplication application, IObjectFactory objectFactory, IProcessingEngine processingEngine, IWireSerialization serialization) { this.Application = application; this.ObjectFactory = objectFactory; this.ProcessingEngine = processingEngine; this.Serialization = serialization; }
public ReportingMiddleware( IServiceProvider locator, CommandConverter converter, IDomainModel domainModel, IWireSerialization serialization) { this.Locator = locator; this.Converter = converter; this.DomainModel = domainModel; this.Serialization = serialization; }
public DomainController( IServiceProvider locator, CommandConverter converter, IDomainModel domainModel, IWireSerialization serialization) { this.Locator = locator; this.Converter = converter; this.DomainModel = domainModel; this.Serialization = serialization; }
public Routes(IServiceProvider locator, IWireSerialization serialization) { var totalControllers = 0; foreach (var t in AssemblyScanner.GetAllTypes()) { if (t.IsClass && !t.IsAbstract && (t.IsPublic || t.IsNestedPublic)) { var attr = t.GetCustomAttributes(typeof(ControllerAttribute), false) as ControllerAttribute[]; if (attr != null && attr.Length > 0) { totalControllers++; foreach (var a in attr) ConfigureService(locator, serialization, a.RootUrl, t); } } } var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var xml = XElement.Load(config.FilePath, LoadOptions.None); var sm = xml.Element("system.serviceModel"); if (sm == null) { if (totalControllers > 0) return; throw new ConfigurationErrorsException("Services not defined. system.serviceModel missing from configuration"); } var she = sm.Element("serviceHostingEnvironment"); if (she == null) { if (totalControllers > 0) return; throw new ConfigurationErrorsException("Services not defined. serviceHostingEnvironment missing from configuration"); } var sa = she.Element("serviceActivations"); if (sa == null) { if (totalControllers > 0) return; throw new ConfigurationErrorsException("Services not defined. serviceActivations missing from configuration"); } var services = sa.Elements("add").ToList(); if (services.Count == 0 && totalControllers == 0) throw new ConfigurationErrorsException("Services not defined and controllers not found on path. serviceActivations elements not defined in configuration"); foreach (XElement s in services) { var attributes = s.Attributes().ToList(); var ra = attributes.FirstOrDefault(it => "relativeAddress".Equals(it.Name.LocalName, StringComparison.InvariantCultureIgnoreCase)); var serv = attributes.FirstOrDefault(it => "service".Equals(it.Name.LocalName, StringComparison.InvariantCultureIgnoreCase)); if (serv == null || string.IsNullOrEmpty(serv.Value)) throw new ConfigurationErrorsException("Missing service type on serviceActivation element: " + s.ToString()); if (ra == null || string.IsNullOrEmpty(ra.Value)) throw new ConfigurationErrorsException("Missing relative address on serviceActivation element: " + s.ToString()); var type = Type.GetType(serv.Value); if (type == null) throw new ConfigurationErrorsException("Invalid service defined in " + ra.Value + ". Type " + serv.Value + " not found."); ConfigureService(locator, serialization, ra.Value, type); } }
public CachingDomainCommands( IDomainModel domainModel, DomainCommands domainCommands, IServiceLocator locator, IWireSerialization serialization) { this.DomainModel = domainModel; this.DomainCommands = domainCommands; this.Locator = locator; this.Serialization = serialization; }
public static Stream Serialize( IWireSerialization serialization, IRequestContext request, IResponseContext response, object result, ChunkedMemoryStream outputStream) { outputStream.Reset(); response.ContentType = serialization.Serialize(result, request.Accept, outputStream); response.ContentLength = outputStream.Position; outputStream.Position = 0; return(outputStream); }
public RevenjMiddleware( RequestDelegate next, IObjectFactory objectFactory, IWireSerialization serialization, IDomainModel domainModel, ILoggerProvider loggerProvider) { this.next = next; this.objectFactory = objectFactory; this.serialization = serialization; this.domainModel = domainModel; this.loggerProvider = loggerProvider; }
public DomainCommands( IServiceProvider locator, ICommandConverter converter, IProcessingEngine processing, IDomainModel domainModel, IWireSerialization serialization) { this.Locator = locator; this.Converter = converter; this.Processing = processing; this.DomainModel = domainModel; this.Serialization = serialization; }
private static string EmptyInstanceString(this IWireSerialization serializer, Type target) { try { return(SerializeToString(serializer, Revenj.Utility.TemporaryResources.CreateRandomObject(target))); } catch (Exception ex) { return(Exceptions.DebugMode ? "Error creating instance example: " + ex.Message : "Error creating instance example ;("); } }
public DomainCommands( IServiceLocator locator, ICommandConverter converter, IProcessingEngine processing, IDomainModel domainModel, IWireSerialization serialization) { this.Locator = locator; this.Converter = converter; this.Processing = processing; this.DomainModel = domainModel; this.Serialization = serialization; }
public RouteHandler( string service, string template, object instance, bool isAsync, MethodInfo method, IServiceProvider locator, IWireSerialization serialization) { this.Service = "/" + service.ToLowerInvariant(); this.Template = template; this.Pattern = new UriPattern(template == "*" ? "/*" : template); this.IsAsync = isAsync; this.Url = Service + template; var methodParams = method.GetParameters(); TotalParams = methodParams.Length; WithStream = TotalParams != 0 && methodParams[TotalParams - 1].ParameterType == typeof(Stream); var lamParams = new ParameterExpression[5]; lamParams[0] = Expression.Parameter(typeof(string[]), "strArr"); lamParams[1] = Expression.Parameter(typeof(IRequestContext), "request"); lamParams[2] = Expression.Parameter(typeof(IResponseContext), "response"); lamParams[3] = Expression.Parameter(typeof(Stream), "input"); lamParams[4] = Expression.Parameter(typeof(ChunkedMemoryStream), "output"); var expArgs = new Expression[TotalParams]; var argInd = 0; for (int i = 0; i < TotalParams; i++) { var mp = methodParams[i]; if (mp.ParameterType == typeof(IRequestContext)) expArgs[i] = lamParams[1]; else if (mp.ParameterType == typeof(IResponseContext)) expArgs[i] = lamParams[2]; else if (i < TotalParams - 1 || !WithStream) expArgs[i] = Expression.ArrayIndex(lamParams[0], Expression.Constant(argInd++)); else expArgs[i] = lamParams[3]; } var mce = Expression.Call(Expression.Constant(instance, instance.GetType()), method, expArgs); if (typeof(IHtmlView).IsAssignableFrom(method.ReturnType)) { mce = Expression.Call(null, RenderFunc.Method, mce, lamParams[2], lamParams[4]); } else if (!typeof(Stream).IsAssignableFrom(method.ReturnType) && method.ReturnType != typeof(void)) { var ws = Expression.Constant(serialization); mce = Expression.Call(null, SerializeFunc.Method, ws, lamParams[1], lamParams[2], mce, lamParams[4]); } var lambda = Expression.Lambda<Func<string[], IRequestContext, IResponseContext, Stream, ChunkedMemoryStream, Stream>>(mce, lamParams); Invocation = lambda.Compile(); }
private static string SerializeToString(this IWireSerialization serializer, object instance, HttpContext context) { StringValues headers; string accept = null; if (context.Request.Headers.TryGetValue("accept", out headers) && headers.Count > 0) { accept = headers[0]; } using (var cms = ChunkedMemoryStream.Create()) { var ct = serializer.Serialize(instance, accept, cms); context.Response.ContentType = ct; return(cms.GetReader().ReadToEnd()); } }
public RestApplication( IProcessingEngine processingEngine, IObjectFactory objectFactory, IWireSerialization serialization, IPluginRepository <IServerCommand> commandsRepository) { Contract.Requires(processingEngine != null); Contract.Requires(objectFactory != null); Contract.Requires(serialization != null); Contract.Requires(commandsRepository != null); this.ProcessingEngine = processingEngine; this.ObjectFactory = objectFactory; this.Serialization = serialization; this.CommandsRepository = commandsRepository; }
public CommandConverter( IRestApplication application, IObjectFactory objectFactory, IProcessingEngine processingEngine, IWireSerialization serialization) { Contract.Requires(application != null); Contract.Requires(objectFactory != null); Contract.Requires(processingEngine != null); Contract.Requires(serialization != null); this.Application = application; this.ObjectFactory = objectFactory; this.ProcessingEngine = processingEngine; this.Serialization = serialization; }
public static object ParseExpressionSpecification(IWireSerialization serializer, Type domainType, Stream data) { try { var expressionNode = serializer.Deserialize <LambdaExpressionNode>(data, ThreadContext.Request.ContentType); return(Activator.CreateInstance(typeof(SpecificationFromNode <>).MakeGenericType(domainType), expressionNode)); } catch (Exception ex) { if (ex.InnerException != null) { ex = ex.InnerException; } Utility.ThrowError(@"Error deserializing expression. " + ex.Message, HttpStatusCode.BadRequest); } return(null); }
public static Either <object> ParseGenericSpecification(this IWireSerialization serialization, Either <Type> target, Stream data) { if (target.IsFailure) { return(target.Error); } switch (GetIncomingFormat()) { case MessageFormat.Json: return(ParseGenericSpecification <string>(serialization, target, data)); case MessageFormat.ProtoBuf: return(ParseGenericSpecification <MemoryStream>(serialization, target, data)); default: return(ParseGenericSpecification <XElement>(serialization, target, data)); } }
public static object ParseObject( IWireSerialization serializer, Type type, Stream data, bool canCreate, IServiceLocator locator) { if (data == null) { if (canCreate == false) { ThrowError(@"{0} must be provided. Example: {1}".With(type.FullName, serializer.EmptyInstanceString(type)), HttpStatusCode.BadRequest); } try { return(Activator.CreateInstance(type)); } catch (Exception ex) { ThrowError(@"Can't create instance of {0}. Data must be provided. Error: {1}. Example: {2}".With(type.FullName, ex.Message, serializer.EmptyInstanceString(type)), HttpStatusCode.BadRequest); } } try { var sc = new StreamingContext(StreamingContextStates.All, locator); //TODO: objects deserialized here will have global scope access. Do OnDeserialized again later in scope return(serializer.Deserialize(data, type, ThreadContext.Request.ContentType, sc)); } catch (TargetInvocationException tie) { var ex = tie.InnerException ?? tie; throw new WebFaultException <string>(@"Can't deserialize {0}. Error: {1}. Example: {2}".With(type.FullName, ex.Message, serializer.EmptyInstanceString(type)), HttpStatusCode.BadRequest); } catch (Exception ex) { throw new WebFaultException <string>(@"Can't deserialize {0}. Error: {1}. Example: {2}".With(type.FullName, ex.Message, serializer.EmptyInstanceString(type)), HttpStatusCode.BadRequest); } }
public static Either <object> ParseExpressionSpecification(IWireSerialization serializer, Either <Type> domainType, Stream data) { if (domainType.IsFailure) { return(domainType.Error); } try { var expressionNode = serializer.Deserialize <LambdaExpressionNode>(data, ThreadContext.Request.ContentType); return(Activator.CreateInstance(typeof(SpecificationFromNode <>).MakeGenericType(domainType.Result), expressionNode)); } catch (Exception ex) { if (ex.InnerException != null) { ex = ex.InnerException; } return(@"Error deserializing expression. " + ex.Message); } }
public static Try <object> ParseGenericSpecification(this IWireSerialization serialization, Try <Type> target, HttpContext context) { if (target.IsFailure) { return(Try <object> .Error); } var request = context.Request; switch (GetIncomingFormat(request)) { case MessageFormat.Json: return(ParseGenericSpecification <string>(serialization, target, request.Body, context)); case MessageFormat.ProtoBuf: return(ParseGenericSpecification <MemoryStream>(serialization, target, request.Body, context)); default: return(ParseGenericSpecification <XElement>(serialization, target, request.Body, context)); } }
public static object Deserialize( IWireSerialization serialization, Stream input, Type target, string contentType, StreamingContext context) { return serialization.Deserialize(input, target, contentType, context); }
public static Stream Serialize( IWireSerialization serialization, IRequestContext request, IResponseContext response, object result, ChunkedMemoryStream outputStream) { outputStream.Reset(); response.ContentType = serialization.Serialize(result, request.Accept, outputStream); response.ContentLength = outputStream.Position; outputStream.Position = 0; return outputStream; }