Showing posts with label Windows 8. Show all posts
Showing posts with label Windows 8. Show all posts

Thursday, February 20, 2014

Town Hall Style, Windows 8 Development Shoot or Aim?

,
Had the first meeting of the year last night for the Orlando Windows Phone / Windows 8 Group and instead of going down the planned presenter lead meeting format it turned more into a "Town Hall" style with some good topics I thought I'd share.

Where does everyone go to learn how to build or develop for Windows 8.1?

As anyone who can use the web, you w ill find a number of popular blogs that have articles written on how to get started using this or that, including my own, but how relevant are they considering how fast Windows 8 development is moving and changing for that matter.  One attendee mentioned the LayoutAwarePage and how it was a thing and now its "just there".  Or how there were only 3 views to deal with and now there are many.

Brian, from the Orlando .NET User Group, likes Microsoft's Virtual Academy and also stated that when looking at blogs the first piece of information is the date the article was posted to know whether or not to keep going.

Pluralsight.com is also another very well known resource for getting up to speed on almost any technology, and their catalog grows daily.

Monetization strategies for apps?

Of course, a very common topic.  How the heck do you make money on your apps?  Charge for them, ads, in app purchases, both, so on and so forth.  There has been a lot of conversation around this topic and sure enough the recent Flappy Bird app incident has everyone in a swirl to find the next big one.

Alex Perez, from Neuralnet, gave some insight into their experience on in app purchases how they attacked the issue.  Free with in app purchases was the most successful way, BUT you have to hook your users and make them want to keep coming back to the app is the key.

I don't this is a big secret, the secret is finding the hook -- right?

Should I build apps for Windows 8.1 now or wait to see what happens after BUILD 2014?

When Windows 8 hit the development community, a lot of the .NET community hit it learning the tools the new stuff throwing apps, blogging it etc. Some even went at the HTML/WinJS framework option reusing the libraries that were available building RSS readers, games, etc.

Then 8.1 hit and the game was changed. Tools got better, controls were added, more views, the OS was smaller, better, faster. Question on the floor - shoot or just aim?  

Strategies for sharing code?

I love the MVVM pattern for mobile development - Windows Phone, Windows 8.* and anything Xamarin supports.  With Portable Class Libraries and the lifted license restrictions and full support through Xamarin there is no reason not use it.  BUT, do not get caught in hours of trying to force something into the pattern simply to put it into the pattern.  Get the product out there, and rev. Refactor and release often.

Apps or Web?

It just depends right? What is the target audience, the device support, does it need connectivity, what is the skill set of the team you have and so on.  There is no right answer. The answer is -> know what questions to ask.

All great discussions, really enjoyed the format.  What are your thoughts on any or all of these issues, and have you tried this format at your local user group? Would you?
Read more →

Saturday, August 24, 2013

Azure Mobile Services & Portable Class Libraries - Part 2 Authentication Cont'd

,
In Part 1 I covered a simple implementation of the Authentication feature and portable class libraries from the Azure Mobile Services SDK.  However, as mentioned in the "Good & Bad So Far" section; there is not a whole lot of code reuse other than the Azure endpoint and secret key.  Let's refactor a bit by adding some interfaces, conditional compile statements and the MVVM Light Event Bus to help the same solution operate cleaner.

The "after" code for part one is available here.

Building Our Core

PortableAzure.Core is our Portable Class Library that is being shared with the Windows 8 and  Windows Phone project in the attempt to reuse as much code as possible.  However, as mentioned in Part 1 the authentication portion of the Azure Mobile Service SDK is a platform specific implementation due to the UX pieces of that component and how it is presented varies.

Platform Adapter (PlatformAdapter.cs)

In the Services folder, add a new class called PlatformAdapter.cs.  This is an abstract class that will be used as the base class for the platform specific implementation.

    public abstract class PlatformAdapter
    {
        public static PlatformAdapter Current { get; set; }
        public abstract IIdentity Identity { get; }
    }

Identity (IIdentity.cs)

Add a new Identity interface, IIdentity.cs to be used as the implementation to execute the Authenticate method as well as store the MobileServiceUser upon logging in.

    public interface IIdentity
    {
        void Authenticate();
        MobileServiceUser User { get; set; }
    }


 Messages

Add a Messages folder to the root and a class called LoginMessage.cs to newly created folder.

Using the Event Bus from MVVM Light, a LoginMessage will be sent from the platform specific MainPage.xaml then subsequently handled in the MainViewModel.  The LoginMessage is just an empty class at this point.

    namespace PortableAzure.Core.Messages {
        public class LoginMessage { } 
    }

Adding Adapters to the Platforms

On each plaftform we need to now inherit from the PlatformAdapter.cs class in the Services namespace from the Core library as well as implement the IIdentity interface thus replacing the code shown in part one with this code.

Windows Phone

Add an "Adapters" folder to the root of the project and then a Platform.cs class which inherits from PlatformAdapter.

namespace PortableAzure.Phone8.Adapters
{
    public class Platform : PlatformAdapter
    {
        public IIdentity _identity = new Identity();

        public override IIdentity Identity
        {
            get
            {
                return _identity;
            }
        }
    }
}


Next, add the Identity class which is where all of the heavy lifting is done for the login logic.

namespace PortableAzure.Phone8.Adapters
{
    public class Identity : IIdentity
    {
        public async void Authenticate()
        {
            var app = ((App)Application.Current);

            string message = string.Empty;

            while (this.User == null)
            {
                try
                {
                    User = await app.Azure.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Twitter);

                    message = string.Format("You are now logged in - {0}", User.UserId);
                }

                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }
            }

            MessageBox.Show(message);
        }

        public MobileServiceUser User { get; set; }
    }
}   
   
   
   
