Websockets vb.net example signalR2
Account Home | Help | Blog | Contact us | Log Out


Welcome to Kbytes > Articles

Websockets vb.net example signalR2

Posted By: siteadmin on 29/11/2018 18:52:00

Vb.net is not well supported in terms of signalR demos.  Here you can find a working solution for a version of Microsoft's SignalR demo in c#

You need an Owin Startup Class

Imports System
Imports System.Threading.Tasks
Imports Microsoft.Owin
Imports Owin


Namespace SignalR.StockTicker
    Public Class Startup
        Public Sub Configuration(ByVal app As IAppBuilder)
            app.MapSignalR()
        End Sub
    End Class
End Namespace

The Stock.vb contains some properties of company stock to play around with

Imports System

Public Class Stock
        Private _price As Decimal
        Public Property Symbol As String

        Public Property Price As Decimal
            Get
                Return _price
            End Get
            Set(ByVal value As Decimal)

                If _price = value Then
                    Return
                End If

                _price = value

                If DayOpen = 0 Then
                    DayOpen = _price
                End If
            End Set
        End Property

        Public Property DayOpen As Decimal

        Public ReadOnly Property Change As Decimal
            Get
                Return Price - DayOpen
            End Get
        End Property

        Public ReadOnly Property PercentChange As Double
            Get
                Return CDbl(Math.Round(Change / Price, 4))
            End Get
        End Property
    End Class

The StockTicker.html file contains the css, the html table for the stock, and the references to SignalR2 and jquery

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>ASP.NET SignalR Stock Ticker</title>
    <style>
        body {
            font-family: 'Segoe UI', Arial, Helvetica, sans-serif;
            font-size: 16px;
        }
 
        #stockTable table {
            border-collapse: collapse;
        }
 
            #stockTable table th, #stockTable table td {
                padding: 2px 6px;
            }
 
            #stockTable table td {
                text-align: right;
            }
 
        #stockTable .loading td {
            text-align: left;
        }
    </style>
</head>
<body>
    <h1>ASP.NET SignalR Stock Ticker Sample</h1>
 
    <h2>Live Stock Table</h2>
    <div id="stockTable">
        <table border="1">
            <thead>
                <tr><th>Symbol</th><th>Price</th><th>Open</th><th>Change</th><th>%</th></tr>
            </thead>
            <tbody>
                <tr class="loading"><td colspan="5">loading...</td></tr>
            </tbody>
        </table>
    </div>
 
 
 
    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="/Scripts/jquery-3.3.1.min.js"></script>
    <!--Reference the SignalR library. -->
    <script src="/Scripts/jquery.signalR-2.3.0.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="/signalr/hubs"></script>
    <!--Reference the StockTicker script. -->
    <script src="StockTicker.js"></script>
</body>
</html>
 


 

 

Stockticker.js contains the JQuery to update the stockprices.

// A simple templating method for replacing placeholders enclosed in curly braces.
if (!String.prototype.supplant) {
    String.prototype.supplant = function (o) {
        return this.replace(/{([^{}]*)}/g,
            function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            }
        );
    };
}

$(function () {

    var ticker = $.connection.stockTickerMini, // the generated client-side hub proxy
        up = '?',
        down = '?',
        $stockTable = $('#stockTable'),
        $stockTableBody = $stockTable.find('tbody'),
        rowTemplate = '

{Symbol}{Price}{DayOpen}{Direction} {Change}{PercentChange}';

    function formatStock(stock) {
        return $.extend(stock, {
            Price: stock.Price.toFixed(2),
            PercentChange: (stock.PercentChange * 100).toFixed(2) + '%',
            Direction: stock.Change === 0 ? '' : stock.Change >= 0 ? up : down
        });
    }

    function init() {
        ticker.server.getAllStocks().done(function (stocks) {
            $stockTableBody.empty();
            $.each(stocks, function () {
                var stock = formatStock(this);
                $stockTableBody.append(rowTemplate.supplant(stock));
            });
        });
    }

    // Add a client-side hub method that the server will call
    ticker.client.updateStockPrice = function (stock) {
        var displayStock = formatStock(stock),
            $row = $(rowTemplate.supplant(displayStock));

        $stockTableBody.find('tr[data-symbol=' + stock.Symbol + ']')
            .replaceWith($row);

        console.log(stock);

    }

    // Start the connection
    $.connection.hub.logging = true;
    $.connection.hub.start().done(init);

});

