Using Metro UI CSS version 2.0 with ASP.NET MVC

Metro UI CSS is now in version 2.0 so the previous post is not useful.

metroexample1

Metro UI CSS’s author is Sergey Pimenov from Kiev, Ukraine.

Metro UI CSS a set of styles to create a site with an interface similar to Windows 8.

metroexample2

You can use NuGet to add Metro UI CSS to your project:

PM> Install-Package Metro.UI.CSS

Well that didn’t work for me and I don’t know why, the package is added to the project but I didn’t see any new files or references added to it.

metro2.0.12

Fortunately there is another package in the NuGet Library you can use but is version 2.0.4 instead of 2.0.12.  You can see it here:

metro2.0.4

This package do the following (from my point of view):

1. Adds a reference to WebActivatorEx

2. In the folder App_Start adds a new file called “MetroUICSSBundleConfig.cs”, I show you the code here:

using System.Web.Optimization;

[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(metrouicssPrueba.App_Start.MetroUICSSBundleConfig), "RegisterBundles")]

namespace metrouicssPrueba.App_Start
{
    public class MetroUICSSBundleConfig
    {
        public static void RegisterBundles()
        {
            // Add @Styles.Render("~/Content/metro-ui/css") in the <head/> of your _Layout.cshtml view
            // Add @Scripts.Render("~/bundles/metro-ui") after jQuery in your _Layout.cshtml view
            // When <compilation debug="true" />, ASP.Net will render the full readable version. When set to <compilation debug="false" />, the minified version will be rendered automatically
            BundleTable.Bundles.Add(new ScriptBundle("~/bundles/metro-ui").Include("~/Scripts/metro-ui/jquery.ui.widget.js").Include("~/Scripts/metro-ui/metro-*"));
            BundleTable.Bundles.Add(new StyleBundle("~/Content/metro-ui/css").Include("~/Content/metro-ui/css/metro-bootstrap.css", "~/Content/metro-ui/css/metro-bootstrap-responsive.css"));
        }
    }
}

You can follow the instructions in the comments:
// Add @Styles.Render("~/Content/metro-ui/css") in the <head/> of your _Layout.cshtml view
// Add @Scripts.Render("~/bundles/metro-ui") after jQuery in your _Layout.cshtml view
// When <compilation debug="true" />, ASP.Net will render the full readable version. When set to <compilation debug="false" />, the minified version will be rendered automatically

3. In the folder “Content” adds a new folder called “metro-ui” inside this folder in creates 2 new folders called “css” and “fonts”

In folder “css”  you can see the following files:

  • metro-bootstrap-responsive.css
  • metro-bootstrap.css

In folder “fonts” you can see the following files:

  • iconFont.dev.svg
  • iconFont.eot
  • iconFont.json
  • iconFont.svg
  • iconFont.ttf
  • iconFont.woff

In the folder “Scripts” it adds a new folder called “metro-ui” and add the following files:

  • jquery.ui.widget.js
  • metro-accordion.js
  • metro-button-set.js
  • metro-calendar.js
  • metro-carousel.js
  • metro-core.js
  • metro-countdown.js
  • metro-date-format.js
  • metro-datepicker.js
  • metro-dialog.js
  • metro-drag-tile.js
  • metro-dropdown.js
  • metro-fluentmenu.js
  • metro-hint.js
  • metro-input-control.js
  • metro-listview.js
  • metro-live-tile.js
  • metro-notify.js
  • metro-plugin-template.js
  • metro-progressbar.js
  • metro-rating.js
  • metro-slider.js
  • metro-stepper.js
  • metro-streamer.js
  • metro-tab-control.js
  • metro-table.js
  • metro-times.js
  • metro-touch-handler.js
  • metro-treeview.js

4. You can add the reference to the Metro UI CSS in the file Views/Shared/_Layout.cshtml. To the CSS files and to the JavaScript files.

Thats it.

Or you can use the manual way like this:

metrouihowto

As you can see in the Metro UI CSS web site. There are 5 steps to start using Metro UI CSS.

I think Step Zero is download the Metro UI CSS zip file (16.7Mb). Here: https://github.com/olton/Metro-UI-CSS/archive/master.zip