Now that the Windows Phone implementation is complete we need to tell the Service library what is the current class is for the PlaformAdapater.  This is set in the App.xaml.cs class in the App contstructor:

public App()
{
   Azure = new AzureMobileServices();

   PortableAzure.Core.Services.PlatformAdapter.Current = new Platform();

   ...

Windows 8

To implement the PlatformAdapter class in the Windows 8 application, you could follow the same steps as documented for the Phone project, but that is duplication and not manageable over time.

So in this case we will use add the existing Identity and Platform classes then add conditional compile statements to the areas of the classes where needed to address the small differences for Windows versus Phone.

Add Existing item by holding the Alt key and dragging the file, or the whole folder from the Phone project to the Windows 8 Project.  Thanks Matt Hidinger for this little trick. You could also just go through the right click -> add existing -> add as link process but now that you know the "Hold Alt + Drag" why??

Here are the completed Platform and Identity classes.  You will need to repeat the setting of the current platform in the App.xaml.cs constructor.

Platform.cs


#if NETFX_CORE

namespace PortableAzure.Win8.Adapters

#endif



#if WINDOWS_PHONE

namespace PortableAzure.Phone8.Adapters

#endif

{
    public class Platform : PlatformAdapter
    {
        public IIdentity _identity = new Identity();

        public override IIdentity Identity
        {
            get
            {
                return _identity;
            }
        }
    }
}

Identity.cs

#if NETFX_CORE

namespace PortableAzure.Win8.Adapters

#endif


#if WINDOWS_PHONE

namespace PortableAzure.Phone8.Adapters

#endif

{
    public class Identity : IIdentity
    {
        public async void Authenticate()
        {

#if WINDOWS_PHONE

            var app = ((App)Application.Current);

#endif


#if NETFX_CORE

            var app = ((PortableAzure.Win8.App)(Windows.UI.Xaml.Application.Current));

#endif

            string message = string.Empty;

            while (this.User == null)
            {
                try
                {
                    User = await app.Azure.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Twitter);

                    message = string.Format("You are now logged in - {0}", User.UserId);

                }

                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }
            }

#if WINDOWS_PHONE

            MessageBox.Show(message);

#endif

#if NETFX_CORE

            var messageDialog = new Windows.UI.Popups.MessageDialog(message);

            await messageDialog.ShowAsync();

#endif

        }

        public MobileServiceUser User { get; set; }

    }

}

Note, be sure to use the full namespace OR add more #if at the top for the imports.

Cleanup & Consolidation

Now that there is a single place where the application executes the call to Authenticate, through the magic of #if and reusing existing files, time to delete some code.  Nice right?

In Part, each of the front end projects had code in the MainPage.xaml.cs file within the "Loaded" handler to execute the Azure authentication code.  That can be replaced by using the Event Messaging Bus provided by MVVM Light and sending the LoginMessage.

Messenger.Default.Send<LoginMessage>(new LoginMessage());

In the MainViewModel, add the handler in the constructor and the Login subroutine to call the Authenticate method in the Identity interface.

 public MainViewModel()
 {
     Messenger.Default.Register<LoginMessage>(this, m => { Login(); });
  }

 public void Login()
 {
     if (PlatformAdapter.Current.Identity.User == null)
     {
         try
         {
           PlatformAdapter.Current.Identity.Authenticate();
         }
          catch (Exception ex)
         {
             Debug.WriteLine(ex.ToString());
         }
     }
 }

Now when either platform is run, the Login entry point happens in the MainViewModel upon loading of the main page.  Another option, if you wanted to eliminate the messaging, would be to add a login button and have the ICommand call the Login method thus eliminating any code behind in the MainPage.xaml but that depends on your applications needs.

Windows Phone
Windows 8 / RT



Wrapping Up Authentication

One item to mention, in this example every time the app is run on either platform the user will have to authenticate.  When the MobileServiceUser is successfully authenticated, there are two properties that you can save; MobileServiceAuthenticationToken and UserId respectively.  In a subsequent execution of the app, create a new instance of the MobileServiceUser and set the CurrentUser property of the AzureMobileService.MobileService. For Example:

var user = new MobileServiceUser(mySavedUserId);

user.MobileServiceAuthenticationToken = mySavedMobileServiceAuthenticationToken;

App.MobileService.CurrentUser = user;

Part 1 and Part 2 has shown a simple introduction of how to use portable class libraries with Azure Mobile Services and through the use of a little indirection reuse all the code possible BUT also keep the MVVM implementation and code organization as clean as possible.

Final Code for Part 2 located here

Read more →

Monday, August 5, 2013

Azure Mobile Services & Portable Class Libraries - Part 1 Authentication

,
Azure Mobile Services is undoubtedly one of the best platforms to emerge from the Azure group over the last year. If you are a mobile developer and not taking advantage of it; I encourage you to do so.  There are many video and blog posts available to get you started at http://www.windowsazure.com/en-us/develop/mobile/ .

One of the features you may not be aware of is Azure Mobile Services is a Portable Class Library (PCL) available through nuget. If you are not familiar with PCL's see my "Move Your ViewModels" series.

There is a caveat however when using Azure Mobile Services in your PCL; although all of the data calls to the services are available, using the Identity feature is not and must be implemented in a platform specific way.

The Identity feature allows your application to leverage the user's Microsoft, Google, Facebook or Twitter account to login to the application and abstract the overhead of OAuth or provider specific authentication models into a single call.

var user = MobileService.LoginAsync(MobileServiceAuthenticationProvider.Twitter);

The Challenge - Maximize Code Reuse

