SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Downloaden Sie, um offline zu lesen
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-HackerNews Demo
• Second Date with Nancy
• Further Demos
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 routing
Runs anywhere
„Super Duper Happy Path“
„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 (optional)

Get["/voteup/{id}"] = x => {
return View["Voteup", x.id];
};
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];
};
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

...
Nancy.Response
• Nancy.Response implicit casts
– Int32 → HTTP Status Code
– String → body of the response

• Response formatters:
– As File, Image, Json, Xml & Redirect
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"];
};
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);
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 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
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);
dynamic customer = db.Customers.FindById(1);

}

Console.WriteLine("{0}, {1}!",
customer.FirstName, customer.LastName);
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);
}
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>();
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
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
}
}
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");
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!";
}
}
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
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
– Great for Webservices

– Powerful
– DB Agnostic
– Compelling

• Excellent for prototypes & small projects
• „Super duper happy path“
Further Reading
• Github
– https://github.com/markrendle/Simple.Data
– https://github.com/NancyFx/Nancy

• GoogleGroups

– Simpledata
– Nancy-web-framework

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

• Steven Robbins (NancyFx, TinyIoC)
– @Grumpydev
– http://www.grumpydev.com/

• Mark Rendle (Simple.Data)
– @MarkRendle
– http://blog.markrendle.net/
Ich freue mich auf Eure Fragen!
tim.bourguignon@mathema.de
about.me/timbourguignon

35

Weitere ähnliche Inhalte

Was ist angesagt?

Evolution of integration and microservices patterns with service mesh
Evolution of integration and microservices patterns with service meshEvolution of integration and microservices patterns with service mesh
Evolution of integration and microservices patterns with service mesh
Christian Posta
 

Was ist angesagt? (20)

Evolution of integration and microservices patterns with service mesh
Evolution of integration and microservices patterns with service meshEvolution of integration and microservices patterns with service mesh
Evolution of integration and microservices patterns with service mesh
 
Warsaw muleSoft meetup #11 MuleSoft OData
Warsaw muleSoft meetup #11 MuleSoft ODataWarsaw muleSoft meetup #11 MuleSoft OData
Warsaw muleSoft meetup #11 MuleSoft OData
 
Node.js Blockchain Implementation
Node.js Blockchain ImplementationNode.js Blockchain Implementation
Node.js Blockchain Implementation
 
JavaOne 2016 - Reactive Microservices with Java and Java EE
JavaOne 2016 - Reactive Microservices with Java and Java EEJavaOne 2016 - Reactive Microservices with Java and Java EE
JavaOne 2016 - Reactive Microservices with Java and Java EE
 
Live Node.JS Training
Live Node.JS TrainingLive Node.JS Training
Live Node.JS Training
 
Building an E-commerce website in MEAN stack
Building an E-commerce website in MEAN stackBuilding an E-commerce website in MEAN stack
Building an E-commerce website in MEAN stack
 
TabTale Architecture Overview
TabTale Architecture OverviewTabTale Architecture Overview
TabTale Architecture Overview
 
The Dark Side of Single Page Applications
The Dark Side of Single Page ApplicationsThe Dark Side of Single Page Applications
The Dark Side of Single Page Applications
 
Blazor certification training - Dot Net Tricks
Blazor certification training - Dot Net TricksBlazor certification training - Dot Net Tricks
Blazor certification training - Dot Net Tricks
 
autodiscoverable microservices with vertx3
autodiscoverable microservices with vertx3autodiscoverable microservices with vertx3
autodiscoverable microservices with vertx3
 
Building Services with WSO2 Microservices framework for Java and WSO2 AS
Building Services with WSO2 Microservices framework for Java and WSO2 ASBuilding Services with WSO2 Microservices framework for Java and WSO2 AS
Building Services with WSO2 Microservices framework for Java and WSO2 AS
 
Using NodeJS for Real-Time Web
Using NodeJS for Real-Time WebUsing NodeJS for Real-Time Web
Using NodeJS for Real-Time Web
 
