Add ServiceStack Reference

Demis Bellot edited this page Oct 25, 2016 · 35 revisions

  1. Getting Started

    1. Creating your first project
      1. Create Service from scratch
    2. Your first webservice explained
    3. Example Projects Overview
    4. Learning Resources
  2. Designing APIs

    1. ServiceStack API Design
    2. Designing a REST-ful service with ServiceStack
      1. Simple Customer REST Example
    3. How to design a Message-Based API
    4. Software complexity and role of DTOs
  3. Reference

    1. Order of Operations
    2. The IoC container
    3. Configuration and AppSettings
    4. Metadata page
    5. Rest, SOAP & default endpoints
    6. SOAP support
    7. Routing
    8. Service return types
    9. Customize HTTP Responses
    10. Customize JSON Responses
    11. Plugins
    12. Validation
    13. Error Handling
    14. Security
    15. Debugging
    16. JavaScript Client Library (ss-utils.js)
  4. Clients

    1. Overview
    2. C#/.NET client
      1. .NET Core Clients
    3. Add ServiceStack Reference
      1. C# Add Reference
      2. F# Add Reference
      3. VB.NET Add Reference
      4. Swift Add Reference
      5. Java Add Reference
    4. Silverlight client
    5. JavaScript client
      1. Add TypeScript Reference
    6. Dart Client
    7. MQ Clients
  5. Formats

    1. Overview
    2. JSON/JSV and XML
    3. HTML5 Report Format
    4. CSV Format
    5. MessagePack Format
    6. ProtoBuf Format
  6. View Engines

    1. Razor & Markdown Razor
    2. Markdown Razor
  7. Hosts

    1. IIS
    2. Self-hosting
    3. Messaging
    4. Mono
  8. Security

    1. Authentication
    2. Sessions
    3. Restricting Services
    4. Encrypted Messaging
  9. Advanced

    1. Configuration options
    2. Access HTTP specific features in services
    3. Logging
    4. Serialization/deserialization
    5. Request/response filters
    6. Filter attributes
    7. Concurrency Model
    8. Built-in profiling
    9. Form Hijacking Prevention
    10. Auto-Mapping
    11. HTTP Utils
    12. Dump Utils
    13. Virtual File System
    14. Config API
    15. Physical Project Structure
    16. Modularizing Services
    17. MVC Integration
    18. ServiceStack Integration
    19. Embedded Native Desktop Apps
    20. Auto Batched Requests
    21. Versioning
    22. Multitenancy
  10. Caching

    1. Caching Providers
    2. HTTP Caching
      1. CacheResponse Attribute
      2. Cache Aware Clients
  11. Auto Query

    1. Overview
    2. Why Not OData
    3. AutoQuery RDBMS
    4. AutoQuery Data
      1. AutoQuery Memory
      2. AutoQuery Service
      3. AutoQuery DynamoDB
  12. Server Events

    1. Overview
    2. JavaScript Client
    3. C# Server Events Client
    4. Redis Server Events
  13. Service Gateway

    1. Overview
    2. Service Discovery
  14. Encrypted Messaging

    1. Overview
    2. Encrypted Client
  15. Plugins

    1. Auto Query
    2. Server Sent Events
    3. Swagger API
    4. Postman
    5. Request logger
    6. Sitemaps
    7. Cancellable Requests
    8. CorsFeature
  16. Tests

    1. Testing
    2. HowTo write unit/integration tests
  17. ServiceStackVS

    1. Install ServiceStackVS
    2. Add ServiceStack Reference
    3. TypeScript React Template
      1. React, Redux Chat App
    4. AngularJS App Template
    5. React Desktop Apps
  18. Other Languages

    1. FSharp
      1. Add ServiceStack Reference
    2. VB.NET
      1. Add ServiceStack Reference
    3. Swift
      1. Swift Add Reference
    4. Java
      1. Add ServiceStack Reference
      2. Android Studio & IntelliJ
      3. Eclipse
  19. Amazon Web Services

    1. ServiceStack.Aws
    2. PocoDynamo
    3. AWS Live Demos
    4. Getting Started with AWS
  20. Deployment

    1. Deploy Multiple Sites to single AWS Instance
      1. Simple Deployments to AWS with WebDeploy
    2. Advanced Deployments with OctopusDeploy
  21. Install 3rd Party Products

    1. Redis on Windows
    2. RabbitMQ on Windows
  22. Use Cases

    1. Single Page Apps
      1. HTML, CSS and JS Minifiers
    2. Azure
      1. Connecting to Azure Redis via SSL
    3. Logging
    4. Bundling and Minification
    5. NHibernate
  23. Performance

    1. Real world performance
  24. Other Products

    1. ServiceStack.Redis
    2. ServiceStack.OrmLite
    3. ServiceStack.Text
  25. Future

    1. Roadmap
Clone this wiki locally

This page has moved to docs.servicestack.net