There is no secret that Model-View-View-Model (MVVM) is a preferred pattern for xaml developers, but it is also know that sometimes breaking patterns is needed either due to time constraints or other restrictions.

In the effort to maintain the MVVM pattern in this scenario a platform abstraction is needed to accomplish to goal of reusing as much code as possible.  Matt Hidinger did a great talk at BUILD 2013 this year on this topic, give a watch on his blog.

Scenario - Setting up your solution

I won't walk through setting up a Mobile Service on Azure, see this post for instructions, so let's assume we have a Windows Phone & Windows Store application where we'd like to share code in a Portable Class Library and allow the user to login with their Twitter account. The project solution should contain 3 projects:


  • PortableAzure.Win8 - Windows 8 Blank  Application
  • PortableAzure.Phone8 - Windows Phone 8 Application
  • PortableAzure.Core - Portable Class Library Project
    •  .NET Framework 4.0 & higher
    • Windows Phone 7.5 & higher
    • Windows Store Apps

I have added the following nuget packages to the projects

  • Microsoft.Net.Http
  • Portable.MvvmLightLibs
  • WindowsAzure.MobileServices

There is some plumbing related to the MVVM structure that is needed as well.  Get the "before" code here http://sdrv.ms/14ufYYZ , your solution explorer should look like the image here ->.


Adding Azure 


Assumption(s) - you have created a Azure Mobile Service.

First, you will want to add a new class to the Services folder in the PortableAzure.Core project and call it AzureMobileServices. I have also added an empty interface out of habit and to use for IoC (Inversion of Control).

namespace PortableAzure.Core.Services
{
    public class AzureMobileServices : IAzureMobileServices
    {
        public MobileServiceClient MobileService = new MobileServiceClient(
            "https://portableazure.azure-mobile.net/",
            "[your app key]"
        );
        public AzureMobileServices()
        {
        }
    }
    public interface IAzureMobileServices
    {
    }
}


The app key and url comes from the Azure portal when you complete the setup; you will want to choose "Connect to an Existing Project". Either Windows Phone or Windows 8 is an acceptable choice.

Next step is to setup the Twitter authentication, or other provider of your choosing.  (reference)

Now that that is complete, we'll add the necessary platform specific code to the Windows Phone & Windows 8 platforms to prompt the user to login using their Twitter account.

Windows Phone

Open the App.xaml.cs and create a new property for the AzureMobileService class from the Core project.

    public partial class App : Application
    {
        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public static PhoneApplicationFrame RootFrame { get; private set; } 
        public AzureMobileServices Azure { get; private set; } 
        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()

Then in the App constructor create the new instance of the AzureMobileService class.

Azure = new AzureMobileServices();
 In order to prompt the user, open the MainPage.xaml.cs file and add the following code to the PhoneApplicationPage_Loaded event.

 private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            MobileServiceUser user = null;
            while (user == null)
            {
                string message;
                try
                {
                    user = await((App)Application.Current).Azure.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Twitter);
                    message = string.Format("You are now logged in - {0}", user.UserId);
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }
                MessageBox.Show(message);
            }
        }


Windows 8

The implementation is essentially the same for Windows 8 with the exception of how to show a message box.

private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            MobileServiceUser user = null;
            while (user == null)
            {
                string message;
                try
                {
                    user = await((App)Application.Current).Azure.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Twitter);
                    message = string.Format("You are now logged in - {0}", user.UserId);
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login Required";
                }
                var dialog = new MessageDialog(message);
                dialog.Commands.Add(new UICommand("OK"));
                await dialog.ShowAsync();

            }
        }

The Good & Bad - so far

To this point everything is working great and we have now effectively added the authentication to each platform using the Identity features in Azure Mobile Services. But other than the url and the key of the Azure Mobile Service; there isn't a lot of code reuse in this scenario.

This is a necessity when there are platform specific implementations of a feature.  In this case, the UI needs to present differently and cannot re-use the xaml or controls that are a part of the login utility for the specified provider.

The bad part of this is it breaks the MVVM pattern to a degree by putting some of the logic in the code behind.

In the next installment, I'll show how to add an abstraction layer and use the MVVM Light Event Bus to push some of this code back to our view models.

Here is the completed code for Part 1.





Read more →

Friday, February 1, 2013

Develop Windows 8 & Windows Phone Apps and Win Cash!

,
From February 1 through June 2013, publish a new Windows 8 or Windows Phone app and enter my sweepstakes page to win up to $1000 in cash prizes.  WHAT?!?!  

Pretty cool right.  Get extra $$ for what you are already doing.  Publish you app in the store the go to http://spboyer.me/appsforcash and submit your app.

3 Winners each month!
$1000
$500
$250

Follow me on twitter @spboyer and let me know when you submit it and I'll personally look at the app and give it a review and let all my friends to give it a look as well for extra exposure.

See official rules here



BONUS POINTS AND AWARDS

FREE NOKIA PHONE

If this is your FIRST Windows Phone App you may qualify for a Free Nokia Lumia Phone.


TELERIK WINDOWS 8 Controls

I will pick 1 Winner each month from the Windows 8 Submissions to receive a free licensed copy of Telerik's Windows 8 Controls

Read more →

Thursday, January 24, 2013

Portable MVVM Light - Move Your View Models

,

Portable Class Libraries 