StockTicker.vb is the serverside code for updating the HTML table

Imports System
Imports System.Collections.Concurrent
Imports System.Collections.Generic
Imports System.Threading
Imports Microsoft.AspNet.SignalR
Imports Microsoft.AspNet.SignalR.Hubs

Public Class StockTicker

        ' Singleton instance
        Private Shared ReadOnly _instance As Lazy(Of StockTicker) =
            New Lazy(Of StockTicker)(Function() New StockTicker(GlobalHost.ConnectionManager.GetHubContext(Of StockTickerHub)().Clients))

        Private _stocks As ConcurrentDictionary(Of String, Stock) = New ConcurrentDictionary(Of String, Stock)

        Private _updateStockPricesLock As Object = New Object

        'stock can go up or down by a percentage of this factor on each change
        Private _rangePercent As Double

        Private _updateInterval As TimeSpan = TimeSpan.FromMilliseconds(250)

        Private _updateOrNotRandom As Random = New Random

        Private _timer As Timer

        Private _updatingStockPrices As Boolean = False

        Private Property _Clients As IHubConnectionContext(Of Object)

        Private Sub New(ByVal clients As IHubConnectionContext(Of Object))
            _Clients = clients
            _stocks.Clear()
            Dim stocks = New List(Of Stock) From {
        New Stock With {
            .Symbol = "MSFT",
            .Price = 30.31D
        },
        New Stock With {
            .Symbol = "APPL",
            .Price = 578.18D
        },
        New Stock With {
            .Symbol = "GOOG",
            .Price = 570.3D
        }
    }
            stocks.ForEach(Function(stock) _stocks.TryAdd(stock.Symbol, stock))
            _timer = New Timer(AddressOf UpdateStockPrices, Nothing, _updateInterval, _updateInterval)
        End Sub

        Public Shared ReadOnly Property Instance As StockTicker
            Get
                Return _instance.Value
            End Get
        End Property

        Public Function GetAllStocks() As IEnumerable(Of Stock)
            Return _stocks.Values
        End Function

        Private Sub UpdateStockPrices(ByVal state As Object)
            ' _updateStockPricesLock
            'TODO: lock is not supported at this time
            ' If Not _updatingStockPrices Then
            _updatingStockPrices = True
                For Each stock In _stocks.Values
                    If TryUpdateStockPrice(stock) Then
                        BroadcastStockPrice(stock)
                    End If

                Next
                _updatingStockPrices = False
            ' End If

        End Sub

        Private Function TryUpdateStockPrice(ByVal stock As Stock) As Boolean
            Dim r = _updateOrNotRandom.NextDouble()

            If r > 0.1 Then
                Return False
            End If

            Dim random = New Random(CInt(Math.Floor(stock.Price)))
        Dim percentChange As Decimal = Rnd() / 100
        Dim pos = random.NextDouble() > 0.51
            Dim change = Math.Round(stock.Price * CDec(percentChange), 2)
            change = If(pos, change, -change)
            stock.Price += change
            Return True
        End Function

        Private Sub BroadcastStockPrice(ByVal stock As Stock)
            _Clients.All.updateStockPrice(stock)
        End Sub
    End Class

The StockTickerHub.vb inherits the hub functionality, and the instantiator.

Imports System.Collections.Generic
Imports Microsoft.AspNet.SignalR
Imports Microsoft.AspNet.SignalR.Hubs



    Public Class StockTickerHub
        Inherits Hub

        Private ReadOnly _stockTicker As StockTicker

        Public Sub New()
            Me.New(StockTicker.Instance)
        End Sub

        Public Sub New(ByVal stockTicker As StockTicker)
            _stockTicker = stockTicker
        End Sub

        Public Function GetAllStocks() As IEnumerable(Of Stock)
            Return _stockTicker.GetAllStocks()
        End Function
    End Class

You will need to have the correct version (or updated) Jquery and SignalR2 javascript libraries accessible to the website.

You can download all the code and libraries for here.  SignalR2StockTickerVb.zip  
 

 


blog comments powered by Disqus

Kbytes Home | Privacy Policy | Contact us | Testing Area

© 2004 - 2024 1 Oak Hill Grove Surbiton Surrey KT6 6DS Phone: +44(020) 8123 1321