1) Create a new project ASP.NET and choose the MVC template.

2) From the zip file copy these 2 CSS files to your “Content” folder:

  • “metro-bootstrap-responsive.css” and
  • “metro-bootstrap.css”

3) In the folder “Scripts” create a new folder name it “Metro”.

Here you should copy the JavaScript files that you are planning to USE. For instance if you want to use an accordion control then add the “metro-accordion.js”.

You can copy from the zip file the following files:

  • metro-accordion.js
  • metro-button-set.js
  • metro-calendar.js
  • metro-carousel.js
  • metro-core.js
  • metro-countdown.js
  • metro-date-format.js
  • metro-datepicker.js
  • metro-dialog.js
  • metro-drag-tile.js
  • metro-dropdown.js
  • metro-fluentmenu.js
  • metro-hint.js
  • metro-initiator.js
  • metro-input-control.js
  • metro-listview.js
  • metro-live-tile.js
  • metro-loader.js
  • metro-locale.js
  • metro-notify.js
  • metro-plugin-template.js
  • metro-progressbar.js
  • metro-rating.js
  • metro-scroll.js
  • metro-slider.js
  • metro-stepper.js
  • metro-streamer.js
  • metro-tab-control.js
  • metro-table.js
  • metro-times.js
  • metro-touch-handler.js
  • metro-treeview.js

4. In your Scripts folder you already have jquery version 1.10.2, you can use the normal file or the minified version. So you need to add from the zip file “jquery.widget.min.js” and “metro.min.js”

5. If you are going to need the fonts, add them to the “Fonts” folder in your project the files needed are:

  •  iconFont.eot
  • iconFont.svg
  • iconFont.ttf
  • iconFont.woff

6. In the final code example I use an image from the zip file called “2.jpg” put that file in the “Images” folder in your project.

7. Add a new Html file called it “index.html” and use the following code, it should work:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <link href="Content/metro-bootstrap.css" rel="stylesheet" />
    <link href="Content/metro-bootstrap-responsive.css" rel="stylesheet" />

    <title>PROBANDO METRO UI CSS 2.0</title>
