• DaveDev

    How to install cool, custom fonts (like PDC09) into Windows and use it in your Silverlight application (or even Microsoft Word)

    • 0 Comments

    Whether you are someone who leans more towards design or coding you have probably come across the need for some interesting fonts.  Typography is a fascinating area with a long history dating back to the origins of print.  When we look at creating an engaging user experience today we are often trying to make a connection with our audience.  We “empathize” with our users needs and look to invoke certain feelings.  Fonts can do that in amazing ways and its pretty easy to add them to your own applications.

    PDC09Font

    The Microsoft Professional Developers Conference (PDC) site has a great art section where you can download wallpapers, blog bling and the font that they used.  Maybe its because I’m such a video gamer but the font really connected with me and brought back memories of playing Wipeout and Star Trek.

     

    Installing the Font into Windows

    I keep a local folder in my documents directory of all the fonts I have found intriguing.  Most of these go into my applications or demos I do for that extra sparkle.  You can keep them anywhere you would like however I just find this method the easiest to use.  That way I can zip up all my fonts if I need to use them on a different machine.

    Fonts

    Adding a font to Windows is as easy as double clicking on the filename.  The Font Manager window will them pop up (Windows 7 is pictured) and you will be given some typography information as well as samples of the font at different sizes.  Just click the install button and windows will register the font for use.

    FontsInstall

    This means ALL windows programs will now have access to that font such as Microsoft Word.  Keep in mind that custom fonts are not required to include both uppercase and lowercase. The PDC09 font (it’s official name is Squared) only includes lowercase for example.  So don’t scratch your head when word tries to capitalize at the beginning of a sentence and you see invisible letters.

    WordFont

     

    Using the new font in your Silverlight application

    Now that we have made sure the font installed correctly it is time to add it to a Silverlight Application.  In this example I am opening up Expression Blend 3, adding a simple gradient to the default grid layout and creating a TextBlock control.  I then selected the newly installed squared font from the textbox text properties and added some colors I thought to be pleasing.

    Font-SL

    Keep in mind one of the amazing things about Blend is we are seeing in real time what our application looks like.  This means for Silverlight the artboard is being rendered in Silverlight.  While we are in design time it understands the selected fonts and displays them correctly.  However if we run the application you will notice something happens.

    SLFontEmbedding

    This is where a lot of people get tripped up.  The application compiled, the browser opened up and it looks nothing like what it did in my Blend design surface.  So what is up?

     

    Font Embedding - it’s all about the download size!

    It is important to remember one of the core design principles of Silverlight is a small download size.  Every time you add a resource such as an image, a font, or a video the initial the size of your application will increase.

    Luckily, Silverlight is really smart about this.  It gives you the choice of not only which Fonts you wish to include in your application but also which parts of those fonts (Uppercase, Lowercase, etc.) giving you even more control over the size of your downloads. To bring up this menu simply click on the Font Manager button in the TextBlock text properties.  As mentioned above the squared font doesn’t use any uppercase which is why you will see the “S” missing.  Blend tries to capitalize the first letter of all the fonts being listed. 

    SLFontSize

    You can see both the Font Manager button and the Embed checkbox (I circled it in red) in the artboard screenshot above.  Keep in mind you do not have to select which pieces of the font to use Blend will automatically include all subsets of that font for you.  It is only necessary to check off the Embed checkbox for the font to be included in your application.

    Once you click the checkbox two things will happen.  A new Fonts directory will be created in your application and the selected Font source file will be copied into it for you.

    SLFontsFolder

    Blend will then modify the XAML source for your TextBlock to point to the newly installed Font resources in your project.

    FontEmbedding2

     

    Looking cool with just a TextBlock thanks to Fonts!

    We are now ready to show off our finished product.  Running the application will now show a correctly displaying TextBlock with the selected square font.  Amazing how much of a difference fonts can make even on a plain piece of text.

    TheFinishedProduct

    This is a trick you can use in all of your applications moving forward whether it is WPF or Silverlight based Blend and Fonts have got your back.

    Want more information like this?  The Microsoft Professional Developers Conference is coming up in less than 3 months! 

    PDC09Register

    If you register by September 15th you can also save $500 bringing the cost of a ticket down to only $1,595.  Be sure to check out the PDC site here for more details.

    Bookmark and Share

  • DaveDev

    Accessing the Accelerometer in a Windows 8 Metro Style App using HTML and JavaScript

    • 1 Comments

    Overview

    I have recently been coding a Windows 8 Metro Style App using the new Windows 8 Release Preview bits and Visual Studio Express 2012 RC.  The app is going to be a retro shooter that takes advantage of HTML5 Canvas for the main game engine and then several Windows 8 Metro Style App Features.  Rather then wait for the game to be completely finished I figured I would start sharing some of my development experiences here on my blog.

    One of the first ideas I had was for a “Gravity Pulse” power that would be granted upon earning a predefined a amount of points (1,500 pts being the default).  Every time the user gains these amount of points a custom sound file will be played and then the screen will display a message to shake the device.  If the user shakes the device within a predefined amount of time all ships on the screen will blow up. 

    Gravity Pulse - Shake the Screen!

     

    The language I chose to use was HTML and JavaScript but this example could just have easily been done in C++/XAML or C#/XAML.  The code needed to access the accelerometer was very small and I was impressed just how easy it was to add to my game.

    Declaration and Initialization

    I start out by defining three local class variables I will use to access the sensor itself and default values for the polling interval.

    //accelerometer
       var accelerometer;
       var intervalId = 0;
       var getReadingInterval = 0;

    Once the DOM of the default.js page has been loaded I call a custom function (named initialize).

    //If Document fully loaded than begin processing
       document.addEventListener("DOMContentLoaded", initialize, false);

    Inside of initialize I set up all of my ships, the coordinate system for the gameboard and other important details.  There is a function I have created that will handle the accelerometer instance called initAccel.

    //Set up accelerometer for shake events
          initAccel();
    //Init Accelerometer
    function initAccel() {
        accelerometer = Windows.Devices.Sensors.Accelerometer.getDefault();
        if (accelerometer) {
            // Choose a report interval supported by the sensor
            var minimumReportInterval = accelerometer.minimumReportInterval;
            var reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
            accelerometer.reportInterval = reportInterval;
            getReadingInterval = reportInterval * 2; // double the interval for display (to reduce CPU usage)
            
        } else {
           displayError("No accelerometer found");
        }
    }

    The initAccel function assigns the default accelerometer (through the magic of WinRT) to the class variable accelerometer and if it finds a device it sets up the reporting interval properties.  Reporting interval is how often we will receive new sensor readings from the accelerometer so it is important to pick a value that won’t kill our cpu.

     

    Handling the Accelerometer Readings

    Always remember accessing the sensor (as in any other devices) will cause cpu load and drain your battery.  I am careful to only turn the sensor on when the user hits the predefined amount of points and then I shut it off until the next gravity pulse becomes available.  Fortunately this is easy to do in JavaScript by controlling the eventListener.  If the accelerometer object has an eventListener assigned to it it will be actively polling for new data. 

    The function I use to check for an in progress Gravity Pulse is called updateScore.  This is where I start listening to accelerometer readings by assigning an eventListener for “shake events” as well as updating the screen and playing a wav file (more on playing sounds and external libraries to come)

    //update player score
        function updateScore(points) {
     
            score += points;
            scoreGravity += points;
            txtScore.innerHTML = "  Score: " + score;
     
            if (scoreGravity === GRAVITY_WAVE_PTS_REQ) {
                accelerometer.addEventListener("shaken", onShakenAccel);
                txtScore.innerHTML = " > SHAKE THAT SCREEN <";
                scoreGravity = 0;
                SoundJS.play("pulse", SoundJS.INTERRUPT_ANY);
            }
     
            //new level
            lvlNextPts = (lvlCurrent + 1) * LEVEL_PTS_REQ;
            if (score >= lvlNextPts) {
                lvlCurrent++;
                txtLevel.innerHTML = "Level: " + lvlCurrent;
                lvlDifficulty = LEVEL_SPEED_INCREASE * lvlCurrent;
     
                SoundJS.play("newlevel",SoundJS.INTERUPT_ANY);
     
            }
     
     
        }


    When a user shakes the Windows 8 tablet enough to register a “shake” event the onShakenAccel eventHandler is called and the following code invoked:

     

    //Accelerometer has been shaken and now we need to grant the bonus power
     function onShakenAccel(event) {
          //Stop Listening to Accelerometer
         accelerometer.removeEventListener("shaken", onShakenAccel);
     
         //Gravity Wave Power - Destroy all ships
         gravityWave();
        
     }

     

    You will notice the first thing I do is remove the eventListener which will effectively turn off the Accelerometer Sensor and then I call a custom function to blow up the on screen ships.

     

    Conclusion

    That’s it!  By adding a few eventListeners and a call into the WinRT Windows.Device.Sensors namespace my game has full accelerometer support!  Hopefully this post will help you get started in adding sensor support in your own Metro Style Apps.  As Always - if you are currently working on a Windows 8 app I would love to hear about it!

    You may also want to check out my previous Windows 8 Metro Style Development Tips:

  • DaveDev

    “The application could not be started.” error when debugging a Windows 8 Metro Style App

    • 0 Comments

    I ran across this today and wanted to share the fix.  I have seen it crop up both XAML/C# and HTML/JS projects and has to do more with how the app is registered. 

    The error appears when you attempt to debug your Windows 8 metro Style App you will be prompted with a dialog informing you the application could not be started.

     

    UnabletoStart

     

    Clicking on Yes for more information will show you the id of the Metro Style App and point you to the Debug->Windows->Output window.  Unfortunately looking in the Output window doesn’t give you much information either.

     

    AppID

     

    The goods news is the fix is simple!  Simply exit out of Visual Studio 11 Beta and navigate to the solution file of your project.  Once there delete everything inside of the bin folder.

    Binfolder

    Then open the project back up in Visual Studio 11 Beta and it should deploy correctly for debugging!

    -Dave

     

    You may also want to check out my previous Windows 8 Metro Style Development Tips:

  • DaveDev

    Connecting to WCF RIA Services in a Windows 8 Metro Style App using Upshot.js and Knockout.js

    • 2 Comments

    Overview

    After messing around with KnockoutJS inside of Metro Style Apps I decided to dive a little deeper and see what Single Page Applications (particularly Upshot.js) could offer.  I’ve gotten asked by more than a few developers how best to connect to their existing WCF RIA Services inside of Metro Style Apps.  The approach I took here is one possible solution to help get your started.

    UpshotOverview

     

    For those not familiar with Upshot it is a JavaScript Library that allows you to connect to WCF RIA Services.  It is by the same great wizards who wrote ASP.NET MVC4 Single Page Applications. and included already in Single Page App templates! 

    I also came across two really great posts you should check out that helped me get my head around things:

    Upshot.js & Knockout.js: The HTML5 Client for WCF RIA Services

    Building Single Page Apps with ASP.NET MVC4 - Part 1 - Basic Desktop Application

    If you just want to grab the MVC4 and Windows 8 Metro Style App source code you can download them here:

    DownloadExample

     

    Setting up the MVC 4 Environment

    In order to get the MVC4 Single Page Application Templates I downloaded and installed Visual Studio 2011 Beta Ultimate (currently freely available here).  I am running everything local: MVC4 Website is using IIS Express and the data is stored in SQL Server 2008 R2 Express( the one that comes with the Web Platform Installer).  The code that I used was based of a great sample Bart Jolling wrote on his blog here

    The example is a simple Deliverytracker SIngle Page Application that looks like this:

    SPA-MVC4 

    To  keep things simple I am running everything local with integrated security on IIS Express and SQL Server Express.
     
    Also take note of our DomainModel as we will need to manually set up MetaData for this later.
    public class Customer
    {
        public int CustomerId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }
     
    public class Delivery
    {
        public int DeliveryId { get; set; }
        public virtual int CustomerId { get; set; }
        public virtual Customer Customer { get; set; }
     
        public string Description { get; set; }
        public bool IsDelivered { get; set; }
    }

     

    Setting up the Metro Style App to use Upshot.js

    I then created a new JavaScript based Metro Style App like usual and selected the Tools – > Library Package Manager – > Manage NuGet Packages for Solution menu and searched for UpShot.

    GrabUpshot

    This will bring down all the required scripts you need for using Upshot.js in your application.

    InstalledScripts

    Because the package installer assumes we are inside of an MVC application it will write everything into a new /scripts folder.  For simplicity sake I removed the /scripts folder and copied all of the JavaScript files into our existing /js folder.

     

    Declaration and Initialization

    We now reference these new JavaScript Libraries like usual inside of our default.html.

    <script type="text/javascript" src="js/jquery-1.6.4.js"></script>
    <script type="text/javascript" src="js/knockout.debug.js"></script>
    <script type="text/javascript" src="js/knockout.js"></script>
    <script type="text/javascript" src="js/DeliveriesViewModel.js"></script>
    <script type="text/javascript" src="js/upshot.js"></script>
    <script type="text/javascript" src="js/upshot.compat.knockout.js"></script>
    <script type="text/javascript" src="js/upshot.knockout.extensions.js"></script>
    <script type="text/javascript" src="js/arrayUtils.js"></script>

    There are two additional scripts here arrayUtils.js and DeliveriesViewModel.js that I copied over from the MVC4 Single Page Application DeliveryTracker example  mentioned previously.  arrayUtils is a helper function we can leave as is and DeliveriesViewModel will be how we wire up to our service. 

    The next step was to take the code from our MVC4 app’s Home View located in /Views/Home/Index.cshtml and move it into our Metro Style App.

    <section>
    <div>
        <h3>Deliveries</h3>
     
        <button data-bind="click: saveAll">Save All</button>
        <button data-bind="click: revertAll">Revert All</button>
     
        <label>
            <input data-bind="checked: excludeDelivered" type="checkbox" />
             Exclude delivered items</label>
     
        <ol data-bind="foreach: deliveries">
            <li data-bind="css: { delivered: IsDelivered, 
                                            updated: IsUpdated}">
                <strong data-bind="text: Description"></strong>
                is for <em data-bind="text: Customer().Name"></em>
                <label><input data-bind="checked: IsDelivered"
                      type="checkbox"/>Delivered</label>
            </li>
        </ol>
     
        <h3>Customers</h3>
        <ul data-bind="foreach: deliveriesForCustomer">
            <li>
                <div>Name: <strong data-bind="text: key.Name"></strong>
                </div>
                <ul data-bind="foreach: values">
                    <li data-bind="text: Description, 
                        css: { delivered: IsDelivered,
                                 updated: IsUpdated}">                
                    </li>
                </ul>
            </li>    
        </ul>
    </div>
    </section>

     

    All of this gets done inside our default.html:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>UpshotWin8</title>
     
        <!-- WinJS references -->
        <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">
        <script src="//Microsoft.WinJS.0.6/js/base.js"></script>
     1:  
     2:     <script src="//Microsoft.WinJS.0.6/js/ui.js">
     1: </script>
     2:  
     3:     <script type="text/javascript" src="js/jquery-1.6.4.js">
     1: </script>
     2:     <script type="text/javascript" src="js/knockout.debug.js">
     1: </script>
     2:     <script type="text/javascript" src="js/knockout.js">
     1: </script>
     2:     <script type="text/javascript" src="js/DeliveriesViewModel.js">
     1: </script>
     2:     <script type="text/javascript" src="js/upshot.js">
     1: </script>
     2:     <script type="text/javascript" src="js/upshot.compat.knockout.js">
     1: </script>
     2:     <script type="text/javascript" src="js/upshot.knockout.extensions.js">
     1: </script>
     2:     <script type="text/javascript" src="js/arrayUtils.js">
     1: </script>
     2:  
     3:  
     4:     <!-- UpshotWin8 references -->
     5:     <link href="/css/default.css" rel="stylesheet">
     6:     <script src="/js/default.js">
    </script>
     
     
    </head>
    <body>
     
    <div >
        <h3>Deliveries</h3>
     
        <button data-bind="click: saveAll">Save All</button>
        <button data-bind="click: revertAll">Revert All</button>
     
        <label>
            <input data-bind="checked: excludeDelivered" type="checkbox" />
             Exclude delivered items</label>
     
        <ol data-bind="foreach: deliveries">
            <li data-bind="css: { delivered: IsDelivered, 
                                            updated: IsUpdated}">
                <strong data-bind="text: Description"></strong>
                is for <em data-bind="text: Customer().Name"></em>
                <label><input data-bind="checked: IsDelivered"
                      type="checkbox"/>Delivered</label>
            </li>
        </ol>
     
        <h3>Customers</h3>
        <ul data-bind="foreach: deliveriesForCustomer">
            <li>
                <div>Name: <strong data-bind="text: key.Name"></strong>
                </div>
                <ul data-bind="foreach: values">
                    <li data-bind="text: Description, 
                        css: { delivered: IsDelivered,
                                 updated: IsUpdated}">                
                    </li>
                </ul>
            </li>    
        </ul>
    </div>
     
    </body>
    </html>

     

    Once we have our view code wired up we now need to call out to the service and databind everything.  Just like my previous KnockoutJS examples I wire up everything after the DomContentLoaded Event has fired using a custom function called initialize.

    document.addEventListener("DOMContentLoaded", initialize);


    Initialize will then tell our app about the fields returned by our Domain Service.  In order to do this we need to call the upshot.metadata function and map values manually based on their original DomainModel source types.  The basic formatting used here is Classname#Namespace.  Once you get your head around that it’s pretty easy to map everything (although laborious).  I also set the key to be based of DeliveryID.  

    After our mapping are set we’ll tell KnockoutJS to bind everything using the provided DeliveriesViewModel function.

    function initialize() {
          
     
        upshot.metadata({
            "Delivery:#DeliveryTracker.Models": {
                "key": ["DeliveryId"],
                "fields": {
                    "DeliveryId": { "type": "Int32:#System" },
                    "CustomerId": { "type": "Int32:#System" },
                    "Customer": { "type": "Customer#DeliveryTrack.Models" },
                    "Description": { "type": "String:#System" },
                    "isDelivered": { "type": "Int32:#System" }
                }
            }
        });
     
        ko.applyBindings( new DeliveriesViewModel( ));
     
    }

     

    The last step now is to edit our DeliveriesViewModel.js file with the location of our Domain Service.  This will be different for everyone but on my local machine the service runs at http://localhost:61907//api/DataService.

    function DeliveriesViewModel() {
        // Private
     
        var dataSourceOptions = {
            providerParameters: {
                url: "http://localhost:61907//api/DataService",
                operationName: "GetDeliveriesForToday"
            },
            entityType: "Delivery:#DeliveryTracker.Models",
            bufferChanges: true,
            mapping: Delivery
        };
     
        // Public Properties
        this.dataSource = new upshot.RemoteDataSource(dataSourceOptions).refresh();
        this.localDataSource = upshot.LocalDataSource({ source: this.dataSource,
            autoRefresh: true
        });
     
        this.deliveries = this.localDataSource.getEntities();
        this.deliveriesForCustomer = this.deliveries.groupBy("Customer");
        this.excludeDelivered = ko.observable(false);
     
        // Operations
        this.saveAll = function () { this.dataSource.commitChanges() }
        this.revertAll = function () { this.dataSource.revertChanges() }
     
        // Delegates
        this.excludeDelivered.subscribe(function (shouldExcludeDelivered) {
            var filterRule = shouldExcludeDelivered
                ? { property: "IsDelivered", operation: "==", value: false }
                : null;
            this.localDataSource.setFilter(filterRule);
            this.localDataSource.refresh();
        });
    }
     
    function Customer (data) {
     
        this.CustomerId = ko.observable(data.CustomerId);
        this.Name = ko.observable(data.Name);
        this.Address = ko.observable(data.Address);
        upshot.addEntityProperties(this, "Customer:#DeliveryTracker.Models");
    }
     
    function Delivery (data) {
      
     
        this.DeliveryId = ko.observable(data.DeliveryId);
        this.CustomerId = ko.observable(data.CustomerId);
        this.Customer = ko.observable(data.Customer);
        this.Description = ko.observable(data.Description);
        this.IsDelivered = ko.observable(data.IsDelivered);
        upshot.addEntityProperties(this, "Delivery:#DeliveryTracker.Models");
    }

     

    Other than the service location I did not need to modify the function in any way from the original MVC4 DeliveryTracker example.

    We now have the Metro Style App binding to the same Domain Service and being fully interactive. 

    RunningMetroApp

     

     

    Conclusion

    Obviously we would need to style the application to make it feel like a native Metro Style App but the hard plumbing work has been done.  We were able to keep a majority of the MVC4 code, from both the views and the model, to get us started with our Windows 8 Metro Style App! 

     

    If you are currently working on a Windows 8 app I would love to hear about it.  You may also want to check out my previous Windows 8 Metro Style Development Tips:

Page 4 of 68 (272 items) «23456»