-
Notifications
You must be signed in to change notification settings - Fork 0
Release Notes
Although it's been a long time between formal releases - v3.78 marks our biggest release ever! Mostly as a result of being too busy to prepare these release notes containing all the effort that have gone into the framework (and supporting libraries) in the last 6 months :)
Today we hope to rectify this neglect with a special thanks to all the contributors that helped make this release possible. We would like to pay a special thanks to Steffen Müller (@arxisos) whose code and documentation contributions and expert support in the forums and real-time help channel over these last 6 months have been invaluable.
A lot of features being announced are already well known to our active user-base as they've shipped in our production release builds for months. Hopefully these notes will highlight other useful but less known features.
We're estatic at the response we've received from the community this year which has seen our Contributor count more than doubled (now at 66 Contributors!). We've also received great response from our users which we've started keeping track of this year under @ServiceStack favourites and in the forums.
Many of these features listed below are showcased in the new Social Bootstrap API reference demo - a Backbone.js-enabled Single Page App (SPA) template, pre-configured with Twitter & Facebook login, with Bundler built-in for super-fast bundling and minification.
The above repo is kindly hosted by AppHarbor at http://bootstrapapi.apphb.com
Probably the biggest features shipped in this release is a 'clean' authentication provider model, completely detached from ASP.NET's existing membership providers exposed as clean interfaces with the following pluggable auth providers supported out-of-the-box:
Plugins.Add(new AuthFeature(
() => new CustomUserSession(), //Use your own typed Custom UserSession type
IncludeAssignRoleServices = false, //Don't register AssignRoles/UnAssignRoles services to manage users roles
new IAuthProvider[] {
new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials
new TwitterAuthProvider(appSettings), //Sign-in with Twitter
new FacebookAuthProvider(appSettings), //Sign-in with Facebook
new BasicAuthProvider(), //Sign-in with Basic Auth
new DigestAuthProvider(), //Sign-in with Digest Auth
new CustomCredentialsAuthProvider(), //Subclass CredentialsAuthProvider and access your own User/Pass repository
}));Note: Only the AuthProviders registered on the AuthFeature plugin are available at runtime.
You can add custom logic to the user Authenticaiton by overriding the OnAuthenticated() method on either the:
- Custom UserSession - which gets called after every successful Authentication/Login attempt (on any AuthProvider)
- Custom AuthProvider - which only gets called when a user authenticates with this specific provider
You can also plug-in your own Validation Hooks
- AuthService.ValidateFn - Called in the context of the AuthService, any C# exceptions are propagated to the client
- RegistrationService.ValidateFn - Called in the context of the RegistrationService, any C# exceptions are propagated to the client
- Registration Validator - Override the default Registration validator to add stricter/lax validation logic
Since the new AuthFeature and its related Session classes are pure POCOs we're able to cleanly support multiple back-end session & persistance providers:
- InMemory
- Redis (distributed)
- Memcached (distributed)
- OrmLite
- SqlServer, Sqlite, PostgreSql, MySql and Firebird RDBMS back-ends
- Redis
- InMemory (for testing)
The Auth POCOs can hold any number of Roles and Permissions per user.
Which can be used to protect your services by adding the attributes below onto your Service or Request DTOs:
[RequiredRole(roleNames)]
[RequiredPermission(permissionNames)]
These attributes can also be used on MVC Controllers as part of the ServiceStack.Mvc NuGet pacakage and is explained in the MVC PowerPack.
These permissions can be managed with the AssignRoles/UnAssignRoles services registered as part of the AuthFeature plugin. Only users with the Admin role can access these services.
More info about autentication can be found in the wiki documentation.
When you enable the ValidationFeature() plugin you can create a validator for every request DTO you have, with smart, terse fluent syntax that can handle most use-cases, e.g:
public class UserValidator : UserValidator<ModelToValidate> {
public UserValidator() {
//Validation rules for all requests
RuleFor(r => r.Name).NotEmpty();
RuleFor(r => r.Age).GreaterThan(0);
//Only apply this validation logic to POST and PUT requests
RuleSet(ApplyTo.Post | ApplyTo.Put, () => {
RuleFor(r => r.Count).GreaterThan(10);
});
}
}This fluent syntax is provided to you by an integrated version of JeremySkinner's excellent FluentValidation library.
More info about validation can be found in the wiki documentation.
Request/Response filters (modelled after MVC Action filters) are a great way to share common logic between services which you can easily add by marking your service class or Request/Response DTOs with a Request or Response Filter Attribute. The RequiredRole and RequiredPermission attributes good examples of functionality that's best captured in Filter attributes. Here's a simple example of how to create one:
public class LogFilterAttribute : RequestFilterAttribute {
public IStatsLogger StatsLogger { get; set; } // Injected by IOC
public LogFilterAttribute(){
//Priorities <0 are executed before global filters, filters with priorities >= are executed after (in order)
base.Priority = 10;
}
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto) {
//This code is executed before the service
StatsLogger.SaveUserAgent(req.UserAgent);
}
}That's it! No registration is needed as they're auto-discovered so you can start adding them on services you want to log.
More info about request and response filter attributes can be found in the wiki documentation.
As of v3.55 all ServiceStack's add-ons now implement the following Plugin API:
public interface IPlugin {
void Register(IAppHost appHost);
}ServiceStack's CSV Format:
Plugins.Add(new CsvFormat());
ServiceStack's auto generated HTML5 JSON Report Format:
Plugins.Add(new HtmlFormat());
Plugins.Add(new MarkdownFormat());
More info about Razor Markdown: Intro, Features, Docs Website
You can prevent a default plug-in from being added by removing it from a list, e.g: removing the CSV Format:
Plugins.RemoveAll(x => x is CsvFormat);
Likewise you can access a plug-in just as easy, should you want to modify their existing attriutes, e.g:
var htmlFormat = (HtmlFormat)base.Plugins.First(x => x is HtmlFormat);
Enable ServiceStack's Fluent Validation:
Plugins.Add(new ValidationFeature());
Enable ServiceStack's built-in Authentication (displayed above in full):
Plugins.Add(new AuthFeature(....));
The AuthFeature above already enables the SessionFeature, but if you want to make use of sessions and don't want to enable the built-in Authentication, you will need to register it manually with:
Plugins.Add(new SessionFeature());
The Registration feature enables the Registration Service and allows users to register at the default route /register:
Plugins.Add(new RegistrationFeature());
Adding the ProtoBuf Format NuGet package automatically adds the ProtoBufFormat plug-in:
Plugins.Add(new ProtoBufFormat());
Add an In-Memory IRequestLogger and service with the default route at /requestlogs which maintains a live log of the most recent requests (and their responses). Supports multiple config options incl. Rolling-size capacity, error and session tracking, hidden request bodies for sensitive services, etc.
Plugins.Add(new RequestLogsFeature());
The IRequestLogger is a great way to introspect and analyze your service requests in real-time. Here's a screenshot from the http://bootstrapapi.apphb.com website:
It supports multiple queryString filters and switches so you filter out related requests for better analysis and debuggability:
The RequestLogsService is just a simple C# service under-the-hood but is a good example of how a little bit of code can provide a lot of value in ServiceStack's by leveraging its generic, built-in features.
ServiceStack's typed, message-first design is ideal for coarse-grained out-of-proc communication. Although HTTP is our primary endpoint, through our clean IMessageService interface we also provide a number of alternate hosts that are able to re-use your existing services made available on different hosts.
In many ways MQ's are underrated technology in .NET, but they can provide superior conduit to connect your internal services, especially for async/one-way, idempotent messages. They can offer reliabile and durable messaging, better scalability and natural load-balancing, as well as time-decoupled and disconnected operation between loosely-coupled endpoints.
New hosts can be easily added by implementing the IMessageService interface which is something we plan on doing in the near future. As future hosts will be able to bind to your existing services, you'll be able to easily make use of them when they're ready.
There have been lots of other smaller features and fixes added during the time between releases (too many to add here). Although you can check our commit logs if you're interested in the finer details of what we've been up to :)
For those interested in our future road-map we hope to ship the following features for our next-release:
As part of his excellent contributions @arxisos has been maintaining an async branch that has ServiceStack running on IHttpAsyncHandler and already has a functional alpha build available for you to try at: ServiceStack-v4.00-alpha.zip
With this change ServiceStack supports Task<> as a return type on services. You only need to register the Task<> plugin. To see a full example look at this integration test.
The only way we can support the different layouts and customizations users want to apply to the auto-generated metadata pages is to have them completely customizable and hot-swappable. So that's our plan for the next iteration of the metadata pages - a rewrite into a self-contained, swappable static HTML/Ajax pages. We'll attempt to provide as much info in our json metadata services we can so others are able to create an executable REST API/UI from them - i.e. making it possible to integrate 3rd party OSS REST API clients like Swagger or Apigee.
As soon as Async has been integrated into ServiceStack core, it will lay the foundation for our work on a fast IPC/RPC bridge between ServiceStack services and external C#/.NET and node.js/Dart processes.
As ServiceStack's message-based design influences the development of coarse-grained (i.e. non-chatty) services it provides the perfect interface for efficient out-of-process communications. We plan to get an optimal implementation by employing an async/non-blocking design, invoking services directly (by-passing the overhead of the HTTP Stack/Context) and using our fast JSON Serializer in .NET and the native JSON parsers in node.js/Dart.
Although our motivations to build a bridge to external C#/.NET processes will be well-understood by our .NET-strong user-base, why we'd want to provide a good story for Dart and node.js platforms will be less clear...
In many ways dynamic languages offer greater productivity, flexibility, iteration time advantages over static languages (i.e. C#/.NET) for web development. E.g: Node.js (Server-Side V8/JavaScript) has superior web tooling (with native implementations for all popular web DSLs and minifiers - and why we've adopted it for Bundler), a large and thriving OSS ecosystem, excellent libraries and frameworks making it the 1st-choice platform for many pro-web developers and Start-Ups.
Whilst Dart is the new dynamic structured-language under heavy development by some of the brightest language minds at Google including: Lars Bak, Kasper Lund, Vyacheslav Egorov & Mads Ager (original V8 team), Jim Hugunin (Jython/IronPython/DLR), Joshua Bloch (Java APIs), Gilad Bracha (JLS/JVM/NewSpeak), and many others.
It sports many unique features well suited for the development of complex web apps:
- Optional-typing - Providing dynamic-lang-like productivity & structure
- Snapshotting - For instant-startup times
- Interface/default classes + factories - Encourages binding to interfaces (all core-libs) / eliminate IOCs
- Method missing - For creating terse, dynamic APIs + proxies
- Isolates - Shared-nothing concurrency and secured hosting of 3rd Party code
- String interpolation - For effortless construction of strings
- Large core lib - Rich client & server-side libraries with a consistent & terse DOM API
Although the first version is not yet released it already ships with great tooling (for OSX/Win/Linux) including a smart, lightweight IDE and a built-in VM/Debugger in Dartium (a custom build of Chrome).
Both Node.js and Dart offer full-webstack programming (same language used on client/server), faster compile and iteration times, less friction and a more lax type-system - ideal for web development. Node.js and Dart's async/evented architecture also makes it a great choice for web socket servers and highly interactive sites.
We still believe statically-typed languages offer a better value proposition for developing and maintaining web services and is still in many ways a better choice for any CPU-intensive, Heavy Data/Binary processing tasks as well as accessing native/unmanaged APIs.
With that said we feel there's a lot of value in developing a great story to efficiently communicate between ServiceStack and node.js/Dart processes which we hope offers the best of both worlds for other like-minded polygots.
Although as ServiceStack has already developed .NET's fastest JSON serializer and .NET's leading C# Redis Client (and Dart Redis Client :) - We already have a great comms story via Redis available today - but we hope to make it even better by communicating directly between .NET/node.js/Dart processes (i.e. by-passing redis).
ServiceStack already has existing HTML Support, but we hope to increase it even further by integrating the best thing we like about MVC (i.e. Razor :) so we have even less reasons for wanting to host ServiceStack with ASP.NET MVC :)
Integration with NancyFx
Nancy is another excellent OSS (ASP.NET MVC Replacement) Web Framework for .NET, that offers a simple, clean and terse programming model for websites (just the kind we like :). We hope to provide a good Social Bootstrap API-like template but replaced with a NancyFx host instead.
##ServiceStack 3.09 Release Notes
Now in ServiceStack is StackOverflow's own benchmark leading Micro ORM Dapper. This means a fresh NuGet install of ServiceStack now includes the 2 fastest Micro ORMS for .NET! :)
OrmLite and Dapper are very similar in design in that they're simply useful extension methods on ADO.NET's System.Data.* interfaces, the difference being Dapper has extension methods of IDbConnection whilst OrmLite methods hangs off the lower IDbCommand. And because they both make use of 'clean POCOs' - they can be used interchangibly together on the same DB connection. This also allows them to both make use of OrmLiteConnectionFactory to configure connection manager over your DB ConnectionString.
We've made ServiceStack's HTML5 JSON Report Format even better by now including the excellent Mvc Mini Profiler - by @jarrod_dixon and @samsaffron. It's the same profiler used to profile and help speed up sites like Stack Overflow and more recently the much faster NuGet v2.0 website.
As the MVC Mini Profiler is optimized for a .NET 4.0 MVC app, we've made some changes in order to integrate it into ServiceStack:
- Make it work in .NET 3.0 by backporting .NET 4.0 classes into ServiceStack.Net30 namespace (Special thanks to OSS! :)
- Using Mono's ConcurrentDictionary classes
- Using Lokad.com's Tuples
- Switched to using ServiceStack's much faster Json Serializer
- Reduced the overall footprint by replacing the use of jQuery and jQuery.tmpl with a much smaller jquip (jQuery-in-parts) dependency.
- Moved to the ServiceStack.MiniProfiler namespace and renamed to Profiler to avoid clashing with another Mvc Mini Profiler in the same project
As a side-effect of integrating the Mvc Mini Profiler all ServiceStack .NET 3.0 projects can make use of .NET 4.0's ConcurrentDictionary and Tuple support, hassle free!
Just like the Normal Mvc Mini Profiler you can enable it by starting it in your Global.asax, here's how to enable it for local requests:
protected void Application_BeginRequest(object src, EventArgs e)
{
if (Request.IsLocal)
Profiler.Start();
}
protected void Application_EndRequest(object src, EventArgs e)
{
Profiler.Stop();
}
That's it! Now everytime you view a web service in your browser (locally) you'll see a profiler view of your service broken down in different stages:
By default you get to see how long it took ServiceStack to de-serialize your request, run any Request / Response Filters and more importantly how long it took to Execute your service.
The profiler includes special support for SQL Profiling that can easily be enabled for OrmLite and Dapper by getting it to use a Profiled Connection using a ConnectionFilter:
this.Container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(
"~/App_Data/db.sqlite".MapHostAbsolutePath(),
SqliteOrmLiteDialectProvider.Instance) {
ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
});
Refer to the Main MVC MiniProfiler home page for instructions on how to configure profiling for Linq2Sql and EntityFramework.
It's also trivial to add custom steps enabling even finer-grained profiling for your services. Here's a simple web service DB example returning a list of Movies using both a simple DB query and a dreaded N+1 query.
public class MiniProfiler
{
public string Type { get; set; }
}
public class MiniProfilerService : ServiceBase<MiniProfiler>
{
public IDbConnectionFactory DbFactory { get; set; }
protected override object Run(MiniProfiler request)
{
var profiler = Profiler.Current;
using (var dbConn = DbFactory.OpenDbConnection())
using (var dbCmd = dbConn.CreateCommand())
using (profiler.Step("MiniProfiler Service"))
{
if (request.Type == "n1")
{
using (profiler.Step("N + 1 query"))
{
var results = new List<Movie>();
foreach (var movie in dbCmd.Select<Movie>())
{
results.Add(dbCmd.QueryById<Movie>(movie.Id));
}
return results;
}
}
using (profiler.Step("Simple Select all"))
{
return dbCmd.Select<Movie>();
}
}
}
}
Calling the above service normally provides the following Profiler output:
Whilst calling the service with the n1 param yields the following warning:
In both cases you see the actual SQL statements performed by clicking the SQL link. The N+1 query provides shows the following:
Notice the special attention the MVC MiniProfiler team put into identifying Duplicate queries - Thanks Guys!
- Using Nuget to add ServiceStack to an existing ASP.NET or MVC application
- Download ServiceStack.Examples projects and Starter Templates
- Download just the ServiceStack.dlls binaries
- Other ServiceStack projects available on NuGet
.
Follow @demisbellot and @ServiceStack for twitter updates
##ServiceStack 2.28 Release Notes
This release includes a few enhancements and catches up on all the pull requests and most of the issues that were submitted since the last release.
ServiceStack now hosts and tracks its new issues and feature requests on a live public Trello dash board where anyone is welcome to add to, or simply check the progress of their features/issues in the work queue.
We now have a special contributor page and section on the main project page showing the many contributors to ServiceStack's projects over the years. We hope we haven't missed anyone out - please send us a pull request if you would like to be added.
###The major features in this release include:
A redis-based message queue client/server that can be hosted in any .NET or ASP.NET application. The RedisMqHost lives in the ServiceStack.Redis project and brings the many benefits of using a Message Queue. The current unoptimized version uses only a single background thread although initial benchmarks shows it can send/receive a promising 4.6k messages /sec when accessing a local redis instance (on my dev workstation).
Major kudos goes to Redis which thanks to its versatility, has Pub/Sub and Lists primitives that makes implementing a Queue trivial.
The first version already sports the major features you've come to expect from a MQ:
- Each service maintains its own Standard and Priority MQ's
- Automatic Retries on messages generating errors with Failed messages sent to a DLQ (Dead Letter Queue) when its Retry threshold is reached.
- Each message can have a ReplyTo pointing to any Queue, alternatively you can even provide a ServiceStack endpoint URL which will send the response to a Web Service instead. If the web service is not available it falls back into publishing it in the default Response Queue so you never lose a message!
- MQ/Web Services that don't return any output have their Request DTOs sent to a rolling Out queue which can be monitored by external services (i.e. the publisher/callee) to determine when the request has been processed.
Although you can host RedisMqHost in any ASP.NET web app, the benefit of hosting inside ServiceStack is that your web services are already capaable of processing Redis MQ messages without any changes required since they're already effectively designed to work like a Message service to begin with, i.e. C# POCO-in -> C# POCO-out.
This is another example of ServiceStack's prescribed DTO-first architecture continues to pay dividends since each web service is a DI clean-room allowing your C# logic to be kept pure as it only has to deal with untainted POCO DTOs, allowing your same web service to be re-used in: SOAP, REST (JSON,XML,JSV,CSV,HTML) web services, view models for dynamic HTML pages and now as a MQ service!
Eventually (based on feedback) there will be posts/documentation/examples forthcoming covering how to use it, in the meantime you can Check out the Messaging API to see how simple it is to use. To see some some working code showing some of the capabilities listed above, view the tests.
Hooking up a basic send/reply example is as easy as:
//DTO messages:
public class Hello { public string Name { get; set; } }
public class HelloResponse { public string Result { get; set; } }
var redisFactory = new PooledRedisClientManager("localhost:6379");
var mqHost = new RedisMqHost(redisFactory, noOfRetries:2, null);
//Server - MQ Service Impl:
mqHost.RegisterHandler<Hello>(m =>
new HelloResponse { Result = "Hello, " + m.GetBody().Name });
mqHost.Start();
...
//Client - Process Response:
mqHost.RegisterHandler<HelloResponse>(m => {
Consle.Log("Received: " + m.GetBody().Result);
});
mqHost.Start();
...
//Producer - Start publishing messages:
var mqClient = mqHost.CreateMessageQueueClient();
mqClient.Publish(new Hello { Name = "ServiceStack" });
We're happy to report the most requested feature for ServiceStack's JSON/JSV serializers is now available at: ServiceStack.Text v2.28.
The JSON and JSV Text serializers now support serializing and deserializing DTOs with Interface / Abstract or object types. Amongst other things, this allows you to have an IInterface property which when serialized will include its concrete type information in a __type property field (similar to other JSON serializers) which when serialized populates an instance of that concrete type (provided it exists).
Likewise you can also have polymorhic lists e.g. of a base Animal type and be populated with a Cats and Dogs which should now deserialize correctly.
As always performance was a primary objective when adding this feature and as a result we should have a very peformant implementation of it.
Note: This feature is automatically added to all Abstract/Interface/Object types, i.e. you don't need to include any
[KnownType] attributes to take advantage of it.
- Added JSON/JSV custom serialization behaviour injection of BCL value types in e.g: JsConfig
- Serialization errors now return 400 status code
- Add option to propagate errors instead of being sent in the response Tymek Majewski
- Added UserAgent to IHttpRequest type
- Add useful overloads to HttpResult class
- SetPermantentCookie/SetSessionCookie/SetCookie
- LastModified
- Fix compression bug in
RequestContext.ToOptimizedResult() - byte[] responses are written directly to the response stream with the ContentType: application/octet-stream
##ServiceStack 2.20 Release Notes
The biggest feature in this release is the new Markdown support built-into ServiceStack and more specifically its Markdown Razor View Engine. Markdown Razor is an MVC Razor-inspired templating engine that allows you to generate dynamic Markdown and HTML using plain Markdown and Razor Sytnax.
View the new Markdown Razor Introduction for more information.
The first website to take advantage of the new Markdown templating support in ServiceStack is http://www.servicestack.net/docs which is effectively built entirely using ServiceStack's GitHub project Markdown wiki and README.md pages. To render the entire website the transformed Markdown content is merged with a static default.shtml website template.
A nice feature of a Markdown-enabled website is that since the Content is decoupled from the website template we are easily able to enhance the site using Ajax to load partial content page loads. This provides a faster browsing experience since the entire webpage doesn't have to be reloaded.
See the About ServiceStack Docs Website for more information.
Support was added to the Generic JSON and JSV ServiceStack C# Clients to work around MonoTouch's No-JIT Restrictions. Unfortunately to do this we've had to create a new MonoTouch Build configuration which doesn't use any C# Expressions or Reflection.Emit. So you need to download the MonoTouch ServiceStack builds for running in MonoTouch. Download MonoTouch-v2.20.zip
An example MonoTouch project that uses these Sync and Async C# ServiceClients to talk to the RestFiles web services is in the RestFilesClient Example project.
- Added support for IContainerAdapter to let you plug-in and use different IOC Containers
- Allow alternate strategies for resolving Service Types
- If your IService implements IDisposable, it will be disposed straight after it's been executed.
- New users should download ServiceStack.Examples - v2.20
- Existing users can download just the ServiceStack.dlls - v2.20
.
Follow @demisbellot and @ServiceStack for twitter updates
#ServiceStack 2.09 Release Notes
As we have received a number of requests to provide NuGet packages for ServiceStack and its components, we're now happy to say we're now NuGet compliant! Where a configured and working ServiceStack web framework is just 1 NuGet command away :)
This will add the ServiceStack dlls to your standard VS.NET ASP.NET Web Application, Register ServiceStack handler in your Web.Config, configure your AppHost and create both a Hello and a fully-operational TODO REST service.
Together with just 2 static content files (default.htm and jqunback-1.51.js) you get a fully configured and working REST-ful application (which as an aside benefit we hope encourages .NET developers into the beautiful world of Backbone.js and Single Page Ajax Applications).
The NuGet package of ServiceStack is essentially the RootPath Starter Template. The other starting templates, e.g. Windows Service, Console Hosts, hosting ServiceStack at custom /api paths are still available in the ServiceStack.Examples downloads.
Check ServiceStack's NuGet page for the full description of the available ServiceStack packages on NuGet.org
Although this normally shouldn't warrant a release line item, for the technology focused - it's actually hard work :) We believe the overview slides provide the best starting point for new developers looking to find out the benefits of ServiceStack and how they can easily develop REST services with it. Today, we're releasing the following 2 slides:
In your AppHost Configure() script you can register paths against your Request DTOs with the Routes property like so:
Routes
.Add<Hello>("/hello")
.Add<Hello>("/hello/{Name*}")
.Add<Todo>("/todos")
.Add<Todo>("/todos/{Id}");
This is an alternative to the [RestService("/hello")] attribute which was previously required on your Request DTOs.
They should work as expected, where any match will route that request to the designated service. All variables enclosed with {Id} will be populated on the selected Request DTO with that value of the path component.
Routes.Add<Hello>("/hello/{Name*}") is a special case that matches every path beginning with /hello/ where the Hello Request DTOs Name property is populated with the contents of the remaining url path. E.g. /hello/any/path/here will be populated in Hello.{Name} property.
Sometimes the ServiceStack default of having all endpoints and formats all wired up correctly without any configuration is actually not preferred (we know, enterprises right? :), so in this release we've made it easy to turn on and off system-wide features using simple enum flags. To simplify configuration we also added some useful Enum extensions (Has,Is,Add,Remove) to make it easier to signal your intent with Enums.
E.g. this is how you would disable 'JSV' and 'SOAP 1.1 & 1.2' endpoints:
var disableFeatures = Feature.Jsv | Feature.Soap;
SetConfig(new EndpointHostConfig
{
EnableFeatures = Feature.All.Remove(disableFeatures),
});
##ServiceStack 2.08 - ServiceStack meets Backbone.js
Unlike in previous releases, the ServiceStack framework itself has largely remained unchanged. This update is focused towards including Backbone.js into ServiceStack.Examples project.
Backbone.js is a beautifully-designed and elegant light-weight JavaScript framework that allows you to build you're ajax applications separated into Views and Models connected via key-value data-binding and declarative custom event handling. Of special interest to us is its ability to supply a url and have it automatically connect your Models with your Backend REST services, which we're happy to report works well with ServiceStack's JSON services.
From the author of the popular and game-changing libraries CoffeeScript and Underscore.js - Backbone.js differentiates itself from other javascript frameworks in that it promotes a clean separation of concerns and a modular application design, which is hard to achieve with other frameworks that couple themselves too tightly with the DOM.
Our first action was porting Backbone's example TODO app and replace its HTML5 localStorage backend with a ServiceStack REST + Redis one. This was quite easy to do and we were happy that resulting C# server code for the REST backend ended up weighing in at less than the size of VS.NET's default Web.config file :)
Like the rest of our examples a live demo is available.
As the Backbone TODO app represented a small, but working REST client and server we decided to make it the default app in all of ServiceStack's Starter Templates.
That's right, your Starting template for your Enterprise Windows Service now comes with a useful TODO app out-of-the-box! We rightfully believe this makes it the coolest app provided in any starting project template :)
At this point it's a good time to re-iterate that ServiceStack was designed from the start to be a first-class Ajax server that provides best support for HTML5 Ajax/SPA apps, purely because we believe it to be the future application delivery platform that provides the broadest reach and best user experience possible. We've made special efforts to provide the fastest JSON web services possible for .NET, with a first-class redis client and a strong caching story important in developing high-performance web services and a responsive end user experience.
This release was focused on finding the perfect Web.Config that best allows ServiceStack to work consistently everywhere across all ASP.NET and HttpListener hosts on both .NET and MONO platforms. A primary goal of ServiceStack is to be able to build web services once and use the same binaries and App .config files to run everywhere in every ASP.NET or HttpListener host on Windows with .NET or on OSX/Linux with MONO.
Since your services are POCO message-based and only need to be implement an IService<TRequest> interface your services effectively operate in a clean-room DDD Service, and have a potential for re-use in a variety of other hosts, i.e. Message Queues, Windows services, Windows applications, etc.
Although the promise of the .NET architecture allows for pure C# applications to run on every .NET platform, the ASP.NET hosts don't always share the same compatibility levels as there are subtle differences in implementation and behaviour amongst the various ASP.NET hosts.
The only real way of ensuring ServiceStack runs well in each environment is to actually setup an environment on each host with each configuration we want to support. Unfortunately this time-consuming process is a necessary one in order to limit any new regressions from being introduced as a result of added features.
So with that in mind, included in this release is the 'StartTemplates' solution providing the same Hello World Web service hosted in every supported mode and configurations. There are now 2 supported modes in which to run ServiceStack:
b) Use ServiceStack with an existing Web Framework - Host web services at a user-defined: /custompath
The new StarterTemplates in the ServiceStack.Examples GitHub project provide a good starting template for each supported configuration below:
- .NET 3.5 and .NET 4.0 - ASP.NET Custom Path: /api
- .NET 3.5 and .NET 4.0 - ASP.NET Root Path: /
- Windows Service w/ HttpListener
- Stand alone Console App Host w/ HttpListener
We're happy to report the above configurations are well supported on Windows with .NET visible by the Latest Windows Integration Test Reports showing ServiceStack running correctly on IIS 3.5,4.0/WebDev Server 2.0,4.0/Windows Service/Console Application hosts.
To deploy on MONO you can just XCOPY/SFTP the files across as-is (i.e. as compiled with VS.NET) to your Linux or OSX server. In most of the scenarios it works as-is however the integration tests have uncovered a couple of known issues visible in the Latest Linux Integration Test Reports.
- Depending on your setup a url with a trailing path '/' will cause Nginx/FastCGI or Apache/mod_mono to request a /default.aspx which if it doesn't exist will return a 404
- If you want to use a custom path i.e. /api your ASP.NET virtual path also needs to start with your httpHandler path. Which is why an ASP.NET application hosted on /ApiPath35/api works as expected whilst one at /CustomPath35/api does not.
ServiceStack.NET now running example projects on both Nginx/FastCGI and Apache/mod_mono on the same server
With a few linux admin tweaks to add and assign a new virtual network interface with a new IP Address, we're easily able to run both Nginx/FastCGI and Apache/mod_mono HTTP servers on the same server, both configured to point to ServiceStack ASP.NET GitHub Example Projects.
http://www.servicestack.net is running Nginx/FastCGI configuration while the sub domain http://api.servicestack.net is running Apache/mod_mono (the recommended MONO ASP.NET configuration).
Here are links to ServiceStack.Example projects on both Nginx and Apache:
- Nginx - Apache /ServiceStack.Hello
- Nginx - Apache /RestFiles/
- Nginx - Apache /RedisStackOverflow/
- Nginx - Apache /RedisStackOverflow/
- Nginx - Apache /ServiceStack.MovieRest/
- Nginx - Apache /ServiceStack.Northwind/
We plan to create more wiki pages walking through how to setup your own ASP.NET web applications on Linux with MONO.
If you have a preference on what hosting environment you would like to see ServiceStack running in (e.g. AppHarbor, Moncai, Amazon, Azure, SuseStudio, etc), we'd love to hear from you, please post your preference to ServiceStack's Google Group
The ServiceStack code-base has gone under a re-structure to better support user contributions, testing, fine-grained deployments allowing hosting of ServiceStack in 32 and 64 bit servers, in medium or full trust hosting environments.
The changes from a high-level are:
- No more ILMERGE.exe dlls, all ServiceStack .dlls now map 1:1 with a project of the same name
- As a result all .pdb's for all assemblies are now included in each release to help debugging (this was lost using ILMERGE)
- When not using OrmLite/Sqlite, ServiceStack is a full .NET managed assembly with no P/Invokes that can run in 32/64 bit hosts
- All projects upgraded to VS.NET 2010 (min baseline is still .NET 3.5)
- Non-core, high-level functionality has been moved into a new ServiceStack.Contrib
A lot of effort was made to ensure that clients would not be affected i.e. no code-changes should be required.
As a result of the change to the deployment dlls where previously ServiceStack.dll was an ILMERGED combination of every implementation dll in ServiceStack. You will now need to explicitly reference each dll that you need.
To help visualize the dependencies between the various components, here is a tree showing which dependencies each project has:
In the interest of promoting contributions and modifications from the community, the non-core projects of ServiceStack has been extracted into a new user contributed ServiceStack.Contrib project site at:
https://github.com/ServiceStack/ServiceStack.Contrib
I invite all ServiceStack users who want to share their generic high-level functionality and useful app-specific classes under this project where the rest of the community can benefit from.
The biggest feature added in this release is likely the new HTML5 report format that generates a human-readable HTML view of your web services response when viewing it in a web browser. Good news is, like the ServiceStack-CSV-Format it works with your existing webservices as-is, with no configuration or code-changes required.
Here are some results of web services created before the newer HTML5 and CSV formats existed:
- RedisStackOverflow Latest Questions
- RestMovies All Movie listings
- RestFiles Root Directory
Use the ?format=[json|xml|html|csv|jsv] to toggle and view the same webservice in different formats.
In order to be able to better demonstrate features with a 'real-world' DataSet, a new ServiceStack.Northwind project has been added which inspects the Northwind dataset from an SQLite database. A live demo is hosted at http://servicestack.net/ServiceStack.Northwind/. Here are some links below to better demonstrate the new HTML format with a real-world dataset:
ServiceStack has always had its own (i.e. ASP.NET implementation-free) good support for caching, though like most un-documented features it is rarely used. The caching has been improved in this version to now support caching of user-defined formats as well. Here is example usage from the new Northwind project:
public class CachedCustomersService : RestServiceBase<CachedCustomers>
{
public ICacheClient CacheClient { get; set; }
public override object OnGet(CachedCustomers request)
{
return base.RequestContext.ToOptimizedResultUsingCache(
this.CacheClient, "urn:customers", () => {
var service = base.ResolveService<CustomersService>();
return (CustomersResponse) service.Get(new Customers());
});
}
}
The above code caches the most optimal output based on browser capabilities, i.e. if your browser supports deflate compression (as most do), a deflated, serialized output is cached and written directly on the response stream for subsequent calls. Only if no cache exists will the web service implementation (e.g lambda) be executed, which populates the cache before returning the response.
To see the difference caching provides, here are cached equivalents of the above REST web service calls:
The underlying IHttpRequest (an adapter interface over ASP.NET/HttpListener HTTP Requests) can now be retrieved within your webservice to be able to query the different HTTP Request properties:
var httpReq = base.RequestContext.Get<IHttpRequest>();
Also added is the ability to resolve existing web services (already auto-wired by the IOC) so you can re-use existing web service logic. Here is an example of usage from the Northwind CustomerDetailsService.cs.
var ordersService = base.ResolveService<OrdersService>();
var ordersResponse = (OrdersResponse)ordersService.Get(new Orders { CustomerId = customer.Id });
- Enhanced REST functionality and access, now more succinct than ever
- Uploading of files to ServiceStack web services using HTTP POST multipart/form-data
- More robust error handling support handling C# exceptions over REST services
- For examples of on how to use the C# REST client API check out the tests in the new REST Files project:
New RestFiles project added to ServiceStack.Examples GitHub project:
Live demo available at: servicestack.net/RestFiles/
- Provides a complete remote file system management over a REST-ful api
- The complete REST-ful /files web service implementation is only 1 C# page class
- Includes a pure ajax client to provide a GitHub-like file browsing experience, written in only 1 static HTML page, using only jQuery
- C# integration test examples are also included showing how to access this REST-ful api over sync and async C# clients
Read the rest of the Rest Files README.md for a more detailed overview about the project.
-
Added more tests and fixed bugs in ServiceStack's new CSV format and Request/Response filters
-
Added new information on the generated web service index, individual web service page now include:
- REST paths (if any are defined) thanks to @jakescott
- Included directions to consumers on how to override the HTTP Accept header and specify the format
- Now including any System.CompontentModel.Description meta information attributed on your Request DTO
- Preview the new documentation pages on ServiceStack Hello and Movies example web service pages.
-
Added tests to show how to implement Basic Authentication using the new RequestFilters
-
Changed the httpHandler paths in the Example projects and created a new Config class to store which supported mappings go with which web servers + middleware.
-
Provide a way to register new urls for different ServiceStack handler mappings used, e.g. to register IIS 6.0 urls:
SetConfig(new EndpointConfig { ServiceEndpointsMetadataConfig = ServiceEndpointsMetadataConfig.GetForIis6ServiceStackAshx() });
This release was focused to opening up ServiceStack to better support adding more hooks and extension points where new formats can be added. The CSV format was also added to test these new extension APIs.
- Added support for the CSV format
- Enhanced the IContentTypeFilter API to add support for different serialization formats
- Added Request and Response filters so custom code can inspect and modify the incoming IHttpRequest or IHttpResponse.
- Added
Request.Itemsso you can share arbitrary data between your filters and web services. - Added
Request.Cookiesfor reading cookies (to avoid retrieving it from HttpRuntime.Current) - Removed the preceding UTF8 BOM character to ServiceStack's JSON and JSV Serializers.
- All features above are available on both ASP.NET and HttpListener hosts
Using the same tech that makes ServiceStack's JSV and JSON serializers so fast (i.e. no run-time reflection, static delegate caching, etc), should make it the fastest POCO CSV Serializer available for .NET.
The 'CSV' format is the first format added using the new extensions API, which only took the following lines of code:
//Register the 'text/csv' content-type and serializers (format is inferred from the last part of the content-type)
this.ContentTypeFilters.Register(ContentType.Csv,
CsvSerializer.SerializeToStream, CsvSerializer.DeserializeFromStream);
//Add a response filter to add a 'Content-Disposition' header so browsers treat it as a native .csv file
this.ResponseFilters.Add((req, res, dto) =>
{
if (req.ResponseContentType == ContentType.Csv)
{
res.AddHeader(HttpHeaders.ContentDisposition,
string.Format("attachment;filename={0}.csv", req.OperationName));
}
});
With only the code above, the 'CSV' format is now a first-class supported format which means all your existing web services can take advantage of the new format without any config or code changes. Just drop the latest ServiceStack.dlls (v1.77+) and you're good to go!
Note: there are some limitations on the CSV format and implementation which you can read about on the ServiceStack CSV Format page.
The Request filter takes a IHttpRequest, IHttpResponse and the Request DTO: List<Action<IHttpRequest, IHttpResponse, object>> RequestFilters { get; }
The Response filter takes a IHttpRequest, IHttpResponse and the Response DTO: List<Action<IHttpRequest, IHttpResponse, object>> ResponseFilters{ get; }
Note: both sets of filters are called before there any output is written to the response stream so you can happily use the filters to authorize and redirect the request. Calling IHttpResponse.Close() will close the response stream and stop any further processing of this request.
Feel free to discuss or find more about any of these features at the Service Stack Google Group
- Why ServiceStack?
- What is a message based web service?
- Advantages of message based web services
- Why remote services should use separate DTOs
- Getting Started
- Reference
- Clients
- Formats
- View Engines 4. Razor & Markdown Razor
- Hosts
- Security
- Advanced
- Configuration options
- Access HTTP specific features in services
- Logging
- Serialization/deserialization
- Request/response filters
- Filter attributes
- Concurrency Model
- Built-in caching options
- Built-in profiling
- Form Hijacking Prevention
- Auto-Mapping
- HTTP Utils
- Virtual File System
- Config API
- Physical Project Structure
- Modularizing Services
- MVC Integration
- Plugins 3. Request logger 4. Swagger API
- Tests
- Other Languages
- Use Cases
- Performance
- How To
- Future