</head>
<body class="metro">

    <h1>Heading 1</h1>
    <h2>Heading 2</h2>
    <h3>Heading 3</h3>
    <h4>Heading 4</h4>
    <h5>Heading 5</h5>
    <h6>Heading 6</h6>

    <span class="label">Default</span>
    <h3>Table Bordered</h3>
    <div class="example">
        <table class="table bordered">
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
            </tr>
            <tr>
                <td>one</td>
                <td>two</td>
            </tr>
        </table>
    </div>
    <h3>Table Hovered</h3>
    <div class="example">
        <table class="table hovered">
            <tr>
                <th>Header 1</th>
                <th>Header 2</th>
            </tr>
            <tr>
                <td>row 1, cell 1</td>
                <td>row 1, cell 2</td>
            </tr>
            <tr>
                <td>row 2, cell 1</td>
                <td>row 2, cell 2</td>
            </tr>
        </table>
    </div>
    <h3>Input Text and Password</h3>
    <div class="example">
        <label>User Name:</label>
        <div class="input-control text" data-role="input-control">
            <input type="text" placeholder="Type your user name" />
            <button class="btn-clear" tabindex="-1"></button>
        </div>
        <label>Password:</label>
        <div class="input-control password" data-role="input-control">
            <input type="password" placeholder="Type your password" autofocus />
            <button class="btn-reveal" tabindex="-1"></button>
        </div>
    </div>

    <h3>CheckBox and Radio buttons</h3>
    <div class="example">
        <div class="input-control checkbox" data-role="input-control">
            <label>
                <input type="checkbox" checked />
                <span class="check"></span>
                Check me please.
            </label>
        </div>
        <div>
            <div class="input-control radio default-style" data-role="input-control">
                <label>
                    <input type="radio" name="r1" checked />
                    <span class="check"></span>
                    R1
                </label>
            </div>
            <div class="input-control radio default-style" data-role="input-control">
                <label>
                    <input type="radio" name="r1" />
                    <span class="check"></span>
                    R2
                </label>
            </div>
        </div>
    </div>

    <h3>Select</h3>
    <div class="example">
        <form>
            <div class="input-control select" data-role="input-control" >
                <select>
                    <option>Option 1</option>
                    <option>Option 2</option>
                    <option>Option 3</option>
                </select>
            </div>
            <br />
            <div class="input-control select" data-role="input-control">
                <select multiple>
                    <option>Value 1</option>
                    <option>Value 2</option>
                    <option>Value 3</option>
                    <option>Value 4</option>
                </select>
            </div>
        </form>
    </div>
    <h3>Buttons</h3>
    <div class="example">
        <button>Button1</button>
        <button class="default">Button2</button>
        <button disabled="disabled">Button3</button>
        <a class="button">Button4</a>
    </div>

    <h2><i class="icon-accessibility on-left"></i>Switch control</h2>
    <div class="example">
        <div class="input-control switch margin10" data-role="input-control">
            <label>
                Switch me
                <input type="checkbox" checked />
                <span class="check"></span>
            </label>
        </div>

        <div class="input-control switch margin10" data-role="input-control">
            <label>
                Switch me
                <input type="checkbox" />
                <span class="check"></span>
            </label>
        </div>

        <div class="input-control switch margin10" data-role="input-control">
            <label>
                Switch me
                <input type="checkbox" disabled />
                <span class="check"></span>
            </label>
        </div>

        <div class="input-control switch margin10" data-role="input-control">
            <label>
                Switch me
                <input type="checkbox" disabled checked />
                <span class="check"></span>
            </label>
        </div>
    </div>

    <div class="image-container shadow">
            <img src="../Images/2.jpg">
            <div class="overlay-fluid">Sample text</div>
    </div>

    <div class="example">
        <div class="rating large" data-static="false" data-score="3" data-stars="5" data-role="rating" data-show-score="true" data-score-hint="Rating: "></div>
        <div id="rating_1" class="fg-green"></div>
        <div class="rating small fg-red" data-static="false" data-score="3" data-stars="5" data-role="rating" data-show-score="true" data-score-hint="Value: "></div>
    </div>

    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script src="Scripts/jquery.widget.min.js"></script>
    <script src="Scripts/metro.min.js"></script>
    <script src="Scripts/Metro/metro-rating.js"></script>

    <script>
        $(function () {
            $("#rating_1").rating({
                static: false,
                score: 2,
                stars: 5,
                showHint: true,
                showScore: true,
                click: function (value, rating) {
                    //alert("Rating clicked with value " + value);
                    rating.rate(value);
                }
            });
        });
    </script>
</body>
</html>

The example uses one control the “Rating” control so I had to add the reference to “metro-rating.js”.
The Html file has 2 references to the CSS files from Metro UI CSS:

<link href="Content/metro-bootstrap.css" rel="stylesheet" />
<link href="Content/metro-bootstrap-responsive.css" rel="stylesheet" />

And at the end of the file you can see the references to the JavaScript files

<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/jquery.widget.min.js"></script>
<script src="Scripts/metro.min.js"></script>
<script src="Scripts/Metro/metro-rating.js"></script>

If you need help, inside the zip file there is a folder called “docs” with examples in Html that you can use to understand how to use Metro UI CSS.

Don’t forget that you can use the Metro UI CSS web sites for more examples too. You can use the “view source” command in your browser to take a peek to the code that makes it tick.

Posted in ASP.NET, MVC | Tagged , , , , , , , | 10 Comments

SignalR 2.0 Persistent Connection Another Example, Tracking your Mouse Pointer.

This example uses SignalR 2.0 and track the position of the mouse’s pointer in a web browser.

tracking

Create a new project in Visual Studio 2013 choose the template ASP.NET Web Application, then Empty template.

First you need to add the libraries, open Tools\Library Packet Manager\Packet Manager Console and run the following:
Install-Package Microsoft.AspNet.SignalR

As in previous posts you don’t need to register a route using a Global.asax file.
You need to add an OWIN Startup Class. Add, New Item… and select Owin Start Class. Name it Startup.cs

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(TrackingConnections.Startup))]

namespace TrackingConnections
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Map the TrackerConnection PersistentConnection to "/tracker"
            app.MapConnection<TrackerConnection>("/tracker");
        }
    }
}

