Saturday, December 27, 2014

XAML Broswer Applications: How to connect to Oracle database using XAML and DataGrid

XAML Browser Applications (XBAP) are Windows Presentation Foundation applications that are hosted and run inside Internet Explorer. Hosted applications run in a partial trust sandbox environment and are not given full access to the computer's resources. XBAP runs in an out-of-process executable (PresentationHost.exe) managed by a virtual machine and they are restricted to the same set of permission granted to any InternetZone application.

The question is why XBAP and not ASP.NET. The answer is simply to bring the power and rich client controls of WPF to the web using a new declarative programming model called "Extensible Application Markup Language" or XAML as well as other benefits such as:
  • Data Binding: robust way of getting data into the UI that allows developers to keep business logic and UI separated.WPF controls support data binding to information on a server, Web developers can asynchronously consume their data and visualize it using a rich data templating system.
  • 3-D: The WPF 3-D system is fully integrated into the platform.
  •  Flow Documents: flow documents dynamically layout content based on window size, device resolution, user preference, and more personalized, reading experience. 
  • Animations:  Full integration with the property and eventing systems, databinding, styling, and templating allows for deep support of rich, interactive applications. 
  • Vector graphics. Native use of vector graphics allows users to operate at any scale or resolution. 
  • Hardware acceleration. XBAP can take advantage of WPF's hardware acceleration support to create new levels of visual complexity while leaving the CPU free for the application's computing requirements.
  • Security sandbox. XBAP run in a security sandbox that limits the dangerous things like access the registry, read or write directly to the file system.
  • No-touch deployment. Because XBAP are sandboxed non-installed applications, they do not require user interaction to launch: there is no need to click through a security prompt or an information bar message. They just run.
  • .NET Framework programming languages. WPF is built on top of the .NET Framework. XBAPs receive all the benefits of being strongly typed managed applications. 
  • Same programming model for desktop/Web. Many product teams are forced to author two independent versions of their applications: a Web and a desktop version. Because WPF offers support for both online and installed applications, desktop and Web applications can share code bases. 
 In this article we will be seeing how to connect to the Oracle database using WPF Browser and will perform a search to retrieve the data from the database, display them in the data grid using Visual Studio 2013. In the Oracle database we will be having a table ADMIN_EMP with three columns EMPNO, ENAME, and DEPTNO.

Steps Involved:

A. Create a new WPF Browser Application project

  1. Start Visual Studio 2013.
  2. On the File menu, point to New, and then select Project.
    The New Project dialog box appears.
  3. In the Installed Templates pane, expand Visual Basic or Visual C#, and then select Windows.
  4. Above the middle pane, select the target framework from the drop-down list.
  5. In the middle pane, select the WPF Browser Application template.
B. Replace  Page1.xaml.cs with following code

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Oracle.DataAccess.Client;
using System.Linq;
using System.Runtime.Serialization;
using System.ComponentModel;


namespace WpfBrowserApplication1
{

    public class DataModel

    {
                public ICollectionView Customers { get; private set; }
          public DataModel()
        {
               List<Employee> employees = new List<Employee>();

            string connectionString = "User Id=myuserid;Password=mypassword;Data Source=ORCL";
            using (OracleConnection connection = new OracleConnection())
            {
                connection.ConnectionString = connectionString;
                connection.Open();
                OracleCommand command = connection.CreateCommand();
                string sql;

                sql = "SELECT * FROM admin_emp";
                

                command.CommandText = sql;
                OracleDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Employee employee = new Employee();
                    employee.EMPNO = Convert.ToInt32(reader["EMPNO"]);
                    employee.EName = Convert.ToString(reader["ENAME"]);
                    employee.DeptNo = Convert.ToInt32(reader["DEPTNO"]);
                    employees.Add(employee);
                }
            }
            Customers = CollectionViewSource.GetDefaultView(employees);
            
        }


    }
    public class Employee
    {
        public int _EMPNO;
        public string _EName;
        public string _Comm;
        public int _DeptNo;


        public int EMPNO
        {
            get { return _EMPNO; }
            set { _EMPNO = value; }
        }

        public string EName
        {
            get { return _EName; }
            set { _EName = value; }
        }

        public string Comm
        {
            get { return _Comm; }
            set { _Comm = value; }
        }

        public int DeptNo
        {
            get { return _DeptNo; }
            set { _DeptNo = value; }
        }
    }



    /// <summary>
    /// Interaction logic for Page1.xaml
    /// </summary>
    public partial class Page1 : Page
    {

        public Page1()
        {
                     
            InitializeComponent();         
            DataContext = new DataModel();
        }
    }
}

