public static void AddPluginsFromAssembly(this IAppHost appHost, params Assembly[] assembliesWithPlugins) { foreach (Assembly assembly in assembliesWithPlugins) { var pluginTypes = from t in assembly.GetExportedTypes() where t.GetInterfaces().Any(x => x == typeof(IPlugin)) select t; foreach (var pluginType in pluginTypes) { try { var plugin = pluginType.CreateInstance() as IPlugin; if (plugin != null) { EndpointHost.AddPlugin(plugin); } } catch (Exception ex) { log.Error("Error adding new Plugin " + pluginType.Name, ex); } } } }
protected virtual void Dispose(bool disposing) { if (disposed) { return; } lock (this) { if (disposed) { return; } if (disposing) { if (EndpointHost.Config != null && EndpointHost.Config.ServiceManager != null) { EndpointHost.Config.ServiceManager.Dispose(); } EndpointHost.Dispose(); } //release unmanaged resources here... disposed = true; } }
public void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName) { if (!EndpointHost.ApplyPreRequestFilters(httpReq, httpRes)) { var operationList = (from r in EndpointHost.Config.MetadataMap[_servicePath].Operations let sampleObjects = (ServiceUtils.IsCheckHealthOperation(operationName) ? SampleObjects.CheckHealthSampleMessage : SampleObjects.GetSampleMessage(_servicePath, r.Name)) ?? new SampleMessage(r.RequestType.CreateInstance(), r.ResponseType.CreateInstance()) let requestObject = ReflectionUtils.PopulateObject(sampleObjects.Request) let responseObject = ReflectionUtils.PopulateObject(sampleObjects.Response) select new { Name = r.Name, RequestMessage = new { Xml = XmlSerializeToString(requestObject), Json = WrappedJsonSerializer.Instance.SerializeToString(requestObject), }, ResponseMessage = new { Xml = XmlSerializeToString(responseObject), Json = WrappedJsonSerializer.Instance.SerializeToString(responseObject), } }).OrderBy(item => item.Name).ToList(); httpRes.ContentType = "application/json"; httpRes.Write(WrappedJsonSerializer.Instance.SerializeToString(operationList)); } }
public void Init() { if (Instance != null) { throw new InvalidDataException("HttpListenerBase.Instance has already been set"); } Instance = this; var serviceManager = EndpointHost.Config.ServiceManager; if (serviceManager != null) { serviceManager.Init(); Configure(EndpointHost.Config.ServiceManager.Container); } else { Configure(null); } EndpointHost.AfterInit(); SetAppDomainData(); var elapsed = DateTime.UtcNow - this.startTime; Log.InfoFormat("Initializing Application took {0}ms", elapsed.TotalMilliseconds); }
public void Init() { if (Instance != null) { throw new InvalidDataException("HttpListenerBase.Instance has already been set"); } Instance = this; if (this.serviceManager != null) { serviceManager.Init(); Configure(serviceManager.Container); } else { Configure(null); } EndpointHost.SetOperationTypes( EndpointHost.Config.ServiceController.OperationTypes, EndpointHost.Config.ServiceController.AllOperationTypes ); var elapsed = DateTime.Now - this.startTime; log.InfoFormat("Initializing Application took {0}ms", elapsed.TotalMilliseconds); }
static void Main(string[] args) { var setting = Configuration.GetSetting <Setting>(); var endpoint = new EndpointRunner(setting); Console.Title = setting.EndpointName; EndpointHost.RunAsConsoleAsync(endpoint).GetAwaiter().GetResult(); }
private bool ApplyResponseFilters <TResponse>(object response) { if (EndpointHost.ApplyResponseFilters(httpReq, httpRes, response)) { ThrowIfError <TResponse>(httpRes); return(true); } return(false); }
public static void EndServiceStackRequest(this HttpResponse httpRes, bool skipHeaders = false) { if (!skipHeaders) { httpRes.ApplyGlobalResponseHeaders(); } httpRes.Close(); EndpointHost.CompleteRequest(); }
protected Message ExecuteMessage(Message requestMsg, EndpointAttributes endpointAttributes) { if ((EndpointAttributes.Soap11 & this.HandlerAttributes) == EndpointAttributes.Soap11) { EndpointHost.Config.AssertFeatures(Feature.Soap11); } else if ((EndpointAttributes.Soap12 & this.HandlerAttributes) == EndpointAttributes.Soap12) { EndpointHost.Config.AssertFeatures(Feature.Soap12); } string requestXml; using (var reader = requestMsg.GetReaderAtBodyContents()) { requestXml = reader.ReadOuterXml(); } var requestType = GetRequestType(requestMsg, requestXml); try { var request = DataContractDeserializer.Instance.Parse(requestXml, requestType); IHttpRequest httpReq = null; IHttpResponse httpRes = null; var hasRequestFilters = EndpointHost.RequestFilters.Count > 0; var hasResponseFilters = EndpointHost.ResponseFilters.Count > 0; if (hasRequestFilters || hasResponseFilters) { httpReq = HttpContext.Current != null ? new HttpRequestWrapper(requestType.Name, HttpContext.Current.Request) : null; httpRes = HttpContext.Current != null ? new HttpResponseWrapper(HttpContext.Current.Response) : null; } EndpointHost.ApplyRequestFilters(httpReq, httpRes, request); var response = ExecuteService(request, endpointAttributes, null); EndpointHost.ApplyResponseFilters(httpReq, httpRes, response); return(requestMsg.Headers.Action == null ? Message.CreateMessage(requestMsg.Version, null, response) : Message.CreateMessage(requestMsg.Version, requestType.Name + "Response", response)); } catch (Exception ex) { throw new SerializationException("3) Error trying to deserialize requestType: " + requestType + ", xml body: " + requestXml, ex); } }
/// <summary> /// Adds the rest handlers. /// </summary> /// <param name="services">The services.</param> public void Init(IEnumerable <IRestfulService> services) { _restServices.AddRange(services); _logger.Info("Calling EndpointHost.ConfigureHost"); EndpointHost.ConfigureHost(this, ServerName, CreateServiceManager()); _logger.Info("Calling ServiceStack AppHost.Init"); Init(); }
protected virtual void OnConfigure() { if (HasConfigured) { return; } HasConfigured = true; Configure(Container); EndpointHost.AfterInit(); }
public static void CreateServiceRunnersFor <TRequest>() { foreach (var actionCtx in GetActionsFor <TRequest>()) { if (execMap.ContainsKey(actionCtx.Id)) { continue; } var serviceRunner = EndpointHost.CreateServiceRunner <TRequest>(actionCtx); execMap[actionCtx.Id] = serviceRunner.Process; } }
protected TestBase(string serviceClientBaseUri, params Assembly[] serviceAssemblies) { ServiceClientBaseUri = serviceClientBaseUri; ServiceAssemblies = serviceAssemblies; var appHost = new TestAppHost(this); this.AppHost = appHost; EndpointHost.ConfigureHost(this.AppHost, "TestBase", serviceAssemblies); EndpointHost.ServiceManager = appHost.Config.ServiceManager; }
/// <summary> /// Adds the rest handlers. /// </summary> /// <param name="services">The services.</param> public void Init(IEnumerable <IRestfulService> services) { _restServices.AddRange(services); _logger.Info("Calling EndpointHost.ConfigureHost"); EndpointHost.ConfigureHost(this, ServerName, CreateServiceManager()); _logger.Info("Registering protobuf as a content type filter"); ContentTypeFilters.Register(ContentType.ProtoBuf, (reqCtx, res, stream) => ProtobufSerializer.SerializeToStream(res, stream), (type, stream) => ProtobufSerializer.DeserializeFromStream(stream, type)); _logger.Info("Calling ServiceStack AppHost.Init"); Init(); }
private IEnumerable <PostmanRequest> GetRequests(IHttpRequest request, ServiceMetadata metadata, string parentId, IEnumerable <Operation> operations) { var feature = EndpointHost.GetPlugin <PostmanFeature>(); var label = request.GetParam("label") ?? feature.DefaultLabel; var customHeaders = request.GetParam("headers"); var headers = customHeaders == null ? feature.DefaultHeaders : customHeaders.Split(','); foreach (var op in metadata.OperationsMap.Values.Where(o => metadata.IsVisible(request, o))) { var exampleObject = ReflectionUtils.PopulateObject(op.RequestType.CreateInstance()).ToStringDictionary(); var data = op.RequestType.GetSerializableFields().Select(f => f.Name) .Concat(op.RequestType.GetSerializableProperties().Select(p => p.Name)) .ToDictionary(f => f, f => exampleObject.GetValueOrDefault(f)); foreach (var route in op.Routes) { var routeVerbs = route.AllowsAllVerbs ? new[] { "POST" } : route.AllowedVerbs.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries); var restRoute = new RestRoute(route.RequestType, route.Path, route.AllowedVerbs); foreach (var verb in routeVerbs) { yield return(new PostmanRequest { Id = Guid.NewGuid().ToString(), Headers = string.Join("\n", headers), Method = verb, Url = CalculateAppUrl(request, _aspnetSubPath) + restRoute.Path.ReplaceVariables(), Name = label.FormatLabel(op.RequestType, restRoute.Path), Description = op.RequestType.GetDescription(), PathVariables = restRoute.Variables.ToDictionary(v => v, v => data.GetValueOrDefault(v)), Data = data.Keys.Except(restRoute.Variables).Select(v => new PostmanData { Key = v, Value = data[v], Type = "text", }).ToArray(), DataMode = "params", Version = 2, Time = DateTime.UtcNow.ToUnixTimeMs(), CollectionId = parentId, Folder = restRoute.Path.GetFolderName() }); } } } }
static async Task Main(string[] args) { var host = new EndpointHost(); var endpoint = await Endpoint.Start(host.ConfigureSendOnlyApiEndpoint().Configuration); Console.WriteLine("Send only endpoint started."); Console.WriteLine("Press any key to start."); Console.ReadLine(); //await SimpleTransfer(endpoint); //await TheFundraiser(endpoint); await TheMillionairesGame(endpoint); Console.ReadLine(); }
private bool ApplyRequestFilters(object request) { if (EndpointHost.ApplyRequestFilters(httpReq, httpRes, request)) { if (httpRes.StatusCode >= 400) { throw new WebServiceException("WebServiceException, StatusCode: " + httpRes.StatusCode) { StatusCode = httpRes.StatusCode, }; } return(true); } return(false); }
public void Test_response_with_CompressedResult() { EndpointHost.Config = new EndpointHostConfig( "ServiceName", new ServiceManager(GetType().Assembly)); var assembly = typeof(CompressionTests).Assembly; EndpointHost.ConfigureHost( new TestAppHost(new Container(), assembly), "Name", new ServiceManager(assembly)); var mockResponse = new HttpResponseMock(); var simpleDto = new TestCompress(1, "name"); var simpleDtoXml = DataContractSerializer.Instance.Parse(simpleDto); const string expectedXml = "<TestCompress xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.ddnglobal.com/types/\"><Id>1</Id><Name>name</Name></TestCompress>"; Assert.That(simpleDtoXml, Is.EqualTo(expectedXml)); var simpleDtoZip = simpleDtoXml.Deflate(); Assert.That(simpleDtoZip.Length, Is.GreaterThan(0)); var compressedResult = new CompressedResult(simpleDtoZip); var reponseWasAutoHandled = mockResponse.WriteToResponse( compressedResult, CompressionTypes.Deflate); Assert.That(reponseWasAutoHandled, Is.True); //var bytesToWriteToResponseStream = new byte[simpleDtoZip.Length - 4]; //Array.Copy(simpleDtoZip, CompressedResult.Adler32ChecksumLength, bytesToWriteToResponseStream, 0, bytesToWriteToResponseStream.Length); var bytesToWriteToResponseStream = simpleDtoZip; var writtenBytes = mockResponse.GetOutputStreamAsBytes(); Assert.That(writtenBytes, Is.EqualTo(bytesToWriteToResponseStream)); Assert.That(mockResponse.ContentType, Is.EqualTo(MimeTypes.Xml)); Assert.That(mockResponse.Headers[HttpHeaders.ContentEncoding], Is.EqualTo(CompressionTypes.Deflate)); Log.Debug("Content-length: " + writtenBytes.Length); Log.Debug(BitConverter.ToString(writtenBytes)); }
protected TestBase(string serviceClientBaseUri, params Assembly[] serviceAssemblies) { if (serviceAssemblies.Length == 0) { serviceAssemblies = new[] { GetType().Assembly } } ; ServiceClientBaseUri = serviceClientBaseUri; ServiceAssemblies = serviceAssemblies; this.AppHost = new TestAppHost(null, serviceAssemblies); EndpointHost.ServiceManager = this.AppHost.Config.ServiceManager; EndpointHost.ConfigureHost(this.AppHost, "TestBase", EndpointHost.ServiceManager); }
protected void HandleException(IHttpRequest httpReq, IHttpResponse httpRes, string operationName, Exception ex) { var errorMessage = string.Format("Error occured while Processing Request: {0}", ex.Message); Log.Error(errorMessage, ex); try { EndpointHost.ExceptionHandler(httpReq, httpRes, operationName, ex); } catch (Exception writeErrorEx) { //Exception in writing to response should not hide the original exception Log.Info("Failed to write error to response: {0}", writeErrorEx); //rethrow the original exception throw ex; } finally { httpRes.EndServiceStackRequest(skipHeaders: true); } }
public void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName) { if (EndpointHost.ApplyPreRequestFilters(httpReq, httpRes)) { return; } var response = from o in EndpointHost.Config.MetadataMap[httpReq.ServicePath].Operations orderby o.Name ascending select new { Operation = o.Name, Routes = o.Routes.Select(r => new { Path = r.Path, AllowedVerbs = r.AllowedVerbs ?? "*" }).ToList() }; httpRes.ContentType = "application/json"; httpRes.Write(WrappedJsonSerializer.Instance.SerializeToString(response.ToList())); }
public static void Init(Func <IAuthSession> sessionFactory, params IAuthProvider[] authProviders) { EndpointHost.AssertTestConfig(); if (authProviders.Length == 0) { throw new ArgumentNullException("authProviders"); } DefaultOAuthProvider = authProviders[0].Provider; DefaultOAuthRealm = authProviders[0].AuthRealm; AuthProviders = authProviders; if (sessionFactory != null) { CurrentSessionFactory = sessionFactory; } }
public static void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto) { var validator = ValidatorCache.GetValidator(req, requestDto.GetType()); if (validator == null) { return; } var validatorWithHttpRequest = validator as IRequiresHttpRequest; if (validatorWithHttpRequest != null) { validatorWithHttpRequest.HttpRequest = req; } var ruleSet = req.HttpMethod; var validationResult = validator.Validate( new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet))); if (validationResult.IsValid) { return; } // mark request validation exception res.ExecutionResult.ValidationExceptionThrown = true; // find response type Type responseType = string.IsNullOrEmpty(req.OperationName) ? null : EndpointHost.Config.MetadataMap[req.ServicePath].GetResponseTypeByOpName(req.OperationName); var errorResponse = ErrorUtils.CreateValidationErrorResponse( req, validationResult.ToException(), responseType); var validationFeature = EndpointHost.GetPlugin <ValidationFeature>(); if (validationFeature != null && validationFeature.ErrorResponseFilter != null) { errorResponse = validationFeature.ErrorResponseFilter(validationResult, errorResponse); } res.WriteToResponse(req, errorResponse); }
public static void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto) { var validator = ValidatorCache.GetValidator(req, requestDto.GetType()); if (validator == null) { return; } var validatorWithHttpRequest = validator as IRequiresHttpRequest; if (validatorWithHttpRequest != null) { validatorWithHttpRequest.HttpRequest = req; } var ruleSet = req.HttpMethod; var validationResult = validator.Validate( new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet))); if (validationResult.IsValid) { return; } var errorResponse = DtoUtils.CreateErrorResponse( requestDto, validationResult.ToErrorResult()); var validationFeature = EndpointHost.GetPlugin <ValidationFeature>(); if (validationFeature != null && validationFeature.ErrorResponseFilter != null) { errorResponse = validationFeature.ErrorResponseFilter(validationResult, errorResponse); } res.WriteToResponse(req, errorResponse); }
protected void HandleException(IHttpRequest httpReq, IHttpResponse httpRes, string operationName, Exception ex, bool throwException = true) { try { EndpointHost.ExceptionHandler(httpReq, httpRes, ex); } catch (Exception writeErrorEx) { Log.Info("Failed to write error to response", writeErrorEx, new Dictionary <string, string>() { { "ErrorCode", "FXD300063" } }); var errorMessage = string.Format("Error occured while Processing Request: {0}", ex.Message); Log.Error(errorMessage, ex, new Dictionary <string, string>() { { "Version", ServiceUtils.SOA2VersionCatName }, { "ErrorCode", "FXD300000" }, { "Service", EndpointHost.MetadataMap[httpReq.ServicePath].FullServiceName }, { "Operation", operationName }, { "ErrorClassification", "FrameworkError" } }); if (throwException) { throw ex; } } finally { if (!httpRes.IsClosed) { httpRes.AddHeader(ServiceUtils.ResponseStatusHttpHeaderKey, AckCodeType.Failure.ToString()); } httpRes.LogRequest(httpReq); httpRes.EndRequest(true); } }
public void Init() { if (Instance != null) { throw new InvalidDataException("HttpListenerBase.Instance has already been set"); } Instance = this; var serviceManager = EndpointHost.Config.ServiceManager; if (serviceManager != null) { serviceManager.Init(); Configure(EndpointHost.Config.ServiceManager.Container); } else { Configure(null); } if (serviceManager != null) { //Required for adhoc services added in Configure() serviceManager.ReloadServiceOperations(); EndpointHost.SetOperationTypes( serviceManager.ServiceOperations, serviceManager.AllServiceOperations ); } EndpointHost.AfterInit(); var elapsed = DateTime.Now - this.startTime; Log.InfoFormat("Initializing Application took {0}ms", elapsed.TotalMilliseconds); }
protected Message ExecuteMessage(Message message, EndpointAttributes endpointAttributes, IHttpRequest httpRequest, IHttpResponse httpResponse) { var soapFeature = endpointAttributes.ToSoapFeature(); EndpointHost.Config.AssertFeatures(soapFeature); var httpReq = HttpContext.Current != null && httpRequest == null ? new HttpRequestWrapper(HttpContext.Current.Request) : httpRequest; var httpRes = HttpContext.Current != null && httpResponse == null ? new HttpResponseWrapper(HttpContext.Current.Response) : httpResponse; if (httpReq == null) { throw new ArgumentNullException("httpRequest"); } if (httpRes == null) { throw new ArgumentNullException("httpResponse"); } if (EndpointHost.ApplyPreRequestFilters(httpReq, httpRes)) { return(PrepareEmptyResponse(message, httpReq)); } var requestMsg = message ?? GetRequestMessageFromStream(httpReq.InputStream); string requestXml = GetRequestXml(requestMsg); var requestType = GetRequestType(requestMsg, requestXml); if (!EndpointHost.Metadata.CanAccess(endpointAttributes, soapFeature.ToFormat(), requestType.Name)) { throw EndpointHost.Config.UnauthorizedAccess(endpointAttributes); } try { var useXmlSerializerRequest = requestType.HasAttribute <XmlSerializerFormatAttribute>(); var request = useXmlSerializerRequest ? XmlSerializableDeserializer.Instance.Parse(requestXml, requestType) : DataContractDeserializer.Instance.Parse(requestXml, requestType); var requiresSoapMessage = request as IRequiresSoapMessage; if (requiresSoapMessage != null) { requiresSoapMessage.Message = requestMsg; } httpReq.OperationName = requestType.Name; httpReq.SetItem("SoapMessage", requestMsg); var hasRequestFilters = EndpointHost.RequestFilters.Count > 0 || FilterAttributeCache.GetRequestFilterAttributes(request.GetType()).Any(); if (hasRequestFilters && EndpointHost.ApplyRequestFilters(httpReq, httpRes, request)) { return(EmptyResponse(requestMsg, requestType)); } var response = ExecuteService(request, endpointAttributes, httpReq, httpRes); var hasResponseFilters = EndpointHost.ResponseFilters.Count > 0 || FilterAttributeCache.GetResponseFilterAttributes(response.GetType()).Any(); if (hasResponseFilters && EndpointHost.ApplyResponseFilters(httpReq, httpRes, response)) { return(EmptyResponse(requestMsg, requestType)); } var httpResult = response as IHttpResult; if (httpResult != null) { response = httpResult.Response; } var useXmlSerializerResponse = response.GetType().HasAttribute <XmlSerializerFormatAttribute>(); if (useXmlSerializerResponse) { return(requestMsg.Headers.Action == null ? Message.CreateMessage(requestMsg.Version, null, response, new XmlSerializerWrapper(response.GetType())) : Message.CreateMessage(requestMsg.Version, requestType.Name + "Response", response, new XmlSerializerWrapper(response.GetType()))); } return(requestMsg.Headers.Action == null ? Message.CreateMessage(requestMsg.Version, null, response) : Message.CreateMessage(requestMsg.Version, requestType.Name + "Response", response)); } catch (Exception ex) { throw new SerializationException("3) Error trying to deserialize requestType: " + requestType + ", xml body: " + requestXml, ex); } }
public static void EndServiceStackRequest(this IHttpResponse httpRes, bool skipHeaders = false) { httpRes.EndHttpRequest(skipHeaders: skipHeaders); EndpointHost.CompleteRequest(); }
protected static object ExecuteService(object request, EndpointAttributes endpointAttributes, IHttpRequest httpReq, IHttpResponse httpRes) { return(EndpointHost.ExecuteService(request, endpointAttributes, httpReq, httpRes)); }
protected HttpListenerBase(string serviceName, params Assembly[] assembliesWithServices) : this() { EndpointHost.ConfigureHost(this, serviceName, CreateServiceManager(assembliesWithServices)); }