Then the Client code, add a HTML file call it Index.html
To create dummy text I used a Chrome Extension called “Lorem Ipsum Generator”. You put the number of paragraphs in this case 4 and don’t forget to click the button “Save settings”

lorem

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.0.0.min.js"></script>
    <script src="Scripts/tracking.js"></script>
    <style>
        .client {
            position: absolute;
            background-color: white;
            -moz-box-shadow: 10px 10px 5px #888;
            -webkit-box-shadow: 10px 10px 5px #888;
            box-shadow: 3px 3px 3px #888;
            border: 1px solid #a0a0a0;
        }
    </style>
</head>
<body>
    <h1>Lorem Ipsum</h1>
    <p>Turpis parturient, in risus odio velit hac, tristique nascetur magna, dapibus non, et mus sociis nunc rhoncus ridiculus! Placerat, habitasse? Dictumst pulvinar! Nec arcu, pulvinar adipiscing et vut montes augue urna aliquam amet, enim! Augue, porta sociis enim! Non ut tristique et sed adipiscing, amet porttitor cursus risus, ac duis in porttitor? Lorem vel sed est vel nisi aenean turpis, dolor scelerisque diam mus, facilisis ut mauris risus in porttitor dignissim hac, duis nec quis sed! Tincidunt non turpis placerat, est, risus cum? A risus est porttitor rhoncus, ac et! Ridiculus magnis amet enim! A lorem, magna enim, mus eros. Vel hac cras lundium porta pulvinar enim platea sit aliquet, enim platea? Eros purus mus, augue, in scelerisque odio elit.</p>
    <p>Dis integer hac, in lacus, magnis ac aenean in, dolor placerat! Massa cum, in porta parturient, facilisis et lacus mid elit mid est. A urna. Ac elit etiam dis, cras non lectus porta? Elementum sociis, dignissim sed, nunc platea sit urna etiam elementum odio dictumst montes urna! Magnis, sed? Parturient! Duis rhoncus et pulvinar adipiscing! In porta, augue mid! Adipiscing pellentesque velit placerat enim nec, a, vel platea ac penatibus lectus? Dapibus augue et risus? Porttitor est nascetur hac sit dictumst! Pulvinar placerat? Lacus nascetur turpis? Porta! Nisi scelerisque! Montes sagittis penatibus magnis scelerisque? Urna, lacus augue lorem integer et elementum adipiscing porta cursus turpis sit integer, dis est massa urna? Turpis placerat vel cras nec elementum cursus vel.</p>
    <p>Urna ac, scelerisque urna nisi! Phasellus? Porta, nisi enim a ut! Nascetur turpis, eros! Tempor vel aenean, sociis magnis porttitor mid sit dictumst, hac parturient magnis odio, phasellus adipiscing, magna et, in ac cursus! Urna ut a et! Nisi magna nisi ac, a, amet phasellus. Nec ac? Magna hac, lundium rhoncus egestas augue ridiculus mattis a auctor pellentesque porttitor? Nisi ut diam velit pulvinar, sit ultrices sed phasellus et sagittis? Porttitor? Scelerisque nec urna aliquet tortor odio massa integer, dapibus porttitor porttitor pid mus! Et scelerisque nec magna sociis, aliquam adipiscing dolor ultrices magna mid dolor nec elementum platea, adipiscing aenean, penatibus urna purus, eros integer? Porttitor. In dapibus. Integer platea? A placerat non ridiculus. Enim, hac ac aliquet.</p>
    <p>Augue cursus, integer, augue, dignissim! Placerat lundium turpis quis lundium sociis duis, duis? Elementum, purus lundium nunc, non tortor sociis massa massa tristique scelerisque facilisis penatibus nisi proin vel lacus, platea. Tincidunt amet turpis, penatibus, in arcu ultrices tincidunt magna mid amet urna dis, ac hac, elementum dis turpis, ut nisi scelerisque dictumst cum magnis etiam proin, integer sagittis. Lacus, dolor est, scelerisque? Lectus dis dis risus rhoncus vel velit nisi. Sit sed adipiscing pellentesque, a sociis cras et magna facilisis a risus sed? A purus elit cursus egestas, magna amet cras velit mus, ultricies, adipiscing sed tortor. Arcu vut auctor, cum etiam, nisi vel mus dictumst, cras vut cum ac. Dapibus quis? Phasellus rhoncus urna. Rhoncus phasellus in.</p>