C. Replace  Page1.xaml with following code

<Page
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:WpfBrowserApplication1" x:Class="WpfBrowserApplication1.Page1" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
      Title="Page1">
    <Grid>
           <DataGrid x:Name="dataGrid1" Margin="0,144,175,0" VerticalAlignment="Top" Height="128" HorizontalAlignment="Right" Width="115" ItemsSource="{Binding Customers}"
  SelectionMode="Extended" SelectionUnit="Cell" />
        </Grid>            
</Page>

D. Build and Run the code
When you run the XBAP project, it opens in a browser window instead of a stand-alone window. When you debug the XBAP from Microsoft Visual Studio, the application runs with Internet zone permission and will therefore throw security exceptions if those permissions are exceeded.

E. Deploy: 
When you build an XBAP, the output includes the following three files:

Executable (.exe)This contains the compiled code and has an .exe extension.
Application manifest (.manifest)This contains metadata associated with the application and has a .manifest extension.
Deployment manifest (.xbap)This file contains the information that ClickOnce uses to deploy the application and has the .xbap extension.

Create a web site on your IIS and copy .exe, .xbap and .manifest files under the bin directory of your project file to c:\wwwroot\yourwebsite\

F. Test in Action: 

Create an html  file under c:\wwwroot\yourwebsite\ to point to your xbap file. 

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <a href="WpfBrowserApplication1.xbap">Click this link to launch the application</a></body>
</html>

Note: I'm getting the System.Security.SecurityException The demand was for: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/> when attempting to create an AppDomain with restricted permissions.

Saturday, December 20, 2014

Introduction to Xamarin and how to use it with Visual Studio 2013 to develop cross-platform apps

Xamarin platform helps you write your apps entirely in C# and share the same code on iOS, Android, Windows, Mac. Basically you will take advantage of native iOS and Android apps in C# by using Visual Studio for iOS, Android, and Windows development. You will build fully native user interface with cross-platform components and pre-built apps (Nugets library). So where to start?