Portable Class Libraries were added as a project type in the interest of creating an assembly that you could use across the .NET Framework, Silverlight, Windows Phone 7, or Xbox 360 platforms without modifications.  Well, not really that easy.  There is some work to do and as you get into the development of PCLs you'll find out that there is really a sliver of what you'd hope is supported. (http://msdn.microsoft.com/en-us/library/vstudio/gg597391(v=vs.110).aspx)

MVVM Light

Where I have found it for me is in Windows Store and Windows Phone (7.5 and 8) with MVVM Light. I have been using this MVVM framework exclusively for a few years now on Silverlight, WPF, Windows Phone and now Windows Store platforms and each release gets better.

Most recently, another MVVM Light fan, Oren Novotny (@onovotny) ported the MVVM Light project and made it possible to use it in a Portable Class Library. This is great, code reuse is the ultimate time saver. And when developing Windows Store Apps or a Windows Phone App; making a complimentary piece for the other just makes sense when the UI is really the only difference and even that is almost the same.

Example Project

Open Visual Studio 2012 and create a new project.  I like to start with the "Other Project Types" and select the Blank Visual Studio Solution; name it MvvmPortable and click save. Next add a Windows Store App (C# Blank Template) and call it Mvvm.Store. Add a new Windows Phone 8 project to the solution named Mvvm.Phone.

Now add a new project to the solution and select the "Portable Class Library" project type.


Click OK and then you'll be presented with a dialog to choose the platforms to be supported. Select all except XBox and for Windows Phone choose 7.5 or higher. (An error will occur when adding the nuget packages later if the 'Windows Phone 7.1 or higher' option is chosen).


Click OK and now the MVVM Light packages can start to be added via nuget.

Nuget

If you are  not using nuget, please pause here and go to nuget.org and/or install via Tools->Extensions And Updates.

Mvvm.PCL Project
Right click the project and select the Manage Nuget Packages and in the dialog search for "Portable.MvvmLightLibs" and be sure that the Include Pre-release option is on, or you can use the package manager console and use the command install package portable.mvvmlightlibs -prerelease.


Repeat this process for the Windows Phone and Windows Store projects.

Next we need to add the MVVM Light specific platform assemblies to each of the respective platforms and do some setup and cleanup to make this all work.

Right Click the Windows Store project, select Manage Nuget Packages and search for MVVM Light and click the install button. In doing so, a few folders and files will be added to the project and you may see some errors which we'll clean up and repeat the process for the Phone project.


Moving ViewModelLocator,ViewModels and Wiring it Up

Now on to the fun! 

In the Mvvm.PCL project create a folder call ViewModel in the root of the project. Then expand the  ViewModel folder in the Mvvm.Store project and select the ViewModelLocator.cs and MainViewModel.cs file and cut and paste those to the ViewModel folder in the Mvvm.PCL project.

Open each of those and change the namespace to Mvvm.PCL.ViewModel from Mvvm.Store.ViewModel.

Since the ViewModelLocator has moved, the store app needs to know where to find it and the ViewModels, so open the App.xaml file in the Mvvm.Store project and change:

 xmlns:vm="using:Mvvm.Store.ViewModel" 
to

 xmlns:vm="using:Mvvm.PCL.ViewModel" 

and we need to modify the Resources section because the nuget installer for MvvmLight puts in some extra entries for the ViewModelLocator


    <ResourceDictionary>
        <vm:ViewModelLocator p7:Key="Locator" p8:IsDataSource="True"
                        xmlns:p8="http://schemas.microsoft.com/expression/blend/2008"
                        xmlns:p7="http://schemas.microsoft.com/winfx/2006/xaml" />
        <ResourceDictionary.MergedDictionaries>
                <!--
                    Styles that define common aspects of the platform look and feel
                    Required by Visual Studio project and item templates
                 -->
            <ResourceDictionary Source="Common/StandardStyles.xaml" />
        </ResourceDictionary.MergedDictionaries>
   
    </ResourceDictionary>

Finally for the Store app we'll go to the MainPage.xaml and set the DataContext and add a TextBlock to be filled from the MainViewModel.cs in the portable class library that we'll add following that.

In the MainView.xaml page add the DataContext property at the top of the page after the other declarations.


    ...
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    DataContext="{Binding Main, Source={StaticResource Locator}}"
    >
Next in the grid add the TextBlock as follows


    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Foreground="White" FontSize="42" Text="{Binding Hello, Mode=TwoWay}" />
    </Grid>
If you compile the store project at this point you will get some errors concerning MvvmLight confilcts. These occur because there are class duplicates in the portable and in the specific versions of the assemblies.  In order to alleviate the errors, expand the references folder in the project and select the *.Win8 assemblies and delete them.

Adding Hello to MainViewModel
Now that the wiring up of the relocated ViewModelLocator and MainViewModel are completed we can add the simple "Hello" property in the MainViewModel so it can be bound to in the store project.

Open MainViewModel.cs and add the property as follows:


        private string _hello = "Hello";
        public string Hello
        {
            get
            {
                return _hello;
            }
            set
            {
                _hello = value;
                RaisePropertyChanged(() => Hello);
            }
        }

Set the store project as the default project to run and either run in the simulator or on your local machine and you should see "Hello" appear in the top left of the application.


Wiring up the Phone Project

The process here is pretty much the same as was done for the store project.  Instead of moving the ViewModel folder in the phone project; it can be deleted.

Open the App.xaml and make the adjustments to let the application know where the ViewModelLocator and ViewModels are located. Note that making these references in the phone project are different that in the store project, albeit subtle can trip you up.

Change  

 ...xmlns:vm="clr-namespace:Mvvm.Phone.ViewModel" mc:Ignorable="d">

to

 ...xmlns:vm="clr-namespace:Mvvm.PCL.ViewModel;assembly=Mvvm.PCL">

then make the modifications to the Application.Resources portion as follows:

  <Application.Resources>
    <local:LocalizedStrings xmlns:local="clr-namespace:Mvvm.Phone" x:Key="LocalizedStrings" />
        <vm:ViewModelLocator p6:Key="Locator"
                         p7:IsDataSource="True" xmlns:p7="http://schemas.microsoft.com/expression/blend/2008"
                         xmlns:p6="http://schemas.microsoft.com/winfx/2006/xaml" />
    </Application.Resources>

Next, open the MainPage.xaml and add the DataContext declaration and the TextBlock as we did for the store application.


...
shell:SystemTray.IsVisible="True"
    DataContext="{Binding Main, Source={StaticResource Locator}}">

adding the TextBlock

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBlock Text="{Binding Hello, Mode=TwoWay}" Foreground="White" FontSize="18" />
        </Grid>

And finally as mentioned in the store project, you will get the assembly conflicts so be sure to remove the .*WP8 references in the phone project prior to building the solution here.

Run the application and you'll see the Hello presented in the same location on the phone app.


Wrapping Up

All of the other capabilities that you may or may not be familiar with in the MVVM Light framework is still available to you within the specific projects or of you'd like extract those as well too.  I find that the navigation and switching of the views is still best served within the specific platforms.

I have in my projects moved services negotiation for getting data into the PCL assembly using the Microsfoft.BCL.Async library via nuget too and that is also great but a little different depending on your experience with the platform and WebClient versus HttpClient requests.

Enjoy and feel free to ask questions.

Part 2 - Adding a Data Service


Read more →

Tuesday, January 15, 2013

Picking the Right Tools for Your Project

,
Over the weekend I was able to release the first of many Windows 8 applications (Download and Rate here) into the store that I have been working on. This first one is just a RSS type application for DZone.com, but it just the first version and the next installment will add more content.  If you have ever planned a good, cross platform application before you may or may not understand that picking the right tools for job are important, and yes even what you're using for the front end language matters sometimes as it did in my case here.

Here is a run down of the application architecture components:

  • Node.js REST API on Azure
    • Express : MVC type framework for Node.js for routing, rendering, HTTP Listener
    • Memory-Cache : memory caching on server
    • Cheerio : JQuery on the server, lightweight simple HTML parsing
    • Async : parallel library for Node.js 
  • Windows 8
    • HTML5/WinJS
TypeScript was also used in the Node.js project as well to build out some of the model objects.

I wanted my app to present more. More than just the headline and a link off to another web browser as well as offer the ability to re-use what I had done for Windows Phone or other mobile devices. 


API Architecture Choices - Reuse is Key

The RSS feeds don't change that much, so I want to create a way to have an API I could reuse for other platforms, but also leverage some caching for high availability, scale out if necessary and also make the development as fast as possible. I chose to go with Node.js on Azure to solve this challenge.

Node.js (http://en.wikipedia.org/wiki/Node.js) - Node.js is a packaged compilation of Google's V8 JavaScript engine, the libUV platform abstraction layer, and a core library, which is itself primarily written in JavaScript. Node.js was created by Ryan Dahl starting in 2009, and its growth is sponsored by Joyent, his employer.

Node also has Node Package Manager (npm) which I would or most would say is the equivelant to .NET's nuget package library repository for getting community contributed libraries for accomplishing common tasks such as caching, async and so forth.

I hadn't used node before but I have plenty of JavaScript experience and it was on my list of "want to learn" this year.  I was recently asked why node instead of Web API, other just to say "I used node.js"?  Good question, and a legit one too.  So here is the answer;

Web API is great, I love it and give a talk on "Why you should be using it" at code camps quite often.  However, I found that using C# to parse HTML to not be as flexible and lacked performance in comparison to using Cheerio (JQuery on node.js) when outside of the standard RSS or ATOM formatted feeds. JavaScript is really great at parsing strings.  Secondly, the ability for me to make routes in Express was really easy in comparison to ASP.NET.  For example, in ASP.NET if I wanted to setup a route to handle a controller / action / id route; there are changes needed in the routing configuration as well as potential changes in the controller too.

Routing Config


routes.MapHttpRoute(
    name: "myNewRouteAction",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Controller Code


public class ProductsController : ApiController
{  
     [HttpGet]  
     public string Details(int id)  { ... }
}

Or

public class ProductsController : ApiController
{  
     public string GetDetails(int id) { ... }
}


This sets up the API for the action name to be in the url like http://localhost/api/products/details/1. By contrast in node the same is accomplished with Express.js by doing the following


app.get('/api/products/details/:id', function(request, response) { ... });


Next, in node I can take advantage of running multiple processes at once for checking for updates while also hosting a REST API for the application.  In another application there are two worker roles in Azure, basically Windows Services, doing this type of work and a single Web role for my Web API.  This allows for me to consolidate the processes into one right now and if the need arises I can break the back end architecture into multiple processes. Flexibility and some simplicity I like here. Here is an example where 3 processes are running at once doing tasks at different intervals all non-blocking.

app.js 

var job = function() {
     console.log("working at 1 second.");
 };
var job2 = function() {
     console.log("working at 3 seconds.");
};
setInterval(job, 1000);
setInterval(job2, 3000);

Ouput in Console




Finally, I chose JavaScript/HTML for the UI portions which I'll cover more reasons why later and it's nice to code JavaScript everywhere.

C#/XAML or HTML5/JavaScript/CSS3 ?

Now I will mention that C# is my first language of choice when diving into any new project and in fact that is what I initially started with, but I found that when getting the contents of the RSS feeds, which were non-standard formatted and in order to consume RSS nicely in C# or VB.NET you have a dependency on the SyndicationFeed assembly which is good and bad. Good if the feed is formatted in the standard RSS or ATOM formats, but bad if the provider has extended it.

Once more the article content was also available in nice print formatted HTML, however when using C# in Windows 8 you must embed a browser control and the flow is not fluid in landscape mode.  At least, not the way it should intuitively should appear. However in JavaScript you can take the HTML from the print view and set the innerHTML equal to the result and sprinkle some CSS in there and you are set. No fuss. So HTML5 is the choice here.

In making the decision there are some features that I really enjoy about the language and the ability to create Windows applications versus XAML.

There is a clear separation of concerns between what is Presentation, Styling, and Logic that I think I had taken for granted in my web development projects.  When using C# and XAML I really structure my project with MVVM pattern using MVVM Light, use some naming convention on my files and folder structures to ensure that just by looking at the project I know what does what where.

In a JavaScript Windows 8 project it's clear, just in the tooling and file types.  Now make no mistake you can embed all of the CSS and JavaScript right in the HTML and spaghetti it all up just like anything.  However, the templates and the maturity of the tool set and language almost keeps you from doing so.

The HTML5 support in Blend is also great, especially when seeing what CSS styles are applied to what HTML elements, and using the tooling to create a new style from an existing style.  I encourage you to view the video on blendinsider.com .

Some other items I'll quickly mention that I like about JavaScript projects in Windows 8

  • CSS
    • multiple background layers and overall styling much easier than XAML
    • Supporting snapping, full, landscape etc through media queries I found much more intuitive
  • JQuery Support
    • Who doesn't like JQuery when it comes to getting to the DOM?
  • Web Essentials! not that this has anything specific to do with WIndows 8, but if you are doing any HTML, CSS, and/or JavaScript development you MUST get this.  I have been using this for a while and it continues to get better and now has its own dedicated site as http://vswebessentials.com/
I will still use C# and XAML as it is my first set of tools, but don't forget the others in the box.  There have been some fantastic tools thrown at the developers and some are very quick to poo poo the idea of a new coding language or application of an existing language in a different way.  Pick what best works towards the success of the project.

Here are a few resources for HTML5 and JavaScript Development for Windows 8 




Read more →

Monday, December 3, 2012

Developer Days at Microsoft Store

,

Developer Workshops

Joe Healy (@devfish) and I have been hosting workshops at the Microsoft Store in Orlando at the Florida Mall over the past few Thursdays. The current series has been focusing on Windows Store Apps, including game application development.  Joe presented this past week on MonoGame for Windows 8 and another Florida Developer, Bill Reiss (@billreiss) is doing a blog series on that same topic here, and the turn out was great! Here are the next few topics on deck.



XAML and C# for Windows 8 Store App
https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032532761
Presented by: Shayne Boyer (@spboyer)





Using Game Salad for No-Code Game Development on Windows 8
https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032532922
Presented by: Shayne Boyer (@spboyer)


Future Events

We are planning a two time a month workshop after the New Year with a range of topics covering Windows Store Apps, Windows Phone and much more surrounding these platforms.  If you have some subject matter that you are interested in hearing more about please contact me spboyer@live.com or Joe jhealy@microsoft.com

Other Resources
Visit Generation App at bit.ly/30tolaunch , or Joe's site at devfish.net and be sure to followus on twitter: @devfish and @spboyer.


Read more →

Thursday, October 11, 2012

Tampa Code Camp

,


I will be giving two talks this Saturday at Tampa Code Camp, being held at the University of South Florida in Tampa, Fl.  For directions and more information visit http://www.tampacodecamp.com. Schedule for other sessions here.

 

My Sessions



Building Windows 8 Apps w/ MVVM Light

2:20 PM in Room 1301
Read more →

Tuesday, October 9, 2012

TypeScript for Windows 8 Store Apps

,

What is TypeScript? 

See http://www.typescriptlang.org

TypeScript was recently released and has become the new hot topic.  One of the questions I have asked and heard is can we use this for developing Windows Store Applications with Javascript and have the cool features that have been shown in the videos and examples.

One of the great features was the split window feature where you can code in TypeScript on the left and upon hitting save, it compiles to Javascript on the left. So I fired up a new Javascript Windows Store project in Visual Studio to give it a shot to see if it all works.  Before we get started make sure that you have the following:


Create a New Project

Start by creating a new project. I just went with the "Blank App" template for purposes of this post, but any of the installed templates are certainly applicable.


Click "OK" and you will see that in the Solution Explorer the following structure.  Expand the "js" folder to see the javascript files that are there by default.


Adding the TypeScript Functionality

There are a couple of files that are needed to making TypeScript and Windows 8 play nicely together, as well as jQuery.  The best way to describe these is that they are wrappers for the WinJS, WinRT and JQuery or helpers.  There is also lib.d.ts which is a noted in the file as "ECMA Script APIs

Click on any of these to see the source.

I downloaded all of these and now put them in a folder called tsWin in the project for referencing in my other ts files.

In the examples that have been shown online, by simply adding a .ts file to your project and hitting save; Visual Studio will automatically create the .js file and associate it to the TypeScript file and show the compiled javascript in the split window.  However, this is not the case in a Windows Store Application...Yet.

But we can still make this all work, here's how.

Add a new javascript file to the js folder BUT name it with the extension .ts. I named the file Data.ts.  Next, repeat and name the file Data.js. Your solution explorer should look like this now. Note that I also added the tsWin folder and the mentioned files as well.


Now you can open the data.ts file and get the split window that has been presented and see that the .js file that is compiled on the right. 

There is another file here that is important as well called win.ts, it adds a wrapper for setImmediate and references the winrt.d.ts and winjs.d.t.s files.  I reference this file in any of the TypeScript that I am using but put it within the js folder.

A Quick Example

So here is a quick example that will walk through the following concepts:
  • Creating a simple class
  • Extending the class through inheritance
  • Using Location Services
  • Retrieving a static map from Google Maps API
  • Inserting the image control onto the page.

Open the data.ts file.  We will first create the initial Location class and the MyLocation class in TypeScript  and see the output to javascript.

TypeScript:

///<reference path='win.ts'/>

module Data {

    class Location {
        longitude: any;
        latitude: any;
        url: string;
    }

    class MyLocation extends Location {
        retrieved: any;
    }
};




Javascript:


var __extends = this.__extends || function (d, b) {
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
}

var Data;
(function (Data) {
    var Location = (function () {
        function Location() { }
        return Location;
    })();   

    var MyLocation = (function (_super) {
        __extends(MyLocation, _super);
        function MyLocation() {
            _super.apply(this, arguments);
        }
        return MyLocation;
    })(Location);   
})(Data || (Data = {}));
; ;

Screen shot just to visualize what's show in VS 2012

Not sure about you, but I wouldn't want to write the inheritance code for Javscript, TypeScript kills it there! Ok, let's move on. Next I will add the function to get the location from the device, populate the myLoc object and then create and insert the image into the body of the page.

Note that the TypeScript and Javacript to do this are one and the same, difference here is that we have type safe code.

TypeScript:


  var locator = new Windows.Devices.Geolocation.Geolocator();

  locator.getGeopositionAsync().then(function (pos) {
  
      var myLoc = new MyLocation();
      myLoc.latitude = pos.coordinate.latitude;
      myLoc.longitude = pos.coordinate.longitude;

      myLoc.retrieved = Date.now;
      myLoc.url = "http://maps.googleapis.com/maps/api/staticmap?center="
          + myLoc.latitude + "," + myLoc.longitude
          + "&zoom=12&size=400x400&sensor=false";

      // add a new img tag to the document
      var img = document.createElement("img");
      // set the src and style
      img.setAttribute("src", myLoc.url);
      img.setAttribute("style", "height:400px;width:400px;");
        
      // get the paragraph tag we set for the location of the content
      var p = document.body.getElementsByTagName("p")[0];
      p.appendChild(img);


When you hit save you'll notice that on the status bar at the bottom left of Visual Studio it will read "Compiling TypeScript..." and then the resulting Javascript will refresh/show on the right pane.  It is important to note that if you have the ,js file open you will get the prompt "Such and such file is open would you like to reload".

Before you run the application make sure that you enable the Location capabilities in the package manifest file as shown below or you will get a nasty message box letting you know you didn't.


Ok, hit F5 and see the results.

First you'll get the let me use location services prompt.


And then the page is presented with the downloaded map.


That's a little get started primer on TypeScript and Windows Store Apps!  Pretty awesome stuff.

Tips & Tricks

Content / Package Type

Make sure that all of the TypeScript (.ts) files are marked as None so they are not distributed unnecessarily with your application. 

Debugging

You can put break points in the generated .js files and have access to the immediate window, watch etc.

Dependent Files

I like to see the dependent files like I'm used to seeing in other project types (see below).  Since this is not built in to the Windows Store functionality with TypeScript yet, here is how to do it.


You need to edit the project file.  The best way to do this is to use the Power Commands for Visual Studio extension, or browse to it and open in notepad or some other text editor.

PowerCommands for Visual Studio
For this solution locate the data.ts reference in the file and change it to the following:

    <Content Include="js\data.js">
      <DependentUpon>data.ts</DependentUpon>
    </Content>
    <None Include="js\data.ts" />

Save the file and reload the project and you can now see that the .js file will be shown below the .ts file.

Conclusion

I have had some real fun getting into this and trying it out with the Store apps.  Coming from a C# / XAML life for the last many years, it will be interesting for me to back to some scripting.  I like the option and I see some really cool opportunities with TypeScript.

Read more →

Tuesday, September 25, 2012

RadCustomHubTile from Telerik for Windows 8 UI

,

Introduction

Telerik recently released their Windows 8 UI Controls to RC on September 18th (see post here), and this is probably on the first in a series of posts I will put out showing them off.

The first control here is the RadCustomHubTile.  I chose this because I am in the process of porting my Find Amber app from Windows Phone to Windows 8 and I wanted to transition the app without drifting too far from the spirit of the original app. 

RadControls from Telerik used here for
Current List and Search & Stats section
You can see from the screen shot that I had already used the RadControls for Windows Phone, so now I can bring some of the design through.

The controls do support both HTML and XAML design, if the current version of the controls do not include either or; I assure you the version you seek is in development and on its way.

Getting Started

The RadCustomHubTile allows any user-defined content rather than predefined parts that you may find in a RadHubTile or RadSlideTile, and as in most if not all of the Telerik controls; MVVM as well as code based binding is supported.

Prior to trying this example, please download the controls from Telerik and note that I am using MVVM Light as the MVVM Framework.  You can see how to install MVVM Light via nuget by opening the Package Manager console and running "Install-Package mvvmlight".  If you have any trouble with that please see http://mvvmlight.codeplex.com or contact me via twitter (@spboyer) OR see my blog post on how to get started with Windows 8 and MVVM Light.

In the following example you will see:
  • MVVM Binding
  • Content locally bound
  • Content bound from an internet URI
  • Complex front and back content for the tile
This is a moderately simply example.  I started with a Blank Solution in Visual Studio 2012 and called it RadCustomHubTile (in retrospect probably should have stuck with App1).

Install the MVVM Light Framework via nuget (see above), you will have to make a change to the App.xaml file.  When installing this, it adds the reference to the namespace in the old way

  xmlns:vm="clr-namespace:RadHubTile.ViewModel"

you need to change this to:

 xmlns:vm="using:RadHubTile.ViewModel"

 A little house keeping to make it look nice. Yes I care what it looks like even for this. Go ahead and add the following below the <Grid> tag to add the header to the initial page.  You can change the title if you like and run (F5).

<Grid.RowDefinitions>
 <RowDefinition Height="140"/>
 <RowDefinition Height="*"/>
</Grid.RowDefinitions>


<Grid>
 <Grid.ColumnDefinitions>
  <ColumnDefinition Width="Auto"/>
  <ColumnDefinition Width="*"/>
 </Grid.ColumnDefinitions>
 <Button x:Name="backButton"  Style="{StaticResource BackButtonStyle}"/>
 <TextBlock x:Name="pageTitle" Text="Rad Custom Hub Tile" Grid.Column="1" IsHitTestVisible="false" Style="{StaticResource PageHeaderTextStyle}" Foreground="#FFADD808"/>
</Grid>

Title and Back button


Next, lets add the RadCustomHubTile Control, and the best way to do this is to simply drag it from the toolbox right into the spot within the XAML. This is something you could not do in Windows Phone which is a big step in my opinion.

It will add the namespace and the references to the project.

To clean it up a little and make sure that you are using within the design guidelines, wrap the RadHubControl with a Grid with the following settings.

<Grid Grid.Row="1" Margin="115,0,0,0">



  <Primitives:RadCustomHubTile />



</Grid>

If you are wondering why my RadCustomHubTile is prefixed, it is because I have changed or altered the declaration at the top of the page to be the following (this matches my Phone app stuff).

xmlns:Primitives="using:Telerik.UI.Xaml.Controls.Primitives" 

Setting Front and Back Content

The content for the front and back are defined by setting the content within the <RadCustomHubTile.FrontContent> and <RadCustomHubTile.BackContent> respectively.  Pretty simple, so here is an example:

<Primitives:RadCustomHubTile Height="300" Width="300">
 <Primitives:RadCustomHubTile.FrontContent>
  <Grid>
   <Image x:Name="imgBlogger" 
        Source="{Binding Photo, Mode=TwoWay}" 
        Height="300" Width="300" 
        Stretch="UniformToFill" Margin="0" 
        HorizontalAlignment="Left" 
        VerticalAlignment="Center" />


   <Rectangle Height="65" Fill="#99000000" VerticalAlignment="Bottom" />

   <StackPanel Orientation="Horizontal">
    <TextBlock  Text="Blogger:" 
        Foreground="White" Width="126" Height="43" 
        VerticalAlignment="Bottom" 
        Margin="10,0,0,14" Style="{StaticResource SubheaderTextStyle}" 
        HorizontalAlignment="Left" />

    <TextBlock  Text="{Binding UserName}" 
        Foreground="White" Height="43" 
        VerticalAlignment="Bottom" Margin="0,0,0,14" 
        Style="{StaticResource SubheaderTextStyle}"/>
   </StackPanel>
  </Grid>
 </Primitives:RadCustomHubTile.FrontContent>

 <Primitives:RadCustomHubTile.BackContent>
  <Grid>
   <Image x:Name="img" 
         Source="{Binding Thumbnail, Mode=TwoWay}" 
         Height="300" Width="300" 
         Stretch="UniformToFill" Margin="0" 
         HorizontalAlignment="Left" 
         VerticalAlignment="Center" />

   <Rectangle Height="65" Fill="#99000000" VerticalAlignment="Bottom" />

   <TextBlock  Text="{Binding Title, Mode=TwoWay}" 
        Foreground="White" Width="270" Height="30" 
        VerticalAlignment="Bottom"  
        Margin="0,0,0,30" Style="{StaticResource BasicTextStyle}" />

   <TextBlock  Text="{Binding SubTitle, Mode=TwoWay}" 
        Foreground="White" Width="270" Height="30" 
        VerticalAlignment="Bottom" Margin="0,0,0,5" 
        Style="{StaticResource BasicTextStyle}"/>
  </Grid>
 </Primitives:RadCustomHubTile.BackContent>
</Primitives:RadCustomHubTile>




Note that you will want to wrap your content with the FrontContent / BackContent tags in Grid, StackPanel etc as the designer will give you the "Content cannot be set more than once error".

Here is the MainViewModel that is bound. Note that the Blogger image (me), is pulled from an internet source uri and the back image is pulled from the project itself. The string properties are bound simply.

using GalaSoft.MvvmLight;
using System;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;

namespace RadHubTile.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel() { }

        public string Photo
        {
            get { return "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwU-gMFDLVqD7kgEEeGFpbdzX1aU0iuyWU14v5iyaPP7wqCYfkSykw-RzbcyYn-mO3luv8stH2m61RKJ4y5KpjmVVeh2MdTbxRx3AE3SxbsfoshmzKwfzoOir42-2DLZTEAA8SBO3Q-rs/s1600/profilepic.png"; }
        }

        public string UserName
        {
            get { return "Shayne Boyer"; }
        }

        public ImageSource Thumbnail
        {
            get { return new BitmapImage(new System.Uri(new Uri("ms-appx:"), "/Assets/RadCustomHubTile.png"));}
        }

        public string Title
        {
            get { return "Telerik Windows 8 UI Controls"; }
        }

        public string SubTitle
        {
            get { return "RadCustomHubTile"; }
        }
    }
}



So what does it all look like?

Front



Back



One other item to note is that you can alter the duration of the flip/rotation by setting the UpdateInterval which is a TimeSpan. So setting the value to "0:0:5" would be equal to 5 seconds.  There is also FlowDirection and many other properties to customize the Tile to your liking.  I'd like to see what you can do with it.  Download the controls today and let me know what you working on and if you have any questions.


Read more →
Powered by Blogger.
 
Creative Commons License
TattooCoder.com by Shayne Boyer is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.