</body>
</html>

Add a JavaScript file and name it Tracking.js

/* SignalR Client */
var connection = $.connection("/tracker");
connection.start(function () {
    startTracking();
});
connection.received(function (data) {
    data = JSON.parse(data);
    var domElementId = "id" + data.id;
    var elem = createElementIfNotExists(domElementId);
    $(elem).css({ left: data.x, top: data.y }).text(data.id);
});

function startTracking() {
    $("body").mousemove(function (e) {
        var data = { x: e.pageX, y: e.pageY, id: connection.id };
        connection.send(JSON.stringify(data));
    });
}

/* Helper functions */
function createElementIfNotExists(id) {
    var element = $("#" + id);
    if (element.length == 0) {
        element = $("<span class='client' id='" + id + "'></span>");
        var color = getRandomColor();
        element.css({ backgroundColor: getRgb(color), color: getInverseRgb(color) });
        $("body").append(element).show();
    }
    return element;
}

function getRgb(rgb) {
    return "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")";
}

function getInverseRgb(rgb) {
    return "rgb(" + (255 - rgb.r) + "," +
                    (255 - rgb.g) + "," +
                    (255 - rgb.b) + ")";
}

function getRandomColor() {
    return {
        r: Math.round(Math.random() * 256),
        g: Math.round(Math.random() * 256),
        b: Math.round(Math.random() * 256),
    };
}

And the last piece of code, the server code. Add a class and name it TrackerConnection.cs

using Microsoft.AspNet.SignalR;

namespace TrackingConnections
{
    public class TrackerConnection: PersistentConnection
    {
        //public static void InitRoute()
        //{
        //    RouteTable.Routes.MapConnection<TrackerConnection>(
        //        name: "tracker", url: "/tracker");
        //}

        protected override System.Threading.Tasks.Task OnReceived(IRequest request, string connectionId, string data)
        {
            return Connection.Broadcast(data, connectionId);
        }
    }
}

Run the code in multiple browsers and move your mouse to see how it moves in the other browser’s windows.

This example comes from the book SignalR by J.M.Aguilar, highly recommended.

Posted in SignalR | Tagged , , , , , | Leave a comment

SignalR 2.0 Hub Example

SignalR 2.0 includes some changes that we need to be aware of before trying to run a SignalR 1.x sample.

This example will focus on the Hub, it’s the same example (chat application) as the previous post but using Hub instead of PersistentConnection.

SignalRPersistentConnectionRunning

First create a new project ASP.NET Web Application and select the Empty template. Name it “SignalRHub”

Add NuGet packages, “Microsoft.ASP.NET SignalR”. You can use the NuGet console just type this command:

 Install-Package Microsoft.AspNet.SignalR

Add an OWIN Startup Class. So Add, New Item… and select Owin Startup Class. Name the new class Startup.cs

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SignalRHub.Startup))]

namespace SignalRHub
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

Now we add a new Class, name it “Chat.cs”

using Microsoft.AspNet.SignalR;

namespace SignalRHub
{
    public class Chat : Hub
    {
        public void Send(string message)
        {
            Clients.All.AddMessage(message);
        }
    }
}

That’s it for the server-side part of the project. Now for the client-side, we need an HTML page and some JavaScript to connect to the server and chat.
Add an HTML page and name it index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/jquery.signalR-2.0.0.js"></script>
    <script src="/signalr/hubs" type="text/javascript"></script>

    <script type="text/javascript">
        $(function () {
            var chat = $.connection.chat;

            chat.client.addMessage = function (message) {
                $("#chatWindow").val($("#chatWindow").val() + message + "\n");
            }

            $.connection.hub.start().done(function () {
                $("#chatWindow").val("Connected\n");
                $("#sendButton").click(function () {
                    chat.server.send($("#messageTextBox").val());
                    $("#messageTextBox").val("")
                });
            });
        });
    </script>