ServiceStack's Add ServiceStack Reference feature allows adding generated Native Types for the most popular typed languages and client platforms directly from within most major IDE's starting with ServiceStackVS - providing a simpler, cleaner and more versatile alternative to WCF's Add Service Reference feature that's built into VS.NET.

Add ServiceStack Reference now supports Swift, Java, Kotlin, C#, TypeScript, F# and VB.NET including integration with most leading IDE's to provide a flexible alternative than sharing your DTO assembly with clients. Clients can now easily add a reference to a remote ServiceStack url and update DTOs directly from within VS.NET, Xamarin Studio, Xcode, Android Studio, IntelliJ and Eclipse. We plan on expanding on this foundation into adding seamless, typed, end-to-end integration with other languages - Add a feature request for your favorite language to prioritize support for it sooner!

Our goal with Native Types is to provide an alternative for sharing DTO dlls, that can enable a better dev workflow for external clients who are now able to generate (and update) Typed APIs for your Services from a single remote url directly within their favorite IDE - reducing the burden and effort required to consume ServiceStack Services whilst benefiting from clients native language strong-typing feedback.

ServiceStackVS offers the generation and updating of these clients through the same context for all supported languages giving developers a consistent way of creating and updating your DTOs regardless of their preferred language of choice.

Supported Languages

Example Usage

C# Android PCL Client example

C# Android PCL Client example

VB.NET client talking with C# Server example

CSharp server with VB.Net client example

Options for the generated DTOs can be changed by updating the commented section in the header of the file. Each language will have different options based on what is applicable to that language. For details on these options, please see the specific language wiki page.

ssutil.exe - Command line ServiceStack Reference tool

Add ServiceStack Reference is also moving beyond our growing list of supported IDEs and is now available in a single cross-platform .NET command-line .exe making it easy for build servers and automated tasks or command-line runners of your favorite text editors to easily Add and Update ServiceStack References!

To Get Started download ssutil.exe and open a command prompt to the containing directory:

Download ssutil.exe

ssutil.exe Usage:

Adding a new ServiceStack Reference

To create a new ServiceStack Reference, pass the remote ServiceStack BaseUrl then specify both which -file and -lang you want, e.g:

ssutil http://techstacks.io -file TechStacks -lang CSharp

Executing the above command fetches the C# DTOs and saves them in a local file named TechStacks.dtos.cs.

Available Languages

  • CSharp
  • Swift
  • Java
  • Kotlin
  • TypeScript / TypeScript.d
  • FSharp
  • VbNet

Update existing ServiceStack Reference

Updating a ServiceStack Reference is even easier we just specify the path to the existing generated DTOs. E.g. Update the TechStacks.dtos.cs we just created with:

ssutil TechStacks.dtos.cs

Running on Windows

Running on OSX

Advantages over WCF

  • Simple Server provides DTOs based on metadata and options provided. No heavy client side tools, just a HTTP request!
  • Versatile Clean DTOs works in all JSON, XML, JSV, MsgPack and ProtoBuf generic service clients
  • Reusable Generated DTOs are not coupled to any endpoint or format. Defaults are both partial and virtual for maximum re-use
  • Resilient Messaging-based services offer a number of advantages over RPC Services
  • Flexible DTO generation is customizable, Server and Clients can override built-in defaults
  • Integrated Rich Service metadata annotated on DTO's, Internal Services are excluded when accessed externally

In Contrast with WCF's Add Service Reference

WCF's Add Service Reference also allows generating a typed client from a single url, and whilst it's a great idea, the complexity upon what it's built-on and the friction it imposes were the primary reasons we actively avoided using it (pre-ServiceStack). We instead opted to reuse our server DTO types and created Generic WCF Proxies, to provide a cleaner and simpler solution when consuming our own WCF services.

Complexity of WCF's Add Service Reference

To achieve this feature WCF generates its client proxies using a remote services WSDL. A WSDL is basically a machine-readable XML definition language for describing SOAP Services. It's abstract enough to cover different styles of services and introduces a number of artificial concepts to facilitate it, including: Service, Port, Binding, PortType, Operation, Message and Types. As WSDL's are complex they mandate the use of heavy tooling to generate and maintain both the WSDL file, the generated client proxies and its necessary client configuration. Despite all this complexity it's coupled and limited into using the verbose SOAP protocol and XML wire format which when coupled with WCF's promotion of RPC method signatures meant even minor changes would break existing clients, resulting in a heavy and fragile solution for evolving web services.

How Message based Services would benefit WCF

A small part of a WSDL is the XSD definitions of Types used in the Services. Had WCF only supported a message-based style it could dispense with the overhead of using a WSDL at all and just use XSD schema to generate the DTO's, eliminating the neeed for a SOAP envelope where it could just send Plain Old XML across the wire. As an added benefit it would've got JSON support for free by reusing the generated types in .NET's JSON DataContract Serializer.

Unnecessary Complexity of XSDs

Despite being much simpler, even XSD's by themselves are more complex than it needs to be. The XML Schema specification is itself several hundred pages long and contains many elements which make it a poor programmatic fit for any programming language. E.g. use of XML namespaces and attributes in addition to elements does not naturally map to any language type system and causes unnecessary friction and additional boilerplate to handle this mismatch during serialization.

This is in stark contrast with the JSON spec which fits on a single page yet manages to include most of the core elements required for data interchange consisting of Arrays, Objects and primitive number, string, boolean and null types. It's also a perfect fit for most languages where all valid JSON is always convertible to a valid JavaScript object. When more specialized types are required, you have access to the full power of the host programming language to perform custom conversions, providing a more flexible alternative than otherwise breaking clients requests on minor schema changes.

ServiceStack's Native Types Feature

As with any ServiceStack feature one of our primary goals is to minimize unnecessary complexity by opting for approaches that yield maximum value and minimal complexity, favoring re-use and simple easy to reason about solutions over opaque heavy black-box tools.

We can already see from the WCF scenario how ServiceStack already benefits from its message-based design, where as it's able to reuse any Generic Service Client, only application-specific DTO's ever need to be generated, resulting in a much cleaner, simpler and friction-less solution.

Code-first is another approach that lends itself to simpler solutions, which saves the effort and inertia from adapting to interim schemas/specs, often with impedance mismatches and reduced/abstract functionality. In ServiceStack your code-first DTOs are the master authority where all other features are projected off.

C# also has great language support for defining POCO Data Models, that's as terse as a DSL but benefits from great IDE support and minimal boilerplate, e.g:

[Route("/path")]
public class Request : IReturn<Response>
{
    public int Id { get; set; }
    public string Name { get; set; }
    ...
}

Starting from a C# model, whilst naturally a better programmatic fit also ends up being richer and more expressive than XSD's which supports additional metadata annotations like Attributes and Interfaces.

Enabled by default from v4.0.30+ ServiceStack Projects

Native Types is now available by default on all v4.0.30+ ServiceStack projects. It can be disabled by removing the NativeTypesFeature plugin with:

Plugins.RemoveAll(x => x is NativeTypesFeature);

Generating Types from Metadata

Behind the scenes ServiceStack captures all metadata on your Services DTOs including Sub -classes, Routes, IReturn marker, C# Attributes, textual Description as well as desired configuration into a serializable object model accessible from /types/metadata:

Live examples

This model is then used to generate the generated types, which for C# is at /types/csharp.

Excluding Types from Add ServiceStack Reference

To remove a type from the metadata and code generation you can annotate Request DTOs with [Exclude(Feature.Metadata)], e.g:

[Exclude(Feature.Metadata)]
public class ExcludedFromMetadata
{
    public int Id { get; set; }
}

An alternative is it add it to the IgnoreTypes collection in the NativeTypes Feature Metadata Config in your AppHost:

var nativeTypes = this.GetPlugin<NativeTypesFeature>();
nativeTypes.MetadataTypesConfig.IgnoreTypes.Add(typeof(TypeToIgnore));

If you only want to limit code generation based on where the reference is being added from you can use the Restrict Attribute, E.g you can limit types to only appear when the reference is added from localhost:

[Restrict(LocalhostOnly = true)]
public class ResrtictedToLocalhost { }

Or when added from within an internal network:

[Restrict(InternalOnly = true)]
public class RestrictedToInternalNetwork { }

There's also the rarer option when you only want a service accessible from external requests with:

[Restrict(ExternalOnly = true)]
public class RestrictedToExternalRequests { }

How it works

The Add ServiceStack Reference dialog just takes the URL provided and requests the appropriate route for the current project. Eg, for C#, the path used is at /types/csharp. The defaults are specified by the server and the resultant DTOs are saved and added the the project as {Name}.dtos.{LanguageExtension}. The Update ServiceStack Reference menu is available when any file matches same naming convention of {Name}.dtos.{LanguageExtension}. An update then looks at the comments at the top of the file and parses them to provide overrides when requesting new DTOs from the server. ServiceStackVS also watches these DTO files for updates, so just by saving them these files are updated from the server.

Language Paths

  • /types/csharp - C#
  • /types/swift - Swift
  • /types/java - Java
  • /types/kotlin - Kotlin
  • /types/typescript - TypeScript
  • /types/typescript.d - Ambient TypeScript Definitions
  • /types/fsharp - F#
  • /types/vbnet - VB.NET
  • /types/metadata - Metadata

Limitations

In order for Add ServiceStack Reference to work consistently across all supported languages without .NET semantic namespaces, DTOs includes an additional restriction where each Type must be uniquely named. You can get around this restriction by sharing the ServiceModel.dll where your DTOs are defined instead.

Using with IIS Windows Authentication

If you have configured your NativeTypes service to run on IIS with Windows Authentication enabled, you need to ensure that the /types routes are reachable and do not require the system-level authentication from IIS. To accomplish this, add the following to Web.config.

<configuration>
    <location path="types">
        <system.web>
            <authorization>
                <allow users="?" />
            </authorization>
        </system.web>
    </location>
</configuration>