1. Download Xamarin for Windows: Download Xamarin (http://xamarin.com/download) and run it as an administrator! The installer will download the Android SDK, Java 1.7 JDK (you might have to install the "32" bit version separately yourself), Xamarin for Visual Studio, and Xamarin SDK.

2. Download Xamarin for OS X  (http://xamarin.com/download) and install it.

3. Open a new project in Visual Studio, under "Visual C#", go to "iOS", "Classic API", "iPhone", and select "Single View App (iPhone Classic API)"

4.You'll be prompted to install Xamarin.iOS on your Mac. You will have to open Xamarin.iOS Build Host application (type "xamarin build host" into Spotlight) on your Mac, then click "Pair".

5. Assuming, you already have a license (even with a trial version), you should be able to get the code from your Mac and enter the code to your Windows. Once you pair with a machine, you won't have to do it again.

6. On your Windows machine, you could pick iPhone, or iPhone simulator, go to MainStoryboard.storyboard. Add some buttons, create some events, pop some alerts to get a feeling how it works.

XNA 4.0 game programming

DirectX and OpenGL are both excellent graphics libraries. DirectX works on Microsoft platforms, whereas OpenGL is available on a much wider range of platforms. DirectX tends to be updated more often, which means it has access to the very latest graphics features. OpenGL moves slower and the latest graphics features can only be accessed through a rather unfriendly extension mechanism. OpenGL’s slow movement can be quite advantageous as the interface rarely changes and therefore code written years ago will still work with the latest OpenGL versions. Each new version of DirectX changes the interface, which breaks compatibility and requires older code to be tweaked and changed to be updated.

DirectX can be used with C# using the Managed DirectX libraries, these libraries are no longer officially supported or updated. Managed DirectX has been superseded by Microsoft’s XNA game creation library. XNA uses DirectX, but it is a much higher level framework for quickly creating and prototyping games. SlimDX is an independent C# API for DirectX, which is a good alternative to Managed DirectX.

So, are you ready to write your first game in C#? Let's start with the XNA installation. But before that, I am assuming you already have visual studio 2013 installed. Don't worry if you have the older version, you need to get a different XNA distribution. Go to https://msxna.codeplex.com/releases/view/117230 and install the following:
  1. Install DirectX
  2. Install Xna Framework 4.0 Redistribution
  3. Install Xna Game Studio 4.0 Platform Tools
  4. Install Xna Game Studio 4.0 Shared
What is XNA? XNA Game Studio 4.0 Refresh is a programming environment that allows you to use Visual Studio to create games for Windows Phone, Xbox 360, and Windows. XNA Game Studio includes the XNA Framework, a set of managed libraries designed for game development based on the Microsoft .NET Framework.  This blog is just a tutorial to get you started to write your first game.

1. Create an XNA project: Open the visual studio and create a new "Windows Game (4.0)" project under "XNA Game Studio 4.0" templates. We just simply accept the default name as WindowsGame1. If you don't see the XNA template, you have not installed the right extension. Check out the link above and make sure that you are installing the right XNA extension matching your visual studio version.

2. Create an animation object: Notice that you have two projects under the WindowsGame1 solution. WindowsGame1 project and WindowsGame1Content. Add a new C# class to WindowsGame1 project. Call it Bullet.cs. This class represents an object that will bounce around and make you excited.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace WindowsGame1
{
    class Bullet
    {
        #region Fields

        // drawing support
        Texture2D sprite;
        Rectangle myRectangle;

        // velocity information
        Vector2 velocity = new Vector2(0, 0);

        // bouncing support
        int windowWidth;
        int windowHeight;

        #endregion
        #region Constructors
        //  Constructs a bullet with random direction and speed
        public Bullet(ContentManager contentManager, string spriteName, int x, int y, int windowWidth, int windowHeight)
        {
            this.windowWidth = windowWidth;
            this.windowHeight = windowHeight;
            LoadContent(contentManager, spriteName, x, y);

            // generate random velocity
            Random rand = new Random();
            int speed = rand.Next(30);

            //rand.NextDouble() return double-precision floating point number that is greater than or equal to 0.0, and less than 1.0.
            double angle = 2 * Math.PI * rand.NextDouble();

            //Velocity vector is the position and motion of a single particle using vectors
            //For example, suppose a particle is confined to the plane and its position is given by s=(cost,sint).
            //Then it travels along the unit circle at constant speed. Its velocity vector is v=(-sint,cost).

            velocity.X = (float)Math.Cos(angle) * speed;
            velocity.Y = -1 * (float)Math.Sin(angle) * speed;
        }


        // Constructs a bullet with the given characteristics

        public Bullet(ContentManager contentManager, string spriteName, int x, int y,
            Vector2 velocity, int windowWidth, int windowHeight)
        {
            this.windowWidth = windowWidth;
            this.windowHeight = windowHeight;
            LoadContent(contentManager, spriteName, x, y);
           this.velocity = velocity;
        }
        #endregion
        #region Public methods
        // Updates the bullet's location, bouncing if necessary
        public void Update()
        {
            // move the bullet
            myRectangle.X += (int)(velocity.X);
            myRectangle.Y += (int)(velocity.Y);
            // bounce as necessary
            BounceTopBottom();
            BounceLeftRight();
        }
        // Draws the bullet
        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(sprite, myRectangle, Color.White);
        }
        #endregion
        #region Private methods
        // Loads the content for the bullet
        private void LoadContent(ContentManager contentManager, string spriteName,int x, int y)
        {
            // load content and set remainder of draw rectangle
            sprite = contentManager.Load<Texture2D>(spriteName);
            //Change the bullet's size by changing the last two parameters of Rectangle
            myRectangle = new Rectangle(x - sprite.Width / 2, y - sprite.Height / 2, sprite.Width/5, sprite.Height/5);
        }
        private void BounceTopBottom()
        {
            if (myRectangle.Y < 0)
            {
                // bounce off top
                myRectangle.Y = 0;
                velocity.Y *= -1;
            }
            else if ((myRectangle.Y + myRectangle.Height) > windowHeight)
            {
                // bounce off bottom
                myRectangle.Y = windowHeight - myRectangle.Height;
               velocity.Y *= -1;
            }
        }
        private void BounceLeftRight()
        {
            if (myRectangle.X < 0)
            {
                // bounce off left
                myRectangle.X = 0;
                velocity.X *= -1;
            }
            else if ((myRectangle.X + myRectangle.Width) > windowWidth)
            {
                // bounce off right
                myRectangle.X = windowWidth - myRectangle.Width;
                velocity.X *= -1;
            }
        }
        #endregion
    }
}




3. Add your content: Find a bullet png or jpg picture from internet and save it somewhere. It could be any object. It could be your own picture and then add this png or jpg picture to your WindowsGame1Conent! Let's name the png file, bullet.png.

4. Set the resolution: Go back to Game1.cs and set the resolution by adding these two lines to your Game1 constructor method.

public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            //set resolution
            graphics.PreferredBackBufferWidth = 800;
            graphics.PreferredBackBufferHeight = 800;
        }

