TechEd NA 2014 –Building Real-Time Applications with ASP.NET SignalR

TechEd North America 2014, Houston
Building Real-Time Applications with ASP.NET SignalR – Brady Gaster

Day 3, 14 May 2014, 8:30AM-9:45AM (DEV-B416)

Disclaimer: This post contains my own thoughts and notes based on attending TechEd North America 2014 presentations. Some content maps directly to what was originally presented. Other content is paraphrased or represents my own thoughts and opinions and should not be construed as reflecting the opinion of either Microsoft, the presenters or the speakers.

Executive Summary—Sean’s takeaways

  • SignalR is a mechanism for real-time communication between web server and client(s)
  • You code to abstraction that is unaware of capabilities on either server or clients
  • SignalR automatically uses the most appropriate protocol to accomplish real-time
  • Basic idea
    • Something happens in one browser (or on server) and you can inform all current web clients immediately
  • In action
    • Move rectangle around in one browser and you immediately see it moved in all other browsers
  • New Browser Link feature implemented using SignalR
  • Practical applications
    • Web Chat, Hit Counter
    • Real-Time display of some central data store

Full video

Brady Gaster – Program Manager, Azure SDK & Visual Studio Web Tools Publishing, Microsoft

@bradygaster
bradyg@microsoft.com

www.bradygaster.com

Main web page for SignalR – www.asp.net/signalr

https://github.com/signalr/signalr

When he first saw SignalR, “everything changed”

  • Always open source

Agenda

  • What is SignalR
    • After you see it, everything starts looking like a nail
    • For real-time HTTP
    • Might lose 1/100 messages
    • Not for pub-sub with queues—not for durable messaging
    • Don’t replace all your REST APIs with SignalR
    • Browser Link uses SignalR
  • Hub Class & jQuery Plugin
  • SignalR and AngularJS
  • SignalR .NET Client
  • Calling SignalR Hub methods on the server
  • Authorization with SignalR
  • Scaling SignalR in web farms
  • Self-hosting SignalR using OWIN

SignalR is an abstraction that intelligently decides how to enable real-time over HTTP

  • But HTTP is stateless protocol, not really designed for real-time
  • You write to an abstraction

Demo – SignalR in action – SignalR Hub and jQuery plugin

  • New project, ASP.NET Web app
  • HitCounter app
  • Install NuGet pkg – Manage NuGet, “Microsoft ASP.NET SignalR”
    • If you want SignalR in web app
    • .NET Client – for server-side
  • Readme.txt shows up
    • Uses Owin, hosted in Owin, no global.asax stuff
    • “Map your hubs”
  • Add file – “OWIN Startup class”
    • App.MapSignalR(); — how to route request to hub
  • Add | SignalR Hub Class
    • HitCounterHub : Hub
    • HubName “hitCounter”
    • Public method RecordHit
      • Add to hit count
      • this.Clients.All (or Caller, or Others)
      • .onHitRecorded
  • Hub/Spoke mode
  • “Once I learned how to use SignalR, dynamic made a lot more sense”
  • Client-side web page
    • Add in jQuery, jQuery.signalR
  • Javascript, function
    • Create connection with $.hubConnection
    • createHubProxy(‘hitCounter’)
    • hub.on(‘onHitRecorded’) => callback for when hub calls this method
    • Define function that updates counter ** scode 8:49 **
    • Start connection and then invoke method on hub
  • SignalR allows sending message out of the client

Demo – Know when clients disconnect

  • In Hub class, define OnDisconnected
  • Server will know when something disconnected

SignalR on old-school servers & clients

  • Old-school—polling
  • SignalR will actually do polling on older browsers that don’t support newer constructs that allow event handling
  • HTML Client starts up, asks server if it can do real-time, web sockets

SignalR built almost entirely on async, so won’t block threads back to server

  • E.g. stress testing team/tool
  • SignalR, first thing that fell down was the network card

Demo – Move Shape

  • Moving shape in one browser, you see it move in all browsers
  • URL shows “foreverFrame” in URL
  • SignalR figured out best mechanism
  • Then enable web sockets
    • Now no foreverFrame in URL, but using web sockets

