Sunday, June 15, 2014

Broadcasting Real time Quotes with SignalR 2.0 and ASP.NET MVC 5.0

This demo shows you how to use SignalR framework to create a trading system that shares the latest bid/ask price with other traders in real time. In each browser trader will place their order in and click "Buy" or "Sell". The hub in SignalR broadcasts prices to all other traders.The SignalR library dynamically generate a script file at runtime to manage the communication between jQuery script from the client ("View" page) and server-side code.




1. In Visual Studio 2013, create a C# ASP.NET application that targets .NET Framework 4.5.2, name it MVCTest, and click OK.

2. In the New ASP.NET Project dialog, select MVC, and click Change Authentication.

3. Select No Authentication in the Change Authentication dialog, and click OK.

4. Add the SignalR library to an MVC 5 application. Open the Tools | Library Package Manager | Package Manager Console and run the following command. install-package Microsoft.AspNet.SignalR

5. In Solution Explorer, right-click the project, select Add | New Folder, and add a new folder named Hubs.

6. Create a newSignalR server hub. Right-click the Hubs folder, click Add | New Item, select the Visual C# | Web | SignalR node in the Installed pane, select SignalR Hub Class (v2) from the center pane, and create a new hub named TradeHub.cs that sends last quotes to all clients.The TradeHub class derives from the Microsoft.AspNet.SignalR.Hub class.

7. Create public methods on your hub class and then access those methods by calling them from jQuery scripts in a "View" page. Replace the code in the TradeHub class with the following code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace MVCTest.Hubs
{
    public class TradeHub : Hub
    {
        public void Buy(string security, string numberofshares, string price)
        {
            // Call the updateBid method to update Bid prices.
            Clients.All.updateBid(security, numberofshares, price);
        }
        public void Sell(string security, string numberofshares, string price)
        {
            // Call the updateAsk method to update Ask Prices.
            Clients.All.updateAsk(security, numberofshares, price);
        }
    }
}


8. Set up mapping to the hub when the application starts. In SignalR 2.0, this is done by adding an OWIN startup class, which will call MapSignalR when the startup class' Configuration method is executed when OWIN starts. The class is added to OWIN's startup process using the OwinStartup assembly attribute. In Solution Explorer, right-click the project, then click Add | OWIN Startup Class. Name the class Startup and click OK. Change the contents of Startup.cs to the following:


using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(MVCTest.Startup))]
namespace MVCTest
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

Note: In SignalR 1.0, Open the Global.asax file for the project. Add a call to the method RouteTable.Routes.MapHubs(); as the first line of code in the Application_Start method.This  registers the default route for SignalR hubs

9. Edit the HomeController class found in Controllers/HomeController.cs and add the following method to the class. This method returns the Trade view that you will create in a later step.

 public ActionResult Trade()
        {
            return View();
        }     


10. Create a web page which hosts the SignalR JavaScript client and interacts with the server. Right-click the Views/Home folder, and select Add... | View. In the Add View dialog, name the new view Trade. "Trade" is used by clients. First, it declares a proxy for our hub (TradeHub). And yes, our code says "tradeHub" with lowercase t thanks to Javascript convention. Then  our view calls TradeHub.Buy (when clients want to buy some shares) and TradeHub.Sell (when clients want to sell some shares) to send a new quote from client and share with everybody else. We use Microsoft.AspNet.SignalR.Hub.Clients property to access all clients connected to this hub by calling jQuerys function (updateBid and updateAsk) to update clients with the latest quotes. The TradeHub class on the server calls these two functions to push latest quotes to all clients. connection.hub.start() starts the connection and then passes it Buy/Sell functions to handle "click" event on the "Sell" or "Buy" button. Replace the contents of Trade.cshtml with the following code.

@{
    ViewBag.Title = "Trade";
}
<h2>Realtime Trading System</h2>
<div class="container">
    Security:
    <input type="text" id="security" />
    <br />
    Number of Shares:
    <input type="text" id="numberofshares" />
    <br />
    Price:
    <input type="text" id="price" />
    <br />
    <input type="button" id="buy" value="Buy" /> 
    <input type="button" id="sell" value="Sell" />
    <p></p>
    Last Bid:
    <input type="text" id="bid" />
    Last Ask:
    <input type="text" id="ask" />