MongoDB Days Silicon Valley: Building Applications with the MEAN Stack
MongoDB Days Silicon Valley: Building Applications with the MEAN StackMongoDB Days Silicon Valley: Building Applications with the MEAN Stack
MongoDB Days Silicon Valley: Building Applications with the MEAN Stack
 
Social network with microservices
Social network with microservicesSocial network with microservices
Social network with microservices
 
Ieee S&P 2020 - Software Security: from Research to Industry.
Ieee S&P 2020 - Software Security: from Research to Industry.Ieee S&P 2020 - Software Security: from Research to Industry.
Ieee S&P 2020 - Software Security: from Research to Industry.
 
5 Popular Choices for NoSQL on a Microsoft Platform - All Things Open - Octob...
5 Popular Choices for NoSQL on a Microsoft Platform - All Things Open - Octob...5 Popular Choices for NoSQL on a Microsoft Platform - All Things Open - Octob...
5 Popular Choices for NoSQL on a Microsoft Platform - All Things Open - Octob...
 
Rapid Application Development with MEAN Stack
Rapid Application Development with MEAN StackRapid Application Development with MEAN Stack
Rapid Application Development with MEAN Stack
 
Glass fish performance tuning tips from the field
Glass fish performance tuning tips from the fieldGlass fish performance tuning tips from the field
Glass fish performance tuning tips from the field
 
CloudStack challenges for China customers
CloudStack challenges for China customersCloudStack challenges for China customers
CloudStack challenges for China customers
 
Lagom : Reactive microservice framework
Lagom : Reactive microservice frameworkLagom : Reactive microservice framework
Lagom : Reactive microservice framework
 

Andere mochten auch

Micro Service Architecture
Micro Service ArchitectureMicro Service Architecture
Micro Service Architecture
Eduards Sizovs
 

Andere mochten auch (12)

AngularJS + NancyFx + MongoDB = The best trio for ultimate SPA by Bojan Velja...
AngularJS + NancyFx + MongoDB = The best trio for ultimate SPA by Bojan Velja...AngularJS + NancyFx + MongoDB = The best trio for ultimate SPA by Bojan Velja...
AngularJS + NancyFx + MongoDB = The best trio for ultimate SPA by Bojan Velja...
 
Scala for Java Developers - Intro
Scala for Java Developers - IntroScala for Java Developers - Intro
Scala for Java Developers - Intro
 
Microservices com ASP.NET 5
Microservices com ASP.NET 5Microservices com ASP.NET 5
Microservices com ASP.NET 5
 
Designing and building a micro-services architecture. Stairway to heaven or a...
Designing and building a micro-services architecture. Stairway to heaven or a...Designing and building a micro-services architecture. Stairway to heaven or a...
Designing and building a micro-services architecture. Stairway to heaven or a...
 
Building .NET Microservices
Building .NET MicroservicesBuilding .NET Microservices
Building .NET Microservices
 
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20....Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
 
Developing applications with a microservice architecture (svcc)
Developing applications with a microservice architecture (svcc)Developing applications with a microservice architecture (svcc)
Developing applications with a microservice architecture (svcc)
 
From SOA to MSA
From SOA to MSAFrom SOA to MSA
From SOA to MSA
 
Architecting Microservices in .Net
Architecting Microservices in .NetArchitecting Microservices in .Net
Architecting Microservices in .Net
 
Micro Service Architecture
Micro Service ArchitectureMicro Service Architecture
Micro Service Architecture
 
MicroService Architecture
MicroService ArchitectureMicroService Architecture
MicroService Architecture
 
Microservices Architecture for Web Applications using AWS Lambda and more
Microservices Architecture for Web Applications using AWS Lambda and moreMicroservices Architecture for Web Applications using AWS Lambda and more
Microservices Architecture for Web Applications using AWS Lambda and more
 

Ähnlich wie Introduction to the Nancy Framework

Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
Mohammad Qureshi
 
Nancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web FrameworkNancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web Framework
Christian Horsdal
 

Ähnlich wie Introduction to the Nancy Framework (20)

My way to clean android - Android day salamanca edition
My way to clean android - Android day salamanca editionMy way to clean android - Android day salamanca edition
My way to clean android - Android day salamanca edition
 
Webinar: Architecting Secure and Compliant Applications with MongoDB
Webinar: Architecting Secure and Compliant Applications with MongoDBWebinar: Architecting Secure and Compliant Applications with MongoDB
Webinar: Architecting Secure and Compliant Applications with MongoDB
 
Architecting Secure and Compliant Applications with MongoDB
Architecting Secure and Compliant Applications with MongoDB        Architecting Secure and Compliant Applications with MongoDB
Architecting Secure and Compliant Applications with MongoDB
 
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
Microservices in GO - Massimiliano Dessì - Codemotion Rome 2017
 
Nancy & Simple.Data from ProgNet 11
Nancy & Simple.Data from ProgNet 11Nancy & Simple.Data from ProgNet 11
Nancy & Simple.Data from ProgNet 11
 
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry PiMonitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
My way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca editionMy way to clean android (EN) - Android day salamanca edition
My way to clean android (EN) - Android day salamanca edition
 
Node azure
Node azureNode azure
Node azure
 
RedisConf18 - Writing modular & encapsulated Redis code
RedisConf18 - Writing modular & encapsulated Redis codeRedisConf18 - Writing modular & encapsulated Redis code
RedisConf18 - Writing modular & encapsulated Redis code
 
Back to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDBBack to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDB
 
Nancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web FrameworkNancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web Framework
 
20141011 mastering mysqlnd
20141011 mastering mysqlnd20141011 mastering mysqlnd
20141011 mastering mysqlnd
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.js
 
20120816 nodejsdublin
20120816 nodejsdublin20120816 nodejsdublin
20120816 nodejsdublin
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
NoSQL meets Microservices
NoSQL meets MicroservicesNoSQL meets Microservices
NoSQL meets Microservices
 
Michael Hackstein - NoSQL meets Microservices - NoSQL matters Dublin 2015
Michael Hackstein - NoSQL meets Microservices - NoSQL matters Dublin 2015Michael Hackstein - NoSQL meets Microservices - NoSQL matters Dublin 2015
Michael Hackstein - NoSQL meets Microservices - NoSQL matters Dublin 2015
 
Offline-First Mobile Web Apps with PouchDB, IBM Cloudant, and IBM Bluemix
Offline-First Mobile Web Apps with PouchDB, IBM Cloudant, and IBM BluemixOffline-First Mobile Web Apps with PouchDB, IBM Cloudant, and IBM Bluemix
Offline-First Mobile Web Apps with PouchDB, IBM Cloudant, and IBM Bluemix
 
Hazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMSHazelcast and MongoDB at Cloud CMS
Hazelcast and MongoDB at Cloud CMS
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Introduction to the Nancy Framework

  • 1. Granuläres .NET-WebDevelopment ...mit Nancy- & Simple.DataFrameworks Timothée Bourguignon MATHEMA Software GmbH
  • 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. First Date with Nancy „Lightweight Web Framework for .NET“ nancyfx.org | #nancyfx
  • 4. Microframework • Lean API • Extensible API • Simple setup • “Close to the metal”
  • 5. What has Nancy to offer? • • • • • • • Simplicity & Readability Modularity OpenSource "Close" to HTTP Very explicit routing Runs anywhere „Super Duper Happy Path“
  • 6. „Hello Nancy“ public class MyModule : NancyModule { public MyModule() { Get["/"] = _ => "Hello World"; } }
  • 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. 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. 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. Nancy.Response • Nancy.Response implicit casts – Int32 → HTTP Status Code – String → body of the response • Response formatters: – As File, Image, Json, Xml & Redirect
  • 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. 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);
  • 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
  • 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. 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. 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>();
  • 22. Second date with Nancy In case the SuperDuperHappyPath is not completely Super, Duper or Happy yet…
  • 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. 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. 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. 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. Nancy.Diagnostic • localhost/_nancy – Information – Interactive diagnostic – Request Tracing – Settings
  • 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. Further Reading • Github – https://github.com/markrendle/Simple.Data – https://github.com/NancyFx/Nancy • GoogleGroups – Simpledata – Nancy-web-framework 33
  • 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. Ich freue mich auf Eure Fragen! tim.bourguignon@mathema.de about.me/timbourguignon 35