Demo – SignalR with Angular

  • jQuery and Angular play well together
  • Trace hub – no code
  • Connect trace hub to listener
  • Create Angular factory, signalRService
  • Client dumps out trace messages as 2nd browser hits pages

Demo – Using SignalR’s Native .NET Client – MoveShape with Kinect

  • Daemon on server, pulls in SignalR.Client
  • JavaScript and .NET clients have parity
  • HubConnection created on server
  • Console app that patches Kinect into SignalR on the server
  • Moves shape with his hand

Demo – Calling a SignalR Hub from the Server

  • Real-time location tracking
  • As people connect, pins show up on the map in real-time
  • As people hit site, it’s calling server to add location info
  • GetHubContext<MappingHub> – gives instance of sub back to client, so that he can call methods on it

Demo – Authorization with SignalR

  • You’ll generally want to authorize clients
  • Server calls client to say “hello”
  • Put Authorize attribute on hub—can’t use hub unless logged in
  • You only want to let people use hub if they are authorized

Hubs are server-bound, so you’ll need to use a backplane if you’re running a web farm

  • E.g. if you’re running multiple instances on Azure

How do Backplanes Work?

  • By default, messages back out to client only go to clients on that server
  • Backplane
    • Redis or SQL
  • Client requests go all the way to backplane, then out to all web servers

Demo – Using a SignalR Backplane – Chat App

  • In Startup, SetupScaleOut
  • DependencyResolver.UseSqlServer
  • Same site hosted on two instances of IIS
  • Enable backplane, hit different servers from different browsers
  • Now messages show up in both browsers

Demo – Self-Hosting SignalR Using OWIN

  • Bring OWIN self-hosting and SignalR self-hosting (NuGet packets)
  • Host in .exe
  • SignalR.SelfHost package
  • app.UseCors (authorization)
    • Prior to MapSignalR

TechEd NA 2014 – ASP.NET: Building Web Applications Using ASP.NET and Visual Studio

TechEd North America 2014, Houston
ASP.NET: Building Web Applications Using ASP.NET and Visual Studio – Scott Hanselman, Scott Hunter
(Calling themselves — The “Lesser” Scotts, in a very gracious nod to the greatness of Scott Guthrie)

Day 1, 12 May 2014, 3:00PM-4:15PM (DEV-B213)

Disclaimer: This post contains my own thoughts and notes based on attending TechEd North America 2014 presentations. Some content maps directly to what was originally presented. Other content is paraphrased or represents my own thoughts and opinions and should not be construed as reflecting the opinion of either Microsoft, the presenters or the speakers.

Executive Summary—Sean’s takeaways

  • “One ASP.NET” initiative
    • Can mix and match technologies
    • Don’t have to make the “right” choice when doing File|New
  • In general, lots of great new features in ASP.NET, like:
    • New Identity system, with two-factor authentication
    • Azure Server Explorer in Visual Studio
    • Browser Link, pushing browser-based changes back into Visual Studio
    • Async in Entity Framework
  • Coming soon
    • Project template support for 3rd party libraries like Angular

Full video

Scott Hanselman / Scott Hunter

Hanselman now doing new video podcast – Friday.azure.com – small 10 min podcasts w/devs from Azure team

ASP.NET and Web Tools, Visual Studio 2013.2

ASP.NET vs. Web Tools

  • ASP.NET – think of GAC

One ASP.NET

  • Sites / Services
  • Sites
    • Web Forms
    • Web Pages
    • Single Page Apps
    • MVC
  • Services
    • Web API
    • SignalR
  • All on top of ASP.NET

You don’t have to choose up front (File | New)

  • Can add stuff later, e.g. MVC, Web API
  • E.g. add MVC controller to Web Forms

MVP program changed

  • Old: loudest, wrote most books, blogs
  • Now: Can be MVP based solely on open source contributions

Cadence – every 6 mos

Fall 2014 – Focus – Modern Web

  • Support for various 3rd party .js libraries
  • E.g. jQuery, Angular
  • Will support all these within project templates