</div>
@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the trade page.-->
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.
            var trade = $.connection.tradeHub;
            // Create a function that the hub can call back to display new quotes.
            trade.client.updateBid = function (security, numberofshares, price) {
                // update the last bid price on the page.
                $('#bid').val(htmlEncode(price));
            };
            trade.client.updateAsk = function (security, numberofshares, price) {
                // update the last ask price on the page.
                $('#ask').val(htmlEncode(price));
            };
            // Get the security, number of shares, and price.
            $('#security').val('AAPL');
            $('#numberofshares').val('10');
            // Set initial focus to message input box.
            $('#price').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#buy').click(function () {
                    // Call the Buy method on the hub.
                    trade.server.buy($('#security').val(), $('#numberofshares').val(), $('#price').val());
                    // Clear text box and reset focus for next price.
                    $('#price').val('').focus();
                });
                $('#sell').click(function () {
                    // Call the Sell method on the hub.
                    trade.server.sell($('#security').val(), $('#numberofshares').val(), $('#price').val());
                    // Clear text box and reset focus for next price.
                    $('#price').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}

11. Press F5 to run the project. In the browser address line, append /Home/Trade to the URL of the default page for the project. The Trade page loads in a browser. Enter Ticker name, Number of Shares, Price and click "Buy or Sell" button. Open another browser and see the latest bid or ask text fields in realtime.

Friday, May 9, 2014

How to use Entity Framework with Oracle and ODP.NET in Visual Studio 2013 MVC 5.0

This step-by-step walkthrough provide an introduction to Oracle database development using Entity Framework. This example shows you how to reverse engineer a model from an existing database. The model is stored in an EDMX file  and can be viewed and edited in the Entity Framework Designer. The classes that you interact with in your application are automatically generated from the EDMX file.

1. Download Oracle Developer Tools for Visual Studio: To use Visual Studio's Entity Designer for Database First and Model First object-relational and mapping, Data sources Window, the Dataset Designer, and the Table Adapter Configuration Wizard to drag and drop and automatically generate .NET code, you have to install Oracle developer tools for visual studio.

http://www.oracle.com/technetwork/developer-tools/visual-studio/overview/index.html


2. Create your application: Click New Project, then select Visual C# on the left, then Web and then select ASP.NET  Web Application. Name your project "MvcTest" and then click OK. In the New ASP.NET Project dialog, click MVC and then click OK.

3. The default template gives you  Home, Contact and About, Register and Login pages. You do not want to have register and login pages because they use the newer version (6.0) of entity framework.  Entity Framework 6 is not supported at this time with Oracle 12c or any version of Oracle before 12c. Remove Account folder, Account controller and anything related to account, register, login, and partial login from View, Controller and Model folders from Solution explorer.


4. Nuget Package Manager updade: Before you get too excited to upgrade your entity framework from 6.0 to 6.x.x in Nuget Package Manager, stop right there. Visual Studio 2013 defaults to Entity Framework 6. You will have to set your .NET project to use an earlier version of Entity Framework like 5.0. That means you have to uninstall your entity framework 6.x.x first. As a matter of fact, you will have to uninstall all of its dependencies such as Microsoft ASP.NET identity framework as well. (note to myself: DLL hell era is not over. Microsoft just replaced it with NuGet packages. You can not have two different versions of entity frameworks in the same application domain).

Go to tools -> library package manager -> manage nuget solution for package


  

After the entity framework 6.0 and all its dependencies are uninstalled. you will need to install entity framework 5.0: Install-Package EntityFramework -Version 5.0.0





5. Add a data connection and set the Filters. If you are the owner of the schema, you won't be able to see the other schemas tables or views unless you add the required schemas to your filter. To do that, Open up the server explorer, add/select your database connection, right click on your connection, click on filters. (Note to my self: You can do the same thing when you create ADO.NET Entity Data Model)



6. Clean up the providers that you don't need. You could simply remove "providers" from your entityframwork tags in the web.config. If you don't, you might get an error like unable to retrieve metadata for 'path' unrecognized element providers. (C:\Users\user\appdata\local\Temp-mp6124.tmp line 78)

  <providers>
      <provider invariantName="System.Data.SqlClienttype="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
 The entityFramework tag should look like:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v12.0" />
</parameters>
</defaultConnectionFactory>   
</entityFramework>

8. Install Oracle Data Provider for .NET (ODP.NET) Managed Driver. Everything might work perfectly on your local machine if you have the provider installed. But when you deploy your web site, you get this error: "Unable to find the requested .Net Framework Data Provider. It may not be installed." or "Failed to find or load the registered .Net Framework Data Provider"

There are several ways to install Oracle Data Provider for .NET (ODP.NET) Managed Driver. If you like NuGet , run the following command in the Package Manager Console:

PM> Install-Package odp.net.managed -Version 121.1.0

So when you deploy your code, your managed driver will be included in your deployment package and will be available in the remote machine. If you just add Oracle.ManaedDataAccess.dll as a reference without installing the package, it won't work.


Oracle Data Provider for .NET (ODP.NET) features optimized ADO.NET data access to the Oracle database. ODP.NET allows developers to take advantage of advanced Oracle database functionality, including Real Application Clusters, XML DB, and advanced security. The data provider can be used with the latest .NET Framework 4.5.1 version.
 
ODP.NET makes using Oracle from .NET more flexible, faster, and more stable. ODP.NET includes many features not available from other .NET drivers, including flexible LOB data types, self-tuning, run-time connection load balancing, fast connection failover, and Advanced Queuing.

9. Add an ADO.NET Entity Model to your project. choose model content as Generate from database





















10. Create your data connection and save the entity connection settings in Web.Config.























11. Choose Entity Framework 5.0 and hit the  next button to include some database objects in your model.




















 







Once the reverse engineer process completes the new model is added to your project and opened up for you to view in the Entity Framework Designer. The classes we are going to use to access data are being automatically generated for you based on the EDMX file.  if you are using Visual Studio 2013 the Model.tt and Model.Context.tt files will be nested under the EDMX file. An App.config file has also been added to your project with the connection details for the database.
































Note: if you update the schema in the database, you will have to update the model. To do that:
 
    • Right-click on an empty spot of your model in the EF Designer and select ‘Update Model from Database…’, this will launch the Update Wizard
    • On the Add tab of the Update Wizard check the box next to Tables, this indicates that we want to add any new tables from the schema.

      The Refresh tab shows any existing tables in the model that will be checked for changes during the update. The Delete tabs show any tables that have been removed from the schema and will also be removed from the model as part of the update. The information on these two tabs is automatically detected and is provided for informational purposes only, you cannot change any settings.






























      12. Add a new MVC 5 controller:  In Solution  Explorer, right-click the Controllers folder  and then click Add,  then Controller. In the Add Scaffold dialog box, click MVC 5  Controller with view, using Entity Framework, and then click Add.