5. Declare your variable: Declare a private variable bullet for Class Game1

  public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Bullet bullet;

6. Load your game content: Our game content is just a bullet. To load that,  add a line to LoadContent method.

protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            bullet = new Bullet(Content, "bullet", 300, 100, 450, 450);
        }

7. Draw your object: To draw the bullet, we will use spriteBatch object. Add three lines to your draw method.

 protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin();
            bullet.Draw(spriteBatch);
            spriteBatch.End();

            base.Draw(gameTime);
        }

8. Update your object: Well, we wanted our bullet to bounce around. The update logic goes to Update method by calling the Update method of bullet object:

 protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            // TODO: Add your update logic here
            bullet.Update();
            base.Update(gameTime);
        }

Congratulations, You just created your first animation using XNA in C#. Well, we have to create a game now so players can interact with the animation.

9. Mouse Visible: After you run the program, you will notice when you hover your mouse over anywhere on the window Game, your mouse disappears. Since we want players to interact with the window game, we will need the mouse to be visible. This can be done by setting isMouseVisible to true.

 public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            //set resolution
            graphics.PreferredBackBufferWidth = 800
            graphics.PreferredBackBufferHeight = 800

            IsMouseVisible = true;
        }

10. Create a bullet catcher: So for our game, we try to create a new bullet catcher. This new object basically follows the mouse movement. To make it simple, find a picture of a hand and save and add as hand.jpg under WindowsGame1Content.

  public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        //drawing support
         Bullet bullet;
        Texture2D bulletcatcher;
        Rectangle myRectangle;

11. Load content: Let's load the bullet catcher in LoadContent method:

  protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            // TODO: use this.Content to load your game content here
            bullet = new Bullet(Content, "bullet", 300, 100, 800, 800);
            bulletcatcher = Content.Load<Texture2D>("hand");
            //start bullet catcher in the center of window
            myRectangle = new Rectangle(800 / 2 - bulletcatcher.Width / 2, 800 / 2 - bulletcatcher.Height / 2, bulletcatcher.Width/2, bulletcatcher.Height/2);
        }

12. Draw the bullet catcher:

  protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            // TODO: Add your drawing code here
            spriteBatch.Begin();
            bullet.Draw(spriteBatch);
            spriteBatch.Draw(bulletcatcher, myRectangle, Color.White);
            spriteBatch.End();
            base.Draw(gameTime);
        }

13. Make the bullet follow the mouse: This can done by getting the mouse state and adjust the bullet position according to mouse position.

 protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            // TODO: Add your update logic here
            //Make the bullet catcher follow the mouse
            MouseState mouse = Mouse.GetState();
            myRectangle.X = mouse.X - bulletcatcher .Width / 2;
            myRectangle.Y = mouse.Y - bulletcatcher .Height / 2;
            bullet.Update();
            base.Update(gameTime);
        }




 
 

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.