From Web Tools “Labs”

  • Release every 2 mos
  • Web Essentials (VS extension)
  • Vswebessentials.com

New stuff, Oct 2013

  • General
    • New Identity system
    • Templates based on Bootstrap **
  • One ASP.NET
    • One single project
  • Azure SDK
    • Azure Server Explorer – Azure features from within VS
  • Web API
    • CORs
    • Attribute Routing – brings routing into controller
  • MVC
    • Attribute Routing
  • Entity Framework
    • Async, Stored Procs, Resiliency
    • Azync – will be faster ** very important, available across sub-systems
      • E.g. avoid blocking calls by doing async when doing network access
      • User doesn’t know, code doesn’t know
  • Visual Studio
    • New HTML Editor
    • Live Browser Link + Extensibility
    • AngularJS Class Intellisense (and Bootstrap)

May 2014

  • One ASP.NET
    • Scaffolding
    • Two-factor Auth
    • Account lockout, confirmation, reset, et.c
  • SignalR
    • Xamarin, No jQuery, Android
  • Web API
    • BSON formatter (binary JSON)
    • Improved attribute routing
  • MVC
    • Better bootstrap scaffolding
  • Entity Framework
    • EF Power Tools
    • Reverse engineer DB to Code First

Roslyn

  • New language features
  • Code analysis, custom diagnostics

ASP.NET CodeDOM provider

  • Use new features in ASP.NET applications
  • Improve startup time for large applications

Azure stack

  • Azure Storage
  • VMs (IaaS)
  • Worker Roles

Web Sites vs. Virtual Machines

  • VMs – You manage it – IaaS
  • Web Sites – PaaS

Bitly.com/TECHED2014WebTools

TechEd NA 2014 – Create Applications that Span Devices and Services

TechEd North America 2014, Houston
The Microsoft Development Platform: Create Applications that Span Devices and Services – Scott Hanselman 

Day 1, 12 May 2014, 11:00AM-12:00PM (FDN05)

Disclaimer: This post contains my own thoughts and notes based on attending TechEd North America 2014 presentations. Some content maps directly to what was originally presented. Other content is paraphrased or represents my own thoughts and opinions and should not be construed as reflecting the opinion of either Microsoft, the presenters or the speakers.

Executive Summary—Sean’s takeaways

  • For developers, we need to focus on Cloud + Mobile
  • Very easy to debug/test using Azure
    • Attach Visual Studio debugger to web app running in Azure
  • Microsoft Azure Mobile Services – turnkey back-end solution for mobile apps
  • Modular focus – ability to pick the stuff you want, leave the stuff behind that you don’t
    • Choice
    • “Bring your own” – platform, tools, framework
  • Cross-platform – use Xamarin to get breadth
    • Lots of code reuse across platforms
    • Tools help you with this
  • Native vs. Web app
    • Native is best experience
    • Web app is “shortest path”

Full video

Scott Hanselman – Microsoft

Scott

What we are hearing from you

  • Devs more important than ever
  • Cross-platform required

Hearing

Developer needs

  • Optimize for cloud / devices
  • Hybrid

Today’s Cloud/Mobile

Cloud scenarios

Dev & Test in the cloud

  • Old world—process took couple week
  • Plug stuff into Azure

Demo – VMs

03

VM demo

  • Private network
  • Can quickly fire up VM in virtual network
  • Fire up Win 7 VMs in Azure for dev/test
  • Can VPN into VM in cloud
  • Remote into the machine
  • E.g. testing WPF app on Win 7 VM

Back in Visual Studio – Rt-click, Enable Debugging

  • Attach, set breakpoint
  • Back in VM, exercise app
  • Complete remote debugging session in Visual Studio
  • You only pay for VM while it’s provisioned

04

Web Apps in the cloud

  • Standards based
  • Highly interactive apps
  • Enterprise complexity

Browse With – various browsers

  • Can push Refresh out to multiple browsers
  • Ctrl-Design, hover around browser
  • Modify in Design mode in browser, updated in real-time in code
  • Browser Link

File New project, host in web

Hybrid Apps

  • Maybe want parts of an app on the public internet, part in private network
  • BizTalk Hybrid Connections (preview)
  • Also
    • Virtual network et al