</head>
<body>
    <textarea id="chatWindow" style="width:400px; height:200px;"></textarea>
    <div>
        <label>Message</label>
        <input id="messageTextBox" type="text"/>
        <button id="sendButton">Send</button>
    </div>
</body>
</html>

This code is based on the examples from the book SignalR: Real-time Application Development by Einar Ingebrigtsen

Posted in SignalR | Tagged , , , | 3 Comments

SignalR 2.0 PersistentConnection Example

SignalR 2.0 includes some changes that we need to be aware of before trying to run a SignalR 1.x sample.

This example will focus on the Persistent Connection, it’s a classic chat application.

SignalRPersistentConnectionRunning

First create a new project ASP.NET Web Application and select the Empty template. Name it “SignalRPersistent”

Add NuGet packages, “Microsoft.ASP.NET SignalR”. You can use the NuGet console just type this command:

 Install-Package Microsoft.AspNet.SignalR

Next step is to register a route in ASP.NET using a Global Application Class (Global.asax) but this step has changed in SignalR 2.0.

Instead you need to add an OWIN Startup Class. So Add, New Item… and select Owin Startup Class. Name the new class Startup.cs

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(SignalRPersistent.Startup))]
namespace SignalRPersistent
{

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR("/echo");
        }
    }
}

The following code is no longer necessary, so there is no need to add this code to the project. This is informational.

namespace SignalRPersistent
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            //RouteTable.Routes.MapConnection("echo", "echo/{*operation}");
        }
    }
}

Now we add a new Class, name it “ChatConnection.cs”

using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;

namespace SignalRPersistent
{
    public class ChatConnection: PersistentConnection
    {
        protected override Task OnReceived(IRequest request, string connectionId, string data)
        {
            return Connection.Broadcast(data);
        }
    }
}

That’s it for the server-side part of the project. Now for the client-side, we need an HTML page and some JavaScript to connect to the server and chat.
Add an HTML page and name it index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/jquery.signalR-2.0.0.js"></script>

    <script type="text/javascript">
        $(function () {
            var connection = $.connection("/echo");

            connection.start().done(function () {
                console.log("Connected");
                $("#chatWindow").val("Connected\n");
                $("#sendButton").click(function () {
                    connection.send($("#messageTextBox").val());
                    $("#messageTextBox").val("")
                });
            });

            connection.received(function (data) {
                $("#chatWindow").val($("#chatWindow").val() + data + "\n");
            });
        });
    </script>
</head>
<body>
    <textarea id="chatWindow" style="width:400px; height:200px;"></textarea>
    <div>
        <label>Message</label>
        <input id="messageTextBox" type="text"/>
        <button id="sendButton">Send</button>
    </div>
</body>
</html>

This code is based on the examples from the book SignalR: Real-time Application Development by Einar Ingebrigtsen

Posted in SignalR | Tagged , , , , , , | 9 Comments

LightSwitch Using Tooltips in Controls and DataGrids

lightswitchtooltip

You want a tooltip in a grid when you hover over the grid (you can use this with other controls too):

ToolTipService.SetToolTip(grid, new TextBlock() { Text = "Hello World!!!" });

For other controls just replace “grid” for another control’s name.

You want a tooltip in a grid when you hover over a cell.

ToolTipService.SetToolTip(grid.Columns[0].GetCellContent(row), new TextBlock() { Text = "Hello World!!!" });

Now you want a tooltip in a grid when you hover over a cell but in this case you want to show the contents of the cell as the tooltip.

ToolTipService.SetToolTip(grid.Columns[0].GetCellContent(row), new TextBlock() { Text = (row.DataContext as MyTable).MyProperty });
Where:

  • First parameter is the cell you want to add a tooltip Example: grid.Columns[0] indicates the column (it starts in 0 for the first column)
  • Second parameter is the tooltip. Example, we have an entity “MyTable” with a property called “MyProperty:
    new TextBlock() { Text = (row.DataContext as MyTable).MyProperty }

Finally you want to put a tooltip but it is too long and you end with an incomplete and long line across the screen. You need to split the line in multiple lines using this:

// don't forget this line on top of the file.
using System.Text.RegularExpressions;

Regex rgx = new Regex("(.{50}\\s)");
string WrappedMessage = rgx.Replace((row.DataContext as MyTable).MyProperty, "$1\n");

ToolTipService.SetToolTip(grid.Columns[0].GetCellContent(row), new TextBlock() { Text = WrappedMessage });

The Complete Code (put it on the screen code where the datagrid is located).

Also you’ll need this using System.Windows.Controls;

partial void ScreenName_Created()
{
   this.FindControl("grid").ControlAvailable += ScreenName_ControlAvailable;
}

void ScreenName_ControlAvailable(object sender, ControlAvailableEventArgs e)
{
   var ctrl = e.Control as DataGrid;
   if (ctrl != null)
    {
        ctrl.LoadingRow += ctrl_LoadingRow;
    }
}

void ctrl_LoadingRow(object sender, DataGridRowEventArgs e)
{
    var grid = sender as DataGrid;
    var row = e.Row as DataGridRow;

    // for a general tooltip
    ToolTipService.SetToolTip(grid, new TextBlock() { Text = "Hello World!!!" });

    // for a cell tooltip
    ToolTipService.SetToolTip(grid.Columns[0].GetCellContent(row), new TextBlock() { Text = (row.DataContext as MyTable).MyProperty });
}

The following code splits the tooltip in multiple lines and checks for null in the value (when the property accepts nulls), if it’s null then it doesn’t add the tooltip.

void ctrl_LoadingRow(object sender, DataGridRowEventArgs e)
{
   var grid = sender as DataGrid;
   var row = e.Row as DataGridRow;

    Regex rgx = new Regex("(.{50}\\s)");
    if ((row.DataContext as MyTable).MyProperty != null)
    {
        // split the long line
        string WrappedMessage = rgx.Replace((row.DataContext as MyTable).MyProperty, "$1\n");
        // for a cell tooltip
        ToolTipService.SetToolTip(grid.Columns[0].GetCellContent(row), new TextBlock() { Text = WrappedMessage });
    }
}
Posted in LightSwitch | Tagged , , | 1 Comment

Entity Framework Power Tools Beta 4

New update to the Entity Framework Power tools now version 0.9.0.0 from 0.7.0.0 created by the Entity Framework Team (Microsoft), updated: 10/11/2013.
efpowertoolsbeta4

Posted in Entity Framework | Tagged , | Leave a comment

JavaScript for ASP.NET programmers (webcast by ComponentOne)

You can see the webcast slide here: http://www.slideshare.net/russellfustino/java-scriptforaspnet-programmers-webcast-upload (Russ Fustino and Chris Bannon)

There is not online viewing yet.

Here is the link to the video: http://our.componentone.com/2013/09/21/awesome-recorded-webcast-now-available-javascript-for-asp-net-programmer/

Here is an extract:

Why use JavaScript and HTML5?

  • 61% leave a site if it is not mobile-ready
  • 79% search for another site
  • 48% said if a site didn’t work on a mobile device, they didn’t feel the company valued their business
  • Bottom line… there is a real world business need for mobile-ready sites

How do I use my skill set as an ASP.NET developer to program in JavaScript?

  • What is the pain solved using JavaScript anyway?
  • How do I use AJAX in JavaScript
  • Are there “built-in” libraries available?
  • How do I use third party controls?
  • What about data bindings?
  • What about frameworks?

component1map

Then they talk about Ajax

What exactly is Ajax?

Ajax (Asynchronous JavaScript and XML)

Allows us to load data from the server without a browser page refresh.

Set of technologies working together:

  • XHTML and CSS for markup
  • DOM for display and interaction
  • XML and XSLT for data interchange & manipulation
  • JSON for marshalling objects
  • XMLHttpRequest for asynchronous communication
  • JavaScript for tying it all together

Then about jQuery

jQuery

  • JavaScript is HARD
  • jQuery is a JavaScript library that makes JavaScript easier
  • Simplifies DOM spelunking (explore caverns)
  • Handles browser differences
  • Provides a key shortcut “$”
  • Download from jquery.com
  • The jQuery library has a full suite of functions and methods for AJAX capabilities
  •  Hosted on CDN

jQuery Syntax
$(selector).action()
Where:

  • $ references jQuery:
  • (selector) queries the DOM element or elements
  •  and .action() performs an action on the element

Examples:
$(this).hide() hides the current element.
$(“p”).hide() hides all paragraphs.
$(“p.wow”).hide() hides all paragraphs of the class “wow”.
$(“#wow”).hide() hides an element with the id of “wow”.

jQuery API help: http://api.jquery.com/
for Wijmo: http://wijmo.com/wiki/index.php/Getting_Started_with_Wijmo

jqueryapi

Then about jQueryUI

jQuery UI

  • UI controls built on top of jQuery
  • All open source
  • Download from jqueryui.com
  • Hosted on CDN

HTML -> jQueryUI -> Widget (HTML, JavaScript, CSS)

jQuery UI

Widgets: Accordion, AutoComplete, Button, DatePicker, Dialog, Menu, ProgressBar, Slider, Spinner, Tabs, Tooltip

Interactions: Draggable, Droppable, Resizeable, Selectable, Sortable

Effects: Add class, Color animation, Effect, Hide, Remove class, Show, Switch class, Toggle, Toggle class

Utilities: Position, Widget class factory

Widget

  • Options (Configure widget)
  • Methods (Command widget)
  • Event (Handle widget events)

jQuery UI API help: http://api.jqueryui.com

jqueryuiapi

Then about Wijmo a ComponentOne’s framework.

Wijmo is their core client-side framework built on web standards

  • HTML5
  • jQuery / jQuery UI
  • jQuery Mobile
  • CSS3
  • SVG
  • Knockout Angular JS
  • Breeze JS

Wijmo is one technology for all development

  • ASP.NET WebForms
  • ASP.NET MVC
  • JavaScript / jQuery / HTML5
  • Any Platform (PHP, Rails, etc)
  • Studio for ASP.NET
  • LightSwitch

Wijmo works everywhere.

  • Cross-browser support (IE6+, Firefox, Chrome, Safari)
  • Tablets
  • Mobile phones
  • Windows 8

Wijmo.

  • Wijmo Enhanced controls built on top of jQueryUI
  • Created by ComponentOne
  • Two Commercial versions – Wijmo Profesional – Wijmo Enterprise
  • Download from wijmo.com
  • Hosted on CDN
  • All widgets adapt automatically to jQueryUI or jQuery Mobile
  • More options, events and methods

then they talk about Knockout.JS

Knockout.Js

  • MVVM Support
  • Declarative Bindings
  • Observables
  • Live Data
  • Supported in every widget
  • It’s Optional

What is MVVM?

Model. The Model encapsulates the domain model, business logic and may include data access. For example a Customer object contains properties for Name and Address.

View. The View is the application’s User Interface (UI). It defines the appearance of visual elements and controls such as text boxes and buttons.

View Model. The View model is responsible for holding application state, handling presentation logic and exposing application data and operations (commands) to the view such as LoadCustomers and SaveCustomers. It acts as the intermediary between the view and model.

3 steps for using Knockout with Wijmo

  1. Add references to the latest jQuery dependencies, Wijmo widgets, Knockout.js file and KO extension library for Wijmo.
  2. Create the ViewModel and View: add JavaScript to define the data and behavior of the UI, and add markup to create the View – the visual, interactive UI.
  3. Bind the Wijmo widget(s) to the ViewModel and activate KO.

Knockout or Angular?

Knockout is just about data binding

  • Knockout is solid, very widespread and reliable
  • Fully supported by Wijmo

Angular is a presentation framework

  • Routing
  • Animations
  • View orchestration
  • Dependency management
  • Data binding
  • Fully supported by Wijmo

ComponentOne special offers: http://www.componentone.com/SuperPages/SpecialOffers

Summary

  • Responsive Design is important
  • jQuery makes JavaScript programming easier
  • jQuery UI makes using widgets and effects easier
  • Wijmo exposes more options, methods and events on top of jQuery
  • Great Wijmo support is available
  • All Wijmo widgets work with jQuery Mobile
  • HTML5 clients are proliferating
  • Knockout and Angular are great for developers coming from .NET
Posted in ASP.NET, JavaScript, Web Development | Tagged , , , , , , , | Leave a comment