0
Granuläres .NET-WebDevelopment
...mit Nancy- & Simple.DataFrameworks
Timothée Bourguignon
MATHEMA Software GmbH
The Menu
• First date with Nancy
– Generalities & Basics
– Mini-HackerNews Demo
• Simple.Data
– Overview
– Further Mini-Ha...
First Date with Nancy
„Lightweight Web Framework for .NET“
nancyfx.org | #nancyfx
Microframework
• Lean API
• Extensible API
• Simple setup
• “Close to the metal”
What has Nancy to offer?
•
•
•
•
•
•
•

Simplicity & Readability
Modularity
OpenSource
"Close" to HTTP
Very explicit routi...
„Hello Nancy“
public class MyModule : NancyModule
{
public MyModule()
{
Get["/"] = _ => "Hello World";
}
}
Route
• Composed of
– Method (HTTP Methods: Get, Post, Put…)
– Pattern
– Action (+parameters & result object)
– Condition ...
Pattern
• Literal segments: "/customer"
• Capture segments: "/{id}“
• Capture segments (Optional): "/{id?}“
• Capture segm...
Action
• Behavior invoked by a route

Dynamic
Dictionary

Action

Func<dynamic,
dynamic>

Get["/voteup/{id}"] = x => {
ret...
Nancy.Response
• Nancy.Response implicit casts
– Int32 → HTTP Status Code
– String → body of the response

• Response form...
Serving up Views
• Supported View Engines
– SuperSimpleViewEngine
– Razor, Spark, DotLiquid...
– … any other IViewEngine

...
Model Binding
• Module → View
– Any object Type
– dynamics per default

Get["/products"] = _ =>
{
return View["products",
...
Hands on Nancy
HackerNews meet Nancy
Simple.Data
...an O/RM without O, R or M
What is Simple.Data?
• Lightweight way of manipulating data
– Based on .NET 4.0's „dynamic“ keyword
– Interprets method an...
Database agnostic

19
Fluid Convention

Co
lu
m
Pa
n
ra
m
et
er
s

an
d
m
Co
m

Ta
bl
e/
Vi
ew

db.album.FindAllByGenreId(3);

20
„Hello Simple.Data“
public void GetCustomers()
{
var conString = "…";
dynamic db =
Database.OpenConnection(conString);
dyn...
Simple CRUD operations
public void CRUD()
{
db.People.FindAllByName("Bob");
db.People.FindByFirstNameAndLastName("Bob", "X...
Barely less simple operations
//Paging
db.Users.All().OrderByNickname().Skip(10).Take(10);
//Table joins
db.Customers.Find...
Nancy, meet Simple.Data
Simple.Data, meet Nancy
Second date with Nancy
In case the SuperDuperHappyPath is not completely Super,
Duper or Happy yet…
Bootstrapper
•
•
•
•

~DSL on top of the IoC container
Responsible for „putting the puzzle together“
Override and extend
A...
Content Negociation
• Client wishes:
– URI Extension: .json, .xml …
– Header information: „Accept: application/xml“

• Act...
Authentication
public class MyBootstrapper : DefaultNancyBootstrapper
{
protected override void InitialiseInternal(TinyIoC...
Testing
[Test]
public void Should_redirect_to_login_with_error_details_incorrect()
{
// Given
var bootstrapper = new Defau...
Nancy.Diagnostic
• localhost/_nancy
– Information
– Interactive diagnostic

– Request Tracing
– Settings
.NetHackerNews
Nancy Self-Hosted
Wrap-up!
• Simple, readable & flexible frameworks
• Run everywhere
• Nancy
• Simple.Data
– Easy to test
– Customisable
– G...
Further Reading
• Github
– https://github.com/markrendle/Simple.Data
– https://github.com/NancyFx/Nancy

• GoogleGroups

–...
Contacts
• Andreas Håkansson (NancyFx)
– @TheCodeJunkie

• Steven Robbins (NancyFx, TinyIoC)
– @Grumpydev
– http://www.gru...
Ich freue mich auf Eure Fragen!
tim.bourguignon@mathema.de
about.me/timbourguignon

35
Upcoming SlideShare
Loading in...5
×

Introduction to the Nancy Framework

1,765

Published on

Nancy is a lightweight, low-ceremony, framework for building HTTP based services on .Net and Mono. The goal of the framework is to stay out of the way as much as possible and provide a super-duper-happy-path to all interactions. Find more about it at nancyfx.org.

This Slide deck (in English) used at the DWX Conference in Nürnberg in July 2013 and provides you with an overview of the basic elements of the framework. The presentation material as well as the demo code can be found on github at https://github.com/Timothep/Talk.NancyFx

Published in: Technology, Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,765
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
10
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "Introduction to the Nancy Framework"

  1. 1. Granuläres .NET-WebDevelopment ...mit Nancy- & Simple.DataFrameworks Timothée Bourguignon MATHEMA Software GmbH
  2. 2. The Menu • First date with Nancy – Generalities & Basics – Mini-HackerNews Demo • Simple.Data – Overview – Further Mini-HackerNews Demo • Second Date with Nancy • Further Demos
  3. 3. First Date with Nancy „Lightweight Web Framework for .NET“ nancyfx.org | #nancyfx
  4. 4. Microframework • Lean API • Extensible API • Simple setup • “Close to the metal”
  5. 5. What has Nancy to offer? • • • • • • • Simplicity & Readability Modularity OpenSource "Close" to HTTP Very explicit routing Runs anywhere „Super Duper Happy Path“
  6. 6. „Hello Nancy“ public class MyModule : NancyModule { public MyModule() { Get["/"] = _ => "Hello World"; } }
  7. 7. Route • Composed of – Method (HTTP Methods: Get, Post, Put…) – Pattern – Action (+parameters & result object) – Condition (optional) Get["/voteup/{id}"] = x => { return View["Voteup", x.id]; };
  8. 8. Pattern • Literal segments: "/customer" • Capture segments: "/{id}“ • Capture segments (Optional): "/{id?}“ • Capture segments (Optional/Default): "{name?unnamed}“ • Regex Segments: /(?<id>[d]+) • Greedy Regex Segments: ^(?<name>[a-z]{3,10}(?:/{1}))$ • Greedy Segments: "/{id*}“ Get["/voteup/{id}"] = x => { return View["Voteup", x.id]; };
  9. 9. Action • Behavior invoked by a route Dynamic Dictionary Action Func<dynamic, dynamic> Get["/voteup/{id}"] = x => { return View["Voteup", x.id]; }; Nancy .Response <anything> → Content Negociation View ...
  10. 10. Nancy.Response • Nancy.Response implicit casts – Int32 → HTTP Status Code – String → body of the response • Response formatters: – As File, Image, Json, Xml & Redirect
  11. 11. Serving up Views • Supported View Engines – SuperSimpleViewEngine – Razor, Spark, DotLiquid... – … any other IViewEngine • View Engine is selected dynamically, based on the view's file extension • Views are also discovered Get["/products"] = _ => { return View["products.cshtml"]; };
  12. 12. Model Binding • Module → View – Any object Type – dynamics per default Get["/products"] = _ => { return View["products", someModel]; }; • View → Module – Query string – Captured parameters – Body of a request Foo foo = this.Bind(); var foo = this.Bind<Foo>(); this.BindTo(foo);
  13. 13. Hands on Nancy HackerNews meet Nancy
  14. 14. Simple.Data ...an O/RM without O, R or M
  15. 15. What is Simple.Data? • Lightweight way of manipulating data – Based on .NET 4.0's „dynamic“ keyword – Interprets method and property names – Maps them to your underlying data-store – Prevents SQL Injection – Inspired by Ruby’s ActiveRecord and DataMappers – Open Source & runs on Mono – V1.0 rc3 released in Nov. 2012 PM> Install-package Simple.Data.<TheProvider> 18
  16. 16. Database agnostic 19
  17. 17. Fluid Convention Co lu m Pa n ra m et er s an d m Co m Ta bl e/ Vi ew db.album.FindAllByGenreId(3); 20
  18. 18. „Hello Simple.Data“ public void GetCustomers() { var conString = "…"; dynamic db = Database.OpenConnection(conString); dynamic customer = db.Customers.FindById(1); } Console.WriteLine("{0}, {1}!", customer.FirstName, customer.LastName);
  19. 19. Simple CRUD operations public void CRUD() { db.People.FindAllByName("Bob"); db.People.FindByFirstNameAndLastName("Bob", "X"); db.Users.All().OrderByJoinDateDescending(); db.Users.All().OrderByJoinDate().ThenByNickname(); db.People.Insert(Id: 1, FirstName: "Bob"); db.People.Insert(new Person {Id = 1, Name = "Bob"}); db.People.UpdateById(Id: 1, FirstName: "Robert"); db.People.DeleteById(1); }
  20. 20. Barely less simple operations //Paging db.Users.All().OrderByNickname().Skip(10).Take(10); //Table joins db.Customers.FindByCustomerId(1).WithOrders(); //Casting Artist artist = db.Artists.Get(42); IList<Artist> artists = db.Artists.All().ToList<Artist>();
  21. 21. Nancy, meet Simple.Data Simple.Data, meet Nancy
  22. 22. Second date with Nancy In case the SuperDuperHappyPath is not completely Super, Duper or Happy yet…
  23. 23. Bootstrapper • • • • ~DSL on top of the IoC container Responsible for „putting the puzzle together“ Override and extend Autoregister your dependencies public class Home : NancyModule { public Home(IMessageService service) { //If there is only one implementation // of ImessageService, TinyIoC will // resolve it and inject it } }
  24. 24. Content Negociation • Client wishes: – URI Extension: .json, .xml … – Header information: „Accept: application/xml“ • Actions output: – ResponseObject • Response.AsXml(), Response.AsJson()... – ContentNegociation • Default ResponseProcessors: View, Xml, Json... return Negotiate.WithModel(model) .WithView("MyView");
  25. 25. Authentication public class MyBootstrapper : DefaultNancyBootstrapper { protected override void InitialiseInternal(TinyIoCContainer container) { base.InitialiseInternal(container); FormsAuthentication.Enable(this, new FormsAuthenticationConfiguration { RedirectUrl = "~/login", UsernameMapper = container.Resolve<IUsernameMapper>() }); }} public class MyModule : NancyModule { public MyModule() : base("/secure") { this.RequiresAuthentication(); Get["/"] = _ => "Secure!"; } }
  26. 26. Testing [Test] public void Should_redirect_to_login_with_error_details_incorrect() { // Given var bootstrapper = new DefaultNancyBootstrapper(); var browser = new Browser(bootstrapper); // When var response = browser.Post("/login/", (with) => { with.HttpRequest(); with.FormValue("Username", "username"); with.FormValue("Password", "wrongpassword"); }); // Then response.ShouldHaveRedirectedTo( "/login?error=true&username=username"); } PM> Install-package Nancy.Testing
  27. 27. Nancy.Diagnostic • localhost/_nancy – Information – Interactive diagnostic – Request Tracing – Settings
  28. 28. .NetHackerNews Nancy Self-Hosted
  29. 29. Wrap-up! • Simple, readable & flexible frameworks • Run everywhere • Nancy • Simple.Data – Easy to test – Customisable – Great for Webservices – Powerful – DB Agnostic – Compelling • Excellent for prototypes & small projects • „Super duper happy path“
  30. 30. Further Reading • Github – https://github.com/markrendle/Simple.Data – https://github.com/NancyFx/Nancy • GoogleGroups – Simpledata – Nancy-web-framework 33
  31. 31. Contacts • Andreas Håkansson (NancyFx) – @TheCodeJunkie • Steven Robbins (NancyFx, TinyIoC) – @Grumpydev – http://www.grumpydev.com/ • Mark Rendle (Simple.Data) – @MarkRendle – http://blog.markrendle.net/
  32. 32. Ich freue mich auf Eure Fragen! tim.bourguignon@mathema.de about.me/timbourguignon 35
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×