BizTalk Hybrid Connections

  • Tunnel to corp network to get resources

Demo – Hybrid Connections

  • Web site is connection to a specific host (HP laptop)
  • E.g. connection string is hooked to the local machine
  • Service on local machine – Hybrid Connection Manager

Mobile Apps in the cloud

  • Microsoft Azure Mobile Services
  • Back-end API running in cloud
  • Turnkey backend for Mobile Services
  • Extend internal web apps to mobile devices
  • Powerful client-side library for multiple devices
  • Offline sync support
  • Available on any platform

Demo – Managing web API on Azure

  • Supports JSON and .NET APIs
  • Postman, Chrome extension – RESTful client

Web API in Azure:

Using Postman to test Mobile Service Web API:

Future of .NET

  • .NET vNext
  • Multi-purpose
    • Client –
  • Specialized
    • Device optimized – for client
    • Web and service – Cloud optimized
  • Side by side compatibility, each app has its own version of the CLR
    • Break apart Framework, just use the parts that you need
    • Small footprint
  • Common stuff
    • “Entity Framework” everywhere
    • All open source and all in .NET Foundation

ASP.NET vNext and the Modern Web

  • Modular – swap out stuff you don’t like
  • Seamless transition from on-premises to cloud
  • Open Source with Contributions
  • Faster development cycle
  • Choose Editors and Tools
  • Cross-platform


New project, ASP.NET vNext application

  • Nested references, can pull stuff out
  • Project system changing
    • Unified Nugets and References
    • Bring in packages by just typing
  • Run the app
  • Go into controller – C# code
    • Just type in code, don’t do build step, then refresh browser and stuff changes
  • No DLLs in \bin folder
  • With Roslyn, just do everything in memory, doesn’t store bits to DLL
    • Code/refresh/repeat
  • Pick specific packages in NuGet that you want
    • As opposed to installing .NET on local machine
    • Makes it easier to try new stuff without breaking old apps
  • Looking at various .nupkg builds, each of which is some subset of .NET Framework

Demo – Visitors App –

  • Self-hosted, no IIS, run hosting environment in command line
  • Do same app on OS X, ASP.NET running in command line on Mac, web site hits local service

ASP.NET vNext Summary

  • Choice
  • MVC, Web API, Web Pages 6, SignalR 3, EF 7
  • SPS: Entity Framework still a first-class citizen

Cross-platform mobile development – Client

Multi-device approaches

  • .NET – rich experiences
    • Use Xamarin to get breadth
  • Coming from HTML side
    • Hybrid apps to get better richer experience

Windows Store Apps

  • Universal Windows apps
  • .NET Native

Demo – Universal App demo

  • Shared module in universal app – ViewModels, resources, etc.
  • Some Views shared, some views custom

Run Universal App

  • Win Phone emulator, Win 8 tablet
  • Debug Windows Store apps on your machine, RDPs into simulator
  • Win Phone – app running on phone

.NET in Android, iOS devices

  • Native mobile apps
    • Full access to device features
    • High flexibility and customization per device
    • Best US and performance in devices
  • Xamarin
    • Microsoft/Xamarin technical and
      business partnership
    • Visual Studio and C# capabilities fully available
    • Share app logic code across device platforms

Xamarin demo

  • Same app on Android and iOS
  • Android app can use shared component from universal project
  • Run app on Android tablet (Samsung Galaxy Fab?)
  • Remote debugging on physical tablet
  • “Android app that looks like an Android app” – on tablet, native
  • Then run the app on an Android phone and on iPad

“Native cross-platform mobile development”

Cordova tooling in Visual Studio

  • Hybrid-HTML apps
    • Natural path for web devs targeting devices
    • Shortest path for cross-platform mobile
  • New Cordova tooling in Visual Studio
    • Multi-device Hybrid Apps for Visual Studio
    • Hybrid apps
    • Flexibility to use any JavaScript framework
    • Scale to complex Enterprise apps through optional TypeScript support
    • End-to-end dev workflow included

