GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — CSV Format CSV Format
Demis Bellot edited this page
This page has moved to docs.servicestack.net/csv-formatThe CSV format is a first-class supported format which means all your existing web services can automatically take accept and return CSV without any config or code changes. CSV is an important format for transferring, migrating and quickly visualizing data as all spreadsheets support viewing and editing CSV files directly whilst its supported by most RDBMS support exporting and importing data. Compared with other serialization formats, it provides a compact and efficient way to transfer large datasets in an easy to read text format. The CSV Serializer used was developed using the same tech that makes ServiceStack's JSV and JSON serializers fast (i.e. no run-time reflection, static delegate caching, etc), which should make it the fastest CSV serializer available for .NET. The What makes the 'CSV' format different is its the first format added using the new extensions API. The complete code to register the CSV format is: //Register the 'text/csv' content-type and serializers //(format is inferred from the last part of the content-type) this.ContentTypes.Register(ContentType.Csv, CsvSerializer.SerializeToStream, CsvSerializer.DeserializeFromStream); //ResponseFilter to add 'Content-Disposition' header for browsers to open in Spreadsheet this.ResponseFilters.Add((req, res, dto) => { if (req.ResponseContentType == ContentType.Csv) { res.AddHeader(HttpHeaders.ContentDisposition, string.Format("attachment;filename={0}.csv", req.OperationName)); } }); Note: ServiceStack already does this for you though it still serves a good example to show how you can plug-in your own custom format. If you wish, you can remove all custom formats with (inside AppHost.Configure()): this.ContentTypes.ClearCustomFilters(); The ability to automatically to register another format and provide immediate value and added functionality to all your existing web services (without any code-changes or configuration) we believe is a testament to ServiceStack's clean design of using strongly-typed 'message-based' DTOs to let you develop clean, testable and re-usable web services. No code-gen or marshalling is required to bind to an abstract method signature, every request and calling convention maps naturally to your webservices DTOs. The CSV format is effectively a first-class supported format so everything should work as expected, including being registered as an available format on ServiceStack's metadata index page: And being able to preview the output of a service: By default they are automatically available using ServiceStack's standard calling conventions, e.g: CSV also works just as you would expect with user-defined REST-ful urls, i.e. you can append This is how the above web service output looks when opened up in google docs Alternative in following with the HTTP specification you can also specify content-type var csv = "http://nortwind.servicestack.net/customers".GetCsvFromUrl(); The introduction of the new AutoQuery Data feature and it's var pocos = File.ReadAllText("path/to/data.csv").FromCsv<List<Poco>>(); //AutoQuery Data Plugin Plugins.Add(new AutoQueryDataFeature() .AddDataSource(ctx => ctx.MemorySource(pocos))); // AutoQuery DTO [Route("/pocos")] public class QueryPocos : QueryData<Poco> {} A noteworthy feature that sets ServiceStack's CSV support apart is that it's built on the compact and very fast
JSV Format which not only can
deserialize a tabular flat file of scalar values at high-speed, it also supports deeply nested object graphs
which are encoded in JSV and escaped in a CSV field as normal. An example of this can be seen in a HTTP
sample log fragment below where the HTTP Request Headers are a serialized from a Being such a versatile file format opens up a lot of new possibilities, e.g. instead of capturing seed data in code you could maintain them in plain-text .csv files and effortlessly load them on App Startup, e.g: using (var db = container.Resolve<IDbConnectionFactory>().Open()) { if (db.CreateTableIfNotExists<Country>()) //returns true if Table created { List<Country> countries = "~/App_Data/countries.csv".MapHostAbsolutePath() .ReadAllText().FromCsv<List<Country>>(); db.InsertAll(countries); } } Another immediate benefit of CSV Deserialization is that now all Services can now process the CSV Content-Type.
Being a tabular data format, CSV shines when it's processing a list of DTO's, one way to do that in
ServiceStack is to have your Request DTO inherit [Route("/pocos")] public class Pocos : List<Poco>, IReturn<Pocos> { public Pocos() {} public Pocos(IEnumerable<Poco> collection) : base(collection) {} } It also behaves the same way as CSV Serialization but in reverse where if your Request DTO is annotated
with either [Route("/pocos")] [DataContract] public class Pocos : IReturn<Pocos> { [DataMember] public List<Poco> Items { get; set; } } [Route("/pocos")] [Csv(CsvBehavior.FirstEnumerable)] public class Pocos : IReturn<Pocos> { public List<Poco> Items { get; set; } } In addition to the above flexible options for defining CSV-friendly Services, there's also a few different
options for sending CSV Requests to the above Services. You can use the new CSV string csvText = File.ReadAllText("pocos.csv"); //Send CSV Text List<Poco> response = "http://example.org/pocos" .PostCsvToUrl(csvText) .FromCsv<List<Poco>>(); //Send POCO DTO's List<Poco> dtos = csvText.FromCsv<List<Poco>>(); List<Poco> response = "http://example.org/pocos" .PostCsvToUrl(dtos) .FromCsv<List<Poco>>(); Alternatively you can use the var client = new CsvServiceClient(baseUrl); Pocos response = client.Post(new Pocos(dtos)); The var requests = new[] { new Request { ... }, new Request { ... }, new Request { ... }, }; var responses = client.SendAll(requests); As most readers familiar with the CSV format will know there are some inherent limitations with CSV-format namely it is a flat-structured tabular data format that really only supports serialization of a single resultset. This limitation remains, although if you decorate your Response DTO with a
Basically if you only return 1 result it should work as expected otherwise it will chose the best candidate based on the rules above. The second major limitation is that it doesn't yet include a CSV Deserializer (currently on the TODO list), so while you can view the results in CSV format you can't post data to your web service in CSV and have it automatically deserialize for you. You can however still upload a CSV file and parse it manually yourself. Unlike most CSV serializers that can only serialize rows of primitive values, the CsvSerializer uses the JSV Format under the hood so even complex types will be serialized in fields in a easy to read format - no matter how deep its hierarchy.
Clone this wiki locally |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |