SlideShare a Scribd company logo
1 of 65
Download to read offline
Riccardo Terrell – Zurich F# UG
F# and SignalR
for a FastWeb
The tools we use have a profound (and devious!) influence on our thinking habits,
and, therefore, on our thinking abilities.
— Edsger Dijkstra
Agenda
Why F# on the Web
F# Magic
SignalR and F#
CQRS and F#
Code & Code
Goals - Plan of the talk
F# is a great and
mature language for
Web Development
F# has built in features
to develop Fast and
Scalable Web App
F# |> RX |> SignalR
|> CQRS |>
Technology trends
Mobile
Claud computing
Real Time notification
Single Page Apps
Big Data
Scalable
Maintanable & Readable
Reliable & Testable
Composable & Reusable
Concurrent
…F# and Functional Paradigm can help
F# helps with the mission statement simple
code for complex problem…
F# great for scalability and concurrent ready
F# play well together with Web Application
Use function and composition as building
block
Why F# on the web? Really?
Is functional programming and F# mostly targeted at scientific or financial
domains?
Is functional programming and F# just for Server Side computations?
Is functional programming and F# mostly about algorithms and calculations?
Why F# on the web?
Succinct - F# is concise, readable and type-safe, for fast development of
robust web solutions
Reactive and Scalable - F# asynchronous programming simplifies scalable,
reactive web programming, and Agent too!
Fast - F# code execution is fast, using native code generation from scripted
or project code
Interoperable - F# interoperates seamlessly with languages such as C#,
JavaScript and TypeScript, F# is JavaScript-ready through WebSharper
and FunScript
F# Type Providers on the Web
¤  JSON Type Provider
¤  CSV
¤  WSDL
¤  WMI
¤  Data Access – SQL and EF
¤  Funscript to Javascript
¤  And more, write your own
Type provider
IDE
IntelliSense for
Generated Types
Compiler
Type-Check
Imported Types
Compile using Type
Provider
F# Type Providers on the Web
Function Composition
Function Composition
Asynchronous Workflows
¤  Software is often I/O-bound, it provides notable
performance benefits
n  Connecting to the Database
n  Leveraging web services
n  Working with data on disk
¤  Network and disk speeds increasing slower
¤  Not Easy to predict when the operation will complete (no-
deterministic)
¨  Easy transition from synchronous
¤  Wrap in asynchronous workflow with the async keyword, use let! for async
calls and add return
¤  No need of explicit callback
¤  Easy to debug
¨  Supports loops, recursion, exceptions, cancellation, resource management
¨  Operation complete in the same scope
let	
  getLength	
  url	
  =	
  	
  	
  
	
  	
  let	
  wc	
  =	
  new	
  WebClient()	
  
	
  	
  let	
  	
  data	
  =	
  wc.DownloadString(url)	
  
	
  	
  data.Length	
  	
  	
  
Anatomy of Async Workflows
¨  Easy transition from synchronous
¤  Wrap in asynchronous workflow with the async keyword, use let! for async
calls and add return
¤  No need of explicit callback
¤  Easy to debug
¨  Supports loops, recursion, exceptions, cancellation, resource management
¨  Operation complete in the same scope
let	
  getLength	
  url	
  =	
  async	
  {	
  
	
  	
  let	
  wc	
  =	
  new	
  WebClient()	
  
	
  	
  let	
  	
  data	
  =	
  wc.DownloadString(url)	
  
	
  	
  data.Length	
  }	
  
Anatomy of Async Workflows
¨  Easy transition from synchronous
¤  Wrap in asynchronous workflow with the async keyword, use let! for async
calls and add return
¤  No need of explicit callback
¤  Easy to debug
¨  Supports loops, recursion, exceptions, cancellation, resource management
¨  Operation complete in the same scope
let	
  getLength	
  url	
  =	
  async	
  {	
  
	
  	
  let	
  wc	
  =	
  new	
  WebClient()	
  
	
  	
  let	
  	
  data	
  =	
  wc.DownloadString(url)	
  
	
  	
  return	
  data.Length	
  }	
  
Anatomy of Async Workflows
¨  Easy transition from synchronous
¤  Wrap in asynchronous workflow with the async keyword, use let! for async
calls and add return
¤  No need of explicit callback
¤  Easy to debug
¨  Supports loops, recursion, exceptions, cancellation, resource management
¨  Operation complete in the same scope
let	
  getLength	
  url	
  =	
  async	
  {	
  
	
  	
  let	
  wc	
  =	
  new	
  WebClient()	
  
	
  	
  let!	
  data	
  =	
  wc.AsyncDownloadString(url)	
  
	
  	
  return	
  data.Length	
  }	
  
Anatomy of Async Workflows
Asynchronous Workflows
let	
  openFileAsynchronous	
  :	
  Async<unit>	
  
	
  	
  async	
  {	
  use	
  	
  fs	
  =	
  new	
  	
  FileStream(@"C:Program	
  Files...,	
  …)	
  
	
   	
  	
  	
  	
  	
  	
  let	
  	
  data	
  =	
  Array.create	
  (int	
  fs.Length)	
  0uy	
  
	
   	
  	
  	
  	
  	
  	
  let!	
  	
  bytesRead	
  =	
  fs.AsyncRead(data,	
  0,	
  data.Length)	
  
	
   	
  	
  	
  	
  	
  	
  do	
  	
  printfn	
  "Read	
  Bytes:	
  %i,	
  First	
  bytes	
  were:	
  	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  %i	
  %i	
  %i	
  ..."	
  bytesRead	
  data.[1]	
  data.[2]	
  data.[3]	
  }	
  
¤  Async defines a block of code we would like to run asynchronously
¤  We use let! instead of let
n  let! binds asynchronously, the computation in the async block waits until the let!
completes
n  While it is waiting it does not block
n  No program or OS thread is blocked
F# MailboxProcessor – aka Agent
¨  F# really shines in the area of distributed
computing
¤  Language features such as Async Workflow
and MailboxProcessor (a.k.a. agent) open the
doors for computing that focuses on message
passing concurrency
¤  Scaling Up & Scaling Out easy to implement
Concurrent Model Programming
An Agent is an independent computational entity
which contains a queue, and receives and
processes messages
It provides immutability and isolation
(it enforces coarse-grained isolation through message-passing)
IObserver & IObservable
When to use Rx
http://www.introtorx.com/content/v1.0.10621.0/01_WhyRx.html
F# to JavaScript - FunScript
¨  FunScript is Javascript compiler
¤  Write F# client-side code with full intellisense
¤  Leverage F# functional goodies that compiles in JS
n  Higher Order functions
n  Pattern Matching
n  Type Inference
Full functional Data-Structure
Records
Discriminated Union
Tuples
List Map Set seq
.Net mutable Collections Array – Dictionary - List
F# to JavaScript - FunScript
¨  F# unique Features
¤  Async Workflow
¤  Reactive Extensions
¤  Type Providers
¤  Computation Expression
F# and MVC - Web Api
WPF
Android
iPad
Pc Win
Os
iPhone
Mac
Web API
F# and MVC - Web Api
F# Magic in review
TypeProvider
Function Composition - ROP
Async Workflow
MailboxProcessor – aka Agent
Reactive Extensions
FunScript
Full integration with Asp.Net MVC &
Web API
RX the Dual of IEnumerable
http://en.wikipedia.org/wiki/Dual_(category_theory)
Reversing arrows
The input becomes output and <->
IObserver & IObservable
When to use Rx
http://www.introtorx.com/content/v1.0.10621.0/01_WhyRx.html
Subject<‘a>.. as a bus
What is SignalR?
Asp.Net
Self-Host
Owin
javaScript
.Net
WinRT
What is SignalR?
SignalR
Client Server
Why SignalR?
… the real questions are
¨  When the Web users want their Data?
¨  When the Web user want the latest info?
Why SignalR?
What can SignalR do?
SignalR can be used to add any sort of "real-time" web
functionality to your application…
¨  Anything that needs live data
¤  Chat Room application
¤  Broadcasting (Stock Tickers, Live Scores…)
¤  Internet Games ( http://shootr.signalr.net/default.aspx# )
¤  Social Media
¤  Collaborative Apps
SignalR levels of abstraction
Hubs
Persistent Connection
Transports
Internet protocols
Abstractionlevel
WebSockets
Server-Sent
Events
Long polling
Forever
frame
Persistent Connection
Client (javascript)
var conn = $.connection(“myChat”);
conn.start();
conn.send(“Hello F#!!”);
conn.receive(function(text){
$(“#log”).append(“<li>” + text …
type MyChat() =
inherit PersistentConnection()
override x.OnConnected() : Task = …
override x.OnReceived(data) : Task =
Connection.Broadcast(data)
override x.OnDisconnected() : Task =
Hubs
Client (javascript)
var chat = $.connection.myChat
$.connection.hub.start();
chat.server.message(“Hello F#!!”);
chat.client.notify = function(text){
$(“#log”).append(“<li>” + text …
[<HubName(”myChat")>]
type MyChat() =
inherit Hub
member x.Message(text) : Task =
Clients.All.notify(text)
Hubs – Sending Message
Clients.All Clients.Group(groupName,
excludeConnectionIds)
Clients.AllExcept(connections) Clients.Groups(groupNames,
excludeConnectionIds)
Clients.Caller Clients.OthersInGroup(groupNam
e)
Clients.Client(connectionId) Clients.OthersInGroups(groupNa
mes)
Clients.Clients(connestionIds Clients.User(userName)
Clients.Others
SignalR ? Dynamic
SignalR & JavaScript
F# Type Provider for SignalR
Type provider giving a typed view of a .NET SignalR server Hub to client-
side code compiled from F# to JavaScript with FunScript.
Scale-out SignalR (backplane)
Web N-Tier Architecture
In the case of three-tier architecture
1)  Presentation tier
2)  Business logic tier
3)  Data storage tier
Problems:
1)  The project can become very difficult to
maintain
2)  Scalability as only one data base
handles read/write
CQRS pattern
Command Query Responsibility Segregation
CQRS is sort of data flow pattern
Filter Transform Buffer Enriched Persisted Broadcast
And
more…
CQRS benefits
¨  “Almost” infinite scalability
¤  Performance and scalability are always concerns when
handling a large volume of transactions over the internet
¨  Clear understanding what the application does
¨  Separation of concerns
.. scalability, simplicity, and maintainability…
How to handle UI-Eventual Consistency
Building a UI for a CQRS system is challenging
¨  The commands could complete fast
¨  The read model is eventually consistent
¨  The read of the data store may return stale results
Query
SignalR to replace Query
CQRS pattern
Command Query Responsibility Segregation
CQRS CAP
¨  This works when the user actually expects some sort of “background” work to happen, or that we present
this to the user in a meaningful way.
¨  But when doing CQRS, eventual consistency is an orthogonal choice. They are two completely separate
concerns. Going back to our new CQRS design:
¨  We have many choices here on what should be synchronous, and what should not. It can all be
synchronous, all be async, it’s just a separate decision.
¨  What I have found though that is if we build asynchronous denormalization in the back-end, but try to
mimic synchronous results in the front end, we’re really just choosing async where it’s not needed. Not in
all cases of course, but for most of the ones I’ve seen.
¨  Some async-sync mimicry I’ve seen includes:
¨  Using Ajax from the server to ping the read store to see if denormalization is “done”
¨  Using SignalR to notify the client when the denormalization is “done”
¨  Writing to the read store synchronously, but then allowing eventual consistency to fix any mistakes
SAGA
¨  A Saga is a distribution
of multiple workflows
across multiple systems,
each providing a path
(fork) of compensating
actions in the event that
any of the steps in the
workflow fails.
¨  “Sagas and persistence
¨  In general, a saga must be persistent
and persistence of the saga is a
typical responsibility of the bus. In
this regard, it might completely be
transparent to you if you don’t write
a bus class yourself. In the sample
Bus class, we simulated persistence
through an in-memory dictionary—
whereas, for example, NServiceBus
uses SQL Server. For persistence to
happen, it is key that you give a
unique ID to each saga instance.”
When to use CQRS
¨  In general, the CQRS pattern could be very valuable in situations when you have highly
collaborative data and large, multi-user systems, complex, include ever-changing business
rules, and delivers a significant competitive advantage of business. It can be very helpful
when you need to track and log historical changes.
¨  With CQRS you can achieve great read and write performance. The system intrinsically
supports scaling out. By separating read and write operations, each can be optimized.
¨  CQRS can by very helpful when you have difficult business logic. CQRS forces you to not
mix domain logic and infrastructural operations.
¨  With CQRS you can split development tasks between different teams with defined
interfaces.
¨  When not to use CQRS
¨  If you are not developing a highly collaborative system where you don't have multiple
writers to the same logical set of data you shouldn't use CQRS.
SignalR Stock Ticker
http://www.asp.net/signalr/overview/getting-started/tutorial-server-broadcast-with-signalr
The stock ticker application
represents of real-time
applications in which you want to
periodically "push," or broadcast,
notifications from the server to all
connected clients.
C# F# Diff
Lines of code 365 142 -62%
Demo Project
StockTicker Hub
Agent
Supervisor
Web API
[Post]
Command
SignalR
Validation Command
Publish
Command
Stock-Market
UpdateStocks
Open/Close MarketEvent
Store
Update UI SignalR Client
Actor
Actor
Actor
Actor Actor
Summary
F# is a great and
mature language for
Web Development
F# has built in features
to develop Fast and
Scalable Web App
F# |> RX |> SignalR
|> CQRS |>
Q & A ?
The tools we use have a profound (and devious!) influence on our thinking habits,
and, therefore, on our thinking abilities.
-- Edsger Dijkstra
References
¨  https://wizardsofsmart.wordpress.com
¨  http://www.todobackend.com
¨  http://funscript.info
Online resources
¨  www.fsharp.org Information & community
www.tryfsharp.org Interactive F# tutorials
How to reach me
https://github.com/rikace/FS-SignalR
http://meetup.com/DC-fsharp
@DCFsharp @TRikace
rterrell@microsoft.com
How to reach me
github.com/DCFsharp
meetup.com/DC-fsharp/
@DCFsharp
rterrell@microsoft.com

More Related Content

What's hot

Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
Daniel Egan
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
Stratio
 
Parallel Programming in .NET
Parallel Programming in .NETParallel Programming in .NET
Parallel Programming in .NET
SANKARSAN BOSE
 

What's hot (20)

Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
Xtend - better java with -less- noise
Xtend - better java with -less- noiseXtend - better java with -less- noise
Xtend - better java with -less- noise
 
Programming Paradigm & Languages
Programming Paradigm & LanguagesProgramming Paradigm & Languages
Programming Paradigm & Languages
 
The Joy Of Functional Programming
The Joy Of Functional ProgrammingThe Joy Of Functional Programming
The Joy Of Functional Programming
 
Something for Nothing
Something for NothingSomething for Nothing
Something for Nothing
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014JDT Embraces Lambda Expressions - EclipseCon North America 2014
JDT Embraces Lambda Expressions - EclipseCon North America 2014
 
VB.net
VB.netVB.net
VB.net
 
Insight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FPInsight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FP
 
Design Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The WorldDesign Patterns For 70% Of Programmers In The World
Design Patterns For 70% Of Programmers In The World
 
Eclipse and Java 8 - Eclipse Day India 2013
Eclipse and Java 8 - Eclipse Day India 2013Eclipse and Java 8 - Eclipse Day India 2013
Eclipse and Java 8 - Eclipse Day India 2013
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
 
Arquitectura hexagonal
Arquitectura hexagonalArquitectura hexagonal
Arquitectura hexagonal
 
Java script
Java scriptJava script
Java script
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Immutable data structures - A Primer
Immutable data structures - A PrimerImmutable data structures - A Primer
Immutable data structures - A Primer
 
C# Programming: Fundamentals
C# Programming: FundamentalsC# Programming: Fundamentals
C# Programming: Fundamentals
 
Parallel Programming in .NET
Parallel Programming in .NETParallel Programming in .NET
Parallel Programming in .NET
 
BCA IPU VB.NET UNIT-I
BCA IPU VB.NET UNIT-IBCA IPU VB.NET UNIT-I
BCA IPU VB.NET UNIT-I
 

Viewers also liked

Crime thriller pitch presentation AS Media
Crime thriller pitch presentation AS MediaCrime thriller pitch presentation AS Media
Crime thriller pitch presentation AS Media
hayleigh282
 
Lesson four events during the fitrah
Lesson four   events during the fitrahLesson four   events during the fitrah
Lesson four events during the fitrah
Ebrahim Ismail
 

Viewers also liked (20)

The New European PV Legislation: Issues and Challenges
The New European PV Legislation: Issues and ChallengesThe New European PV Legislation: Issues and Challenges
The New European PV Legislation: Issues and Challenges
 
Tahneek lesson 7
Tahneek   lesson 7Tahneek   lesson 7
Tahneek lesson 7
 
Using Social Media for Sales Success
Using Social Media for Sales SuccessUsing Social Media for Sales Success
Using Social Media for Sales Success
 
Trecho de "O livro das religiões"
Trecho de "O livro das religiões"Trecho de "O livro das religiões"
Trecho de "O livro das religiões"
 
Lesson 16 critically analyse the buhyara incident, battle of fujjar & the r...
Lesson 16   critically analyse the buhyara incident, battle of fujjar & the r...Lesson 16   critically analyse the buhyara incident, battle of fujjar & the r...
Lesson 16 critically analyse the buhyara incident, battle of fujjar & the r...
 
Learning the city powerpointfrom am v3
Learning the city powerpointfrom am v3Learning the city powerpointfrom am v3
Learning the city powerpointfrom am v3
 
2012 Outside-In Holiday Infographic
2012 Outside-In Holiday Infographic2012 Outside-In Holiday Infographic
2012 Outside-In Holiday Infographic
 
Lesson 14 - Life, Role and Death of Abu Talib
Lesson 14 - Life, Role and Death of Abu TalibLesson 14 - Life, Role and Death of Abu Talib
Lesson 14 - Life, Role and Death of Abu Talib
 
Crime thriller pitch presentation AS Media
Crime thriller pitch presentation AS MediaCrime thriller pitch presentation AS Media
Crime thriller pitch presentation AS Media
 
Lesson four events during the fitrah
Lesson four   events during the fitrahLesson four   events during the fitrah
Lesson four events during the fitrah
 
Lesson Two - Seerah
Lesson Two - Seerah Lesson Two - Seerah
Lesson Two - Seerah
 
Noelle Hurd, Ph.D., MPH - "Examining Natural Mentoring Relationships among Bl...
Noelle Hurd, Ph.D., MPH - "Examining Natural Mentoring Relationships among Bl...Noelle Hurd, Ph.D., MPH - "Examining Natural Mentoring Relationships among Bl...
Noelle Hurd, Ph.D., MPH - "Examining Natural Mentoring Relationships among Bl...
 
Presentaciones digitales. MPM
Presentaciones digitales. MPMPresentaciones digitales. MPM
Presentaciones digitales. MPM
 
Lesson five miracles
Lesson five   miraclesLesson five   miracles
Lesson five miracles
 
Lesson 20 - Rebuilding of the Ka'bah
Lesson 20 - Rebuilding of the Ka'bahLesson 20 - Rebuilding of the Ka'bah
Lesson 20 - Rebuilding of the Ka'bah
 
Lesson 17 second trip to syria and first encounter with sayyida khadija
Lesson 17  second trip to syria and first encounter with sayyida khadijaLesson 17  second trip to syria and first encounter with sayyida khadija
Lesson 17 second trip to syria and first encounter with sayyida khadija
 
Marketing Summary Report
Marketing Summary ReportMarketing Summary Report
Marketing Summary Report
 
Lareau_Slides
Lareau_SlidesLareau_Slides
Lareau_Slides
 
Connected Media Experiences
Connected Media ExperiencesConnected Media Experiences
Connected Media Experiences
 
Best Practices in Managing e-resources
Best Practices in Managing e-resourcesBest Practices in Managing e-resources
Best Practices in Managing e-resources
 

Similar to F# and SignalR for a FastWeb

The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz
 
Visual Studio .NET2010
Visual Studio .NET2010Visual Studio .NET2010
Visual Studio .NET2010
Satish Verma
 
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
HostedbyConfluent
 
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
OdessaJS Conf
 
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lightbend
 
Exploring SharePoint with F#
Exploring SharePoint with F#Exploring SharePoint with F#
Exploring SharePoint with F#
Talbott Crowell
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
hamzadamani7
 

Similar to F# and SignalR for a FastWeb (20)

F# on the Server-Side
F# on the Server-SideF# on the Server-Side
F# on the Server-Side
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
JAVASRIPT and PHP Basics# Unit 2 Webdesign
JAVASRIPT and PHP Basics# Unit 2 WebdesignJAVASRIPT and PHP Basics# Unit 2 Webdesign
JAVASRIPT and PHP Basics# Unit 2 Webdesign
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's Next
 
Visual Studio .NET2010
Visual Studio .NET2010Visual Studio .NET2010
Visual Studio .NET2010
 
Overview of VS2010 and .NET 4.0
Overview of VS2010 and .NET 4.0Overview of VS2010 and .NET 4.0
Overview of VS2010 and .NET 4.0
 
Compiler design Introduction
Compiler design IntroductionCompiler design Introduction
Compiler design Introduction
 
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for DevelopersMSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
 
Caerusone
CaerusoneCaerusone
Caerusone
 
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
 
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
 
ServerLess by usama Azure fuctions.pptx
ServerLess by usama Azure fuctions.pptxServerLess by usama Azure fuctions.pptx
ServerLess by usama Azure fuctions.pptx
 
Develop in ludicrous mode with azure serverless
Develop in ludicrous mode with azure serverlessDevelop in ludicrous mode with azure serverless
Develop in ludicrous mode with azure serverless
 
Programming Languages: some news for the last N years
Programming Languages: some news for the last N yearsProgramming Languages: some news for the last N years
Programming Languages: some news for the last N years
 
Infrastructure as code, using Terraform
Infrastructure as code, using TerraformInfrastructure as code, using Terraform
Infrastructure as code, using Terraform
 
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
 
Exploring SharePoint with F#
Exploring SharePoint with F#Exploring SharePoint with F#
Exploring SharePoint with F#
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
[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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 

F# and SignalR for a FastWeb

  • 1. Riccardo Terrell – Zurich F# UG F# and SignalR for a FastWeb The tools we use have a profound (and devious!) influence on our thinking habits, and, therefore, on our thinking abilities. — Edsger Dijkstra
  • 2. Agenda Why F# on the Web F# Magic SignalR and F# CQRS and F# Code & Code
  • 3. Goals - Plan of the talk F# is a great and mature language for Web Development F# has built in features to develop Fast and Scalable Web App F# |> RX |> SignalR |> CQRS |>
  • 4. Technology trends Mobile Claud computing Real Time notification Single Page Apps Big Data Scalable Maintanable & Readable Reliable & Testable Composable & Reusable Concurrent
  • 5. …F# and Functional Paradigm can help F# helps with the mission statement simple code for complex problem… F# great for scalability and concurrent ready F# play well together with Web Application Use function and composition as building block
  • 6. Why F# on the web? Really? Is functional programming and F# mostly targeted at scientific or financial domains? Is functional programming and F# just for Server Side computations? Is functional programming and F# mostly about algorithms and calculations?
  • 7. Why F# on the web? Succinct - F# is concise, readable and type-safe, for fast development of robust web solutions Reactive and Scalable - F# asynchronous programming simplifies scalable, reactive web programming, and Agent too! Fast - F# code execution is fast, using native code generation from scripted or project code Interoperable - F# interoperates seamlessly with languages such as C#, JavaScript and TypeScript, F# is JavaScript-ready through WebSharper and FunScript
  • 8.
  • 9. F# Type Providers on the Web ¤  JSON Type Provider ¤  CSV ¤  WSDL ¤  WMI ¤  Data Access – SQL and EF ¤  Funscript to Javascript ¤  And more, write your own Type provider IDE IntelliSense for Generated Types Compiler Type-Check Imported Types Compile using Type Provider
  • 10. F# Type Providers on the Web
  • 13. Asynchronous Workflows ¤  Software is often I/O-bound, it provides notable performance benefits n  Connecting to the Database n  Leveraging web services n  Working with data on disk ¤  Network and disk speeds increasing slower ¤  Not Easy to predict when the operation will complete (no- deterministic)
  • 14. ¨  Easy transition from synchronous ¤  Wrap in asynchronous workflow with the async keyword, use let! for async calls and add return ¤  No need of explicit callback ¤  Easy to debug ¨  Supports loops, recursion, exceptions, cancellation, resource management ¨  Operation complete in the same scope let  getLength  url  =          let  wc  =  new  WebClient()      let    data  =  wc.DownloadString(url)      data.Length       Anatomy of Async Workflows
  • 15. ¨  Easy transition from synchronous ¤  Wrap in asynchronous workflow with the async keyword, use let! for async calls and add return ¤  No need of explicit callback ¤  Easy to debug ¨  Supports loops, recursion, exceptions, cancellation, resource management ¨  Operation complete in the same scope let  getLength  url  =  async  {      let  wc  =  new  WebClient()      let    data  =  wc.DownloadString(url)      data.Length  }   Anatomy of Async Workflows
  • 16. ¨  Easy transition from synchronous ¤  Wrap in asynchronous workflow with the async keyword, use let! for async calls and add return ¤  No need of explicit callback ¤  Easy to debug ¨  Supports loops, recursion, exceptions, cancellation, resource management ¨  Operation complete in the same scope let  getLength  url  =  async  {      let  wc  =  new  WebClient()      let    data  =  wc.DownloadString(url)      return  data.Length  }   Anatomy of Async Workflows
  • 17. ¨  Easy transition from synchronous ¤  Wrap in asynchronous workflow with the async keyword, use let! for async calls and add return ¤  No need of explicit callback ¤  Easy to debug ¨  Supports loops, recursion, exceptions, cancellation, resource management ¨  Operation complete in the same scope let  getLength  url  =  async  {      let  wc  =  new  WebClient()      let!  data  =  wc.AsyncDownloadString(url)      return  data.Length  }   Anatomy of Async Workflows
  • 18. Asynchronous Workflows let  openFileAsynchronous  :  Async<unit>      async  {  use    fs  =  new    FileStream(@"C:Program  Files...,  …)                let    data  =  Array.create  (int  fs.Length)  0uy                let!    bytesRead  =  fs.AsyncRead(data,  0,  data.Length)                do    printfn  "Read  Bytes:  %i,  First  bytes  were:                        %i  %i  %i  ..."  bytesRead  data.[1]  data.[2]  data.[3]  }   ¤  Async defines a block of code we would like to run asynchronously ¤  We use let! instead of let n  let! binds asynchronously, the computation in the async block waits until the let! completes n  While it is waiting it does not block n  No program or OS thread is blocked
  • 19. F# MailboxProcessor – aka Agent ¨  F# really shines in the area of distributed computing ¤  Language features such as Async Workflow and MailboxProcessor (a.k.a. agent) open the doors for computing that focuses on message passing concurrency ¤  Scaling Up & Scaling Out easy to implement
  • 20. Concurrent Model Programming An Agent is an independent computational entity which contains a queue, and receives and processes messages It provides immutability and isolation (it enforces coarse-grained isolation through message-passing)
  • 22. When to use Rx http://www.introtorx.com/content/v1.0.10621.0/01_WhyRx.html
  • 23. F# to JavaScript - FunScript ¨  FunScript is Javascript compiler ¤  Write F# client-side code with full intellisense ¤  Leverage F# functional goodies that compiles in JS n  Higher Order functions n  Pattern Matching n  Type Inference
  • 24. Full functional Data-Structure Records Discriminated Union Tuples List Map Set seq .Net mutable Collections Array – Dictionary - List
  • 25. F# to JavaScript - FunScript ¨  F# unique Features ¤  Async Workflow ¤  Reactive Extensions ¤  Type Providers ¤  Computation Expression
  • 26. F# and MVC - Web Api WPF Android iPad Pc Win Os iPhone Mac Web API
  • 27. F# and MVC - Web Api
  • 28. F# Magic in review TypeProvider Function Composition - ROP Async Workflow MailboxProcessor – aka Agent Reactive Extensions FunScript Full integration with Asp.Net MVC & Web API
  • 29. RX the Dual of IEnumerable http://en.wikipedia.org/wiki/Dual_(category_theory) Reversing arrows The input becomes output and <->
  • 31. When to use Rx http://www.introtorx.com/content/v1.0.10621.0/01_WhyRx.html
  • 35. Why SignalR? … the real questions are ¨  When the Web users want their Data? ¨  When the Web user want the latest info?
  • 37. What can SignalR do? SignalR can be used to add any sort of "real-time" web functionality to your application… ¨  Anything that needs live data ¤  Chat Room application ¤  Broadcasting (Stock Tickers, Live Scores…) ¤  Internet Games ( http://shootr.signalr.net/default.aspx# ) ¤  Social Media ¤  Collaborative Apps
  • 38. SignalR levels of abstraction Hubs Persistent Connection Transports Internet protocols Abstractionlevel WebSockets Server-Sent Events Long polling Forever frame
  • 39. Persistent Connection Client (javascript) var conn = $.connection(“myChat”); conn.start(); conn.send(“Hello F#!!”); conn.receive(function(text){ $(“#log”).append(“<li>” + text … type MyChat() = inherit PersistentConnection() override x.OnConnected() : Task = … override x.OnReceived(data) : Task = Connection.Broadcast(data) override x.OnDisconnected() : Task =
  • 40. Hubs Client (javascript) var chat = $.connection.myChat $.connection.hub.start(); chat.server.message(“Hello F#!!”); chat.client.notify = function(text){ $(“#log”).append(“<li>” + text … [<HubName(”myChat")>] type MyChat() = inherit Hub member x.Message(text) : Task = Clients.All.notify(text)
  • 41. Hubs – Sending Message Clients.All Clients.Group(groupName, excludeConnectionIds) Clients.AllExcept(connections) Clients.Groups(groupNames, excludeConnectionIds) Clients.Caller Clients.OthersInGroup(groupNam e) Clients.Client(connectionId) Clients.OthersInGroups(groupNa mes) Clients.Clients(connestionIds Clients.User(userName) Clients.Others
  • 44. F# Type Provider for SignalR Type provider giving a typed view of a .NET SignalR server Hub to client- side code compiled from F# to JavaScript with FunScript.
  • 46. Web N-Tier Architecture In the case of three-tier architecture 1)  Presentation tier 2)  Business logic tier 3)  Data storage tier Problems: 1)  The project can become very difficult to maintain 2)  Scalability as only one data base handles read/write
  • 47. CQRS pattern Command Query Responsibility Segregation
  • 48. CQRS is sort of data flow pattern Filter Transform Buffer Enriched Persisted Broadcast And more…
  • 49. CQRS benefits ¨  “Almost” infinite scalability ¤  Performance and scalability are always concerns when handling a large volume of transactions over the internet ¨  Clear understanding what the application does ¨  Separation of concerns .. scalability, simplicity, and maintainability…
  • 50. How to handle UI-Eventual Consistency Building a UI for a CQRS system is challenging ¨  The commands could complete fast ¨  The read model is eventually consistent ¨  The read of the data store may return stale results
  • 51. Query
  • 53. CQRS pattern Command Query Responsibility Segregation
  • 54. CQRS CAP ¨  This works when the user actually expects some sort of “background” work to happen, or that we present this to the user in a meaningful way. ¨  But when doing CQRS, eventual consistency is an orthogonal choice. They are two completely separate concerns. Going back to our new CQRS design: ¨  We have many choices here on what should be synchronous, and what should not. It can all be synchronous, all be async, it’s just a separate decision. ¨  What I have found though that is if we build asynchronous denormalization in the back-end, but try to mimic synchronous results in the front end, we’re really just choosing async where it’s not needed. Not in all cases of course, but for most of the ones I’ve seen. ¨  Some async-sync mimicry I’ve seen includes: ¨  Using Ajax from the server to ping the read store to see if denormalization is “done” ¨  Using SignalR to notify the client when the denormalization is “done” ¨  Writing to the read store synchronously, but then allowing eventual consistency to fix any mistakes
  • 55. SAGA ¨  A Saga is a distribution of multiple workflows across multiple systems, each providing a path (fork) of compensating actions in the event that any of the steps in the workflow fails. ¨  “Sagas and persistence ¨  In general, a saga must be persistent and persistence of the saga is a typical responsibility of the bus. In this regard, it might completely be transparent to you if you don’t write a bus class yourself. In the sample Bus class, we simulated persistence through an in-memory dictionary— whereas, for example, NServiceBus uses SQL Server. For persistence to happen, it is key that you give a unique ID to each saga instance.”
  • 56. When to use CQRS ¨  In general, the CQRS pattern could be very valuable in situations when you have highly collaborative data and large, multi-user systems, complex, include ever-changing business rules, and delivers a significant competitive advantage of business. It can be very helpful when you need to track and log historical changes. ¨  With CQRS you can achieve great read and write performance. The system intrinsically supports scaling out. By separating read and write operations, each can be optimized. ¨  CQRS can by very helpful when you have difficult business logic. CQRS forces you to not mix domain logic and infrastructural operations. ¨  With CQRS you can split development tasks between different teams with defined interfaces. ¨  When not to use CQRS ¨  If you are not developing a highly collaborative system where you don't have multiple writers to the same logical set of data you shouldn't use CQRS.
  • 57. SignalR Stock Ticker http://www.asp.net/signalr/overview/getting-started/tutorial-server-broadcast-with-signalr The stock ticker application represents of real-time applications in which you want to periodically "push," or broadcast, notifications from the server to all connected clients. C# F# Diff Lines of code 365 142 -62%
  • 58. Demo Project StockTicker Hub Agent Supervisor Web API [Post] Command SignalR Validation Command Publish Command Stock-Market UpdateStocks Open/Close MarketEvent Store Update UI SignalR Client Actor Actor Actor Actor Actor
  • 59.
  • 60. Summary F# is a great and mature language for Web Development F# has built in features to develop Fast and Scalable Web App F# |> RX |> SignalR |> CQRS |>
  • 61. Q & A ? The tools we use have a profound (and devious!) influence on our thinking habits, and, therefore, on our thinking abilities. -- Edsger Dijkstra
  • 63. Online resources ¨  www.fsharp.org Information & community www.tryfsharp.org Interactive F# tutorials
  • 64. How to reach me https://github.com/rikace/FS-SignalR http://meetup.com/DC-fsharp @DCFsharp @TRikace rterrell@microsoft.com
  • 65. How to reach me github.com/DCFsharp meetup.com/DC-fsharp/ @DCFsharp rterrell@microsoft.com