Visual Studio benefits

  • File New Project – now have Android, iOS, F#, Python, Node,
  • Can start VMs from Visual Studio, attach to debuggers
  • Fire up VMs, make web sites, deploy
  • Bottom line – amazing power to developer

Demo – Hybrid App, Cordova tooling

  • Devices listed in Device dropdown in Visual Studio
  • “Ripple” support
  • Debug Cordova from Visual Studio

Summary

  • Providing the best end-to-end development experience
    • Platform
    • Framework
    • Tools
  • On our terms
    • Bring your own in each area

It’s a WPF World, part 2

Let me continue my ramble about Microsoft technologies leading up to WPF.  Last time, I ended by talking about the .NET technologies and why I think they are so important.  .NET has become the de facto standard for developing applications for the Windows platform (thick clients).  And although ASP.NET likely doesn’t have nearly as big a chunk of market share as Windows Forms, it feels like the WISA stack (Windows, IIS, SQL Server, ASP.NET) is gradually overtaking the LAMP stack (Linux, Apache, MySQL, PHP).  And with the rise of RIAs (Rich Internet Applications), ASP.NET Ajax will likely encourage the continued adoption of the ASP.NET technologies.

Going back to my list of the most important benefits of the .NET world from last time, I realized that I’d like to add a final bullet item.  (In the list–what’s so special about .NET):

  • Programmer Productivity — with things like intellisense and code snippets in Visual Studio, you can be incredibly productive, whether working in Win Forms or ASP.NET

I make the claim about productivity without having had experience with other development environments (at least since doing OWL development with Borland tools).  But the rise in productivity is true even just of Microsoft tools.  They just continue to get better and better.  And though “real programmers” might pooh-pooh all this intellisense nonsense in favor of hand coding in Textpad, I have to believe that even these guys would be more productive if they truly leveraged the tools.

When .NET first came out, I remember reading the marketing materials and being a little misled about where ASP.NET fit into things.  It seemed like Microsoft was touting convergence of Windows vs. web development, by talking up the similarities of the dev experience, working in Windows Forms vs. Web Forms.  Developing with ASP.NET was ostensibly very similar to developing Win Forms applications–you started with an empty design surface, dragged visual controls onto it, and double-clicked to bring up an editor where you wrote your code-behind.  (Nevermind that this model encouraged low quality architectures as people wrote monolithic chunks of event handler code–perpetuating bad habits that we learned with VB6).

But the web model was still very, very different from the thick client model.  On Windows, we were still working with an event-driven model, using the same old Windows message loop that we’d always used.  But users interact with a web-based interface in a completely different way.  We used server-side controls in ASP.NET to hide some of the complexity, but we were still just delivering a big glob of HTML to the client and then waiting for a new HTTP request.

The ASP.NET development environment also felt a bit kludgy.  I remember being a bit dismayed when I wrote my first ASP.NET application.  In the classic Win Forms development environment, there were two separate views of your application, where a developer lived–the design surface and the code behind.  The ASP.NET environment has three–the design surface, the code behind, and the HTML content.  So now instead of a developer jumping back and forth between two views, you end up jumping around in all three.

Spoiler–this web application architecture gets a lot cleaner with Silverlight 2.0.  There seems to be actual convergence between thick vs. thin clients as we use WPF for thick clients, Silverlight 2.0 for thin.  But more on that later.

So along comes WPF (Windows Presentation Foundation) and XAML (Extensible Application Markup Language).

I remember when I first read about XAML and WPF (Avalon at the time).  My first reaction was to be mildly frustrated.  At first glance, XAML seemed to be an arbitrary switch to a new syntax for defining GUIs.  And it seemed cryptic and unnecessary.  In the effort to be able to define a user interface declaratively rather than procedurally, it looked like we were ending up with something far messier and garbled than it needed to be.  It felt much easier to understand an application by reading the procedural code than by trying to make sense of a cryptic pile of angle brackets.

But I’ve come to realize that the switch to defining GUIs declaratively makes a lot of sense.  With XAML, thick clients move a bit closer to web applications, architecturally–the GUI is built from a static declaration of the UI (the XAML), a rendering engine, and some code behind.  And the layout of a user interface (rather than the behavior) is implicitly static, so it makes sense to describe it declaratively.  [As opposed to Windows Installer technology, which converts the dynamics of the installation process to something declarative and ends up being far messier].

Why does it make sense to separate the markup from the code like this?

  • Architecturally cleaner, separating the what (XAML declaraction of GUI) from the how (code-behind).  (Separating the Model from the View)
  • Enables broad tool support–tools can now just read from and write to XAML, since the GUI is now defined separately from the application itself.  (Enabling separate tools for designers/devs, e.g. Expression Blend and Visual Studio).
  • Cleaner for web apps — because we can now serialize a description of the GUI and send it across the wire.  This just extends the ASP.NET paradigm, using a similar architecture, but describing a much richer set of elements.

Another of my earlier reactions to XAML was that it was just a different flavor of external resource (.resx) files.  It looked similar–using angle brackets to describe GUI elements.  But XAML goes far beyond .resx files.  Resource files are used to externalize properties of UI controls that are potentially localizable.  E.g. Control sizes, locations and textual elements.  But the structure is flat because a resource file is nothing more than a big collection of keyword/value pairs.  Nothing can be gleaned about the structure of the UI itself by looking at the .resx file.  XAML, on the other hand, fully describes the UI, hierarchically.  It is far more than a set of properties, but it is logically complete, in that it contains everything required to render the GUI.

XAML is a big part of what makes WPF so powerful.  But there are a number of other key features that differentiate WPF from Windows Forms.

  • Totally new rendering engine for the GUI, based on Direct3D.  This enables better performance in rendering of the GUI, because everything in your GUI is described as 3D objects.  So even apparent 2D user interfaces can take advantage of hardware acceleration on the graphics card.  [The new NVidia GT200 GPU has 1.4 billion transistors, compared with original Core 2 Duo chips, which were in the neighborhood of 300 million].
  • Vector graphics.  The GUI is now entirely defined in vector graphics, as opposed to bitmapped/raster.  This is huge, because it means that you can define the GUI geometry indepedent of the target machine’s screen resolution.  This should mean–no more hair-pulling over trying to test/optimize at various screen resolutions and DPI settings.  (Gack)!
  • Bringing other APIs into the .NET fold.  E.g. 3D, video, and audio are now accessible directly from the .NET Framework, instead of having to use APIs like DirectX.
  • Focus on 3D graphics.  All of the above technologies just make it easier to develop stunning 3D graphical user experiences.  Powerful/cheap graphics hardware has led to 3D paradigms like Apple’s “cover flow” showing up more and more often in the average user interface.  (Battleship Grey, you will not be missed))

So where does WPF fit into the rest of the .NET world?  Is WPF a complete replacement for Windows Forms?

Adopting WPF will not be nearly as big a learning curve as adopting .NET was, originally.  WPF is a full-fledged citizen of the .NET world, existing as a series of .NET namespaces.  So .NET continues to be the premiere Microsoft development technology.

WPF is definitely a replacement for Windows Forms.  It is the new presentation layer, meant to be used for creation of new Windows-based applications (thick clients).  Microsoft is probably hesitant to brand WPF purely as a Windows Forms replacement, not wanting to dismay development shops that have invested a lot in learning .NET and Windows Forms.  But it’s clearly the choice for new Windows-based UI development, especially as the number of WPF controls provided by the tools, and shipped by 3rd party vendors, increases.

WPF is also highly relevant to web development (thin clients).  Silverlight 2 allows a web server to deliver browser-based RIAs containing a subset of the widgets found in WPF.  (Silverlight 2 used to be called Windows Presentation Foundation/Everywhere).  With WPF and Silverlight, Windows and web development are definitely converging.

So we clearly now live in a WPF world.  WPF will rapidly become more widely adopted, as it is used for more and more line-of-business applications, as well as serving as the underlying engine for the new Silverlight 2 RIAs that are starting to appear.  And the best news is that we also still live in a .NET world.  We get all of the .NET goodness that we’ve learned to love, with WPF being the shiniest new tool in our .NET toolbox.