Bill Blogs in C# -- Windows 8

Bill Blogs in C# -- Windows 8

Created: 4/8/2014 12:21:12 PM

Let’s start with the biggest story:

A public Roslyn Preview that’s Open Source.

The next versions of C# and VB.NET have progressed far enough that you now have a new public preview. The Roslyn Compilers now support all the existing features (C# 5, VB.NET 12). In fact, they have even added some new prototype features for the proposed C# 6 and VB.NET vNext releases. (VB.NET would be at version 13, but I haven’t seen a published version number)

Best of all, you can see the development and you can participate in the ongoing language design discussions. The Roslyn compilers are Open Source. You can view them here. I’ll blog more about the compilers and the new and proposed language features in the coming months. 

And TypeScript, don’t forget TypeScript.

In more language news, TypeScript 1.0 has been released. It’s development has been public and Open Source for some time.  It’s integrated into Visual Studio 2013 Update 2, which is available in Release Candidate form.I’ve been working with TypeScript for a while, and I’ll be covering it more here. In particular, this discussion on the null propagating operator is very lively.

In addition, there’s now the new .NET Foundation, which is the curator of several .NET related Open Source projects. You can see a number of .NET libraries and components in the foundation already, and I only expect that trend to continue. The .NET Foundation is a great example of how Microsoft is changing. Look at the current board members of the .NET Foundation. The board already includes prominent community members that do not work for Microsoft. I expect that to continue and grow as time goes on.

Both Roslyn compilers, and TypeScript are already part of the .NET Foundation assets.

Visual Studio Online

The Humanitarian Toolbox has been using the preview versions of Visual Studio. It’s a tremendous step forward for team collaboration in the cloud. The tools help you can more information about your application, and Applications Insights provides a nice extra. Quick edits in the cloud, automatic deployments, insights, and more. Oh, and it’s integrated with your local Visual Studio experience.

Azure Updates

This probably deserves several blog posts on its own. It’s a full time job just to keep up with all the new tools released by the Azure team. There’s a new management portal. New mobile services, new resource management,  Java VMs in Anzure, and more.

I need to dive in more, because it’s hard to keep up with what Guthrie’s team produces.

 

Windows 8.1 update

Most of these news features are for end users, not developers. They do represent a lot of feedback and represent a good direction. For Enterprise developers there are a couple great features. The enterprise side loading story is much better. Modern apps are much more economical for enterprises to deploy than with previous 8.x platforms. The IE Enterprise mode will also help enterprise deal with legacy web-based applications. However, I would still recommend that most enterprises consider any application that needs enterprise mode to be a technology risk.

Universal Apps, and all it comes with

Microsoft has been talking about unifying the Windows Phone, Windows 8 and Windows Server platforms for some time. That’s now gotten even more ambitious. Universal apps also can include iOS and Android devices, using the Xamarin tools. The idea that a common API set could be available across Windows 8, Windows Phone, iPhone, iPad, Android phones and Android Tablets is really innovative.  Also, these projects work across different IDEs: Visual Studio, Xamarin Studio, and (where someone has written the plug ins) Eclipse.

It means C# is, along with JavaScript, the one language you can use to develop applications across all the popular computing platforms today. .NET and C# is truly a cross-platform development environment.

There’s more changes that make this cross-device story compelling. There are changes in the Microsoft Store that make it easier and more advantageous to produce apps for both Windows 8 and Windows Phone. You’ll get more visibility across the stores, and you’ll get more touch points with your potential customers.

Windows Phone and Cortana

I’m impressed with the potential of Cortana. You’ll see lots of people saying that Cortana is “Siri for WIndows Phone”. That’s an oversimplification. Yes, you can talk to Cortana and it will answer you. But what’s really interesting over time is how Cortana integrates with you through your applications on your phone. Voice recognition and voice interaction is a great step. More interesting is how those capabilities will work across applications when integrated with Cortana. Can my scrum app alert me if I’m too aggressive on deadlines because of other commitments? Could a nutrition app integrate across a fitness app to change calorie allocations because of upcoming events, or days off? There’s a lot of potential. There’s also risk. Can those cross-application capabilities be added while respecting users’ privacy?  There’s a lot of potential hear, and I can’t wait to learn more and dive in to create new, useful applications.

Conclusion: Microsoft is reaching out to developers in a big way

I know this post had less detailed technical content than my typical post. There’s a lot of information that came from //build. I’ll drill into many of the areas for some time.

The big picture of all the announcements and the reveals at //build is this: Microsoft is reaching out to developers again. And not just the developers that have traditionally worked within the Microsoft space. They are reaching out to Open Source developers, mobile developers that concentrate on non-Microsoft platforms, and more. It’s a smart move. They brought out lots of technology that makes lots of sense.

The platform, the languages, and the tools, are first rate. I’m glad to see Microsoft reaching out to developers and changing their direction to match today’s developer community.

Created: 7/24/2013 3:26:43 PM

I recently finished Jeremy Likness' book, Building Windows8 Apps with C# and XAML.  This is an excellent first book for C# developers that want to explore Windows 8.

Jeremy's writing is clear, concise, and thorough. He provides an excellent explanation of the information and techniques he covers. The code is clear, and the examples are solid examples of common Windows 8 programming scenarios.

You can also download the associated code so that you can explore the apps, following along as he explains the techniques he uses to create the sample apps. The sample apps are small but complete programs that demonstrate the important techniques he covers.

This book is for you if….

You are new to Windows 8 development, but have a good understanding of C# and .NET.

This book gives a good overview of the new Windows 8 runtime, the new libraries, XAML capabilities in Windows 8, and the Windows 8 templates that ship with Visual Studio 2012. You'll also get an overview of MVVM, unit testing your Windows 8 apps, Live Tiles, Charms, and working with the store. You’ll learn the basics of XAML, and a few intermediate techniques as well.

Jeremy doesn't go extremely deep into those topics. That's the right decision for an introductory book. After you read this, you'll be ready to build Windows 8 store apps. You'll have the knowledge necessary to create professional apps that can be maintained and extended over time. By following Jeremy's advice, you'll leverage the functionality in the Visual Studio templates, and the Windows Runtime. You'll design your app in a way that supports extension and enhancement over time. Your code will also be positioned to take advantage of the upcoming features added in Windows 8.1.

If you want to get started building Windows 8 apps, get this book, and keep it handy. You'll turn to it often as you create your first few Windows 8 apps.

This book is not for you if…

You have already released a few Windows 8 store apps and want a deeper understanding of Windows 8, the runtime, or XAML.

As I said above, Jeremy doesn't go extremely deep into any of the topics he covers. If you already know the basics, and some of the intermediate topics for Windows 8 development, you already know much of what Jeremy covers. Get this book for the junior members of your team, but you'll learn more from Jeremy's blog, and other detailed Windows 8 developer resources.

Created: 1/7/2013 7:48:28 PM
We’ve partnered with Microsoft to host “Windows 8 Unleashed” in Ann Arbor on Thursday January 24th. This is a free event, sponsored by Microsoft, and hosted by SRT Solutions. Windows 8 Unleashed is a developer event focused on people that want to develop apps for the Windows store. (Surely you’ve seen the commercials for Windows 8 by now). The format contains 3 sessions where Jennifer Marsman and I will be explaining the principles of Modern UI Application development (what we formerly referred to as “Metro style apps”).  The afternoon is open lab time for you to create your Windows Store Application.  Jennifer and I (along with a few possible unannounced guests) will be available to help you over the rough spots. The first link above provide information about the event (including prize opportunities, and who doesn’t like free stuff). The second link is the registration page. Registration is free, but it will help us ensure we have enough room, and food for everyone that attends.
Created: 11/19/2012 1:04:43 PM

I've now spent two full weeks with my WinRT Surface. I've tried to spend as much time as possible with this device while I’m forming my opinions.

I bought the Surface Pro, and I bought both the touch cover (red, to match the SRT logo), and the type cover. I wanted to try both to decide which I liked better.

WinRT is the version of Windows8 that runs on the ARM processor. It comes with an ARM version of Microsoft Office Home and Student. (That version includes Word, Excel, PowerPoint and OneNote). Other than those applications, you must install applications from the Windows Store. You cannot install applications from any other location.

The WinRT Surface has a lot to recommend it. Because of the ARM processor, the battery life is amazing. I've been able to take notes through an entire day of meetings without finding a cord or power outlet. The form factor is comfortable to work with. The screen is very clear and bright. The weight is very light, even after a full day.

As I mentioned above, I purchased both the touch cover and the type cover. I have a very strong preference for the type cover. I tried the touch cover for a few days, and I found it too different from a normal typing experience. The type cover is a much better experience, at least for me.

The restriction that all apps must come from the store was really not a problem. I've been able to find great apps for all my non-developer tasks. I'm using Tweeterlight for my twitter client. I've got IM+ to manage my message accounts. I've got skype installed. I use FeedReader for my RSS reader. I don't mean this to be an exhaustive list. It's just to give you some indication of the main applications I'm using. Overall, I've been happy. There are one or two holes that I still need filled, but overall I've been happy with what's available.

Of course, it's not perfect. I'm ambivalent about the kickstand. It's at a great angle when I place the Surface on a desk or a table, and I'm sitting in front of it. However, the angle of the kickstand is not adjustable. It's not at the right angle for me when the surface is in my lap, or when I'm working at my stand desk. However, I can work with the surface lying flat in some of those cases. My one suggestion for a future hardware enhancement would be to allow the kickstand to have a couple of different angles built in. With that said, Microsoft clearly put a lot of thought into the design: the angle of the kickstand is great at a table for me, my wife, and my daughter (all having quite different heights).

I do think that a Surface with Windows RT (on the ARM processor) is a great device for students, home users, and many business users. If you can find the apps you need in the Windows store, you will be very happy with this device on WinRT.

There are a few classes of users for whom the Surface with Windows RT is not the best choice (for their primary device). Serious gamers will not be happy because they will not be able to install games designed for Windows 7. Developers cannot use the ARM -based devices for their main machine (but will want an ARM device. I'm writing another blog post on this topic). Users that have some specialized application needs may not find their specific application ready yet for Windows 8 yet.

Overall, I'm impressed with the Surface running WinRT. I'll use it regularly because of the battery life. It's going to be my primary machine while travelling. I'll also be adding two more of these devices to our family. Both my daughter and my wife are planning on new Surface machines.

Created: 11/10/2012 2:51:24 PM

I’m finishing up my calendar and planning for next week. It’s a big week for developers here in Southeast Michigan. There are three big events you should attend:

Wed Nov 14th:  Windows 8 / VS 2012 Launch and InstallFest

This coming Wednesday, our local .NET developer group, AADND, is hosting an install fest / launch event for Windows 8 and Visual Studio 2012.  You can come and install Windows 8 and Visual Studio 2012 on your box. A number of people that have already worked with Windows 8 and VS2012 will be on hand to help, and to provide guidance. I’ll be there to help and to discuss the Open Source environment for Windows developers.

Thursday Nov 15th:  Doing Privacy Right. A workshop for app developers.

SRT Solutions is teaming up with the Association for Competitive Technology and the Mobile Technology Association of Michigan to raise awareness of privacy issues as it relates to mobile and app development.  We’ve got development experts, FTC officials, and legal and policy experts to help navigate what can be a complicated landscape. It is important information for developers to have at their disposal. I’ll be saying some opening remarks, and helping with Q and A on Windows 8 development.

Saturday Nov 17th: 1DevDayDetroit.

And the week ends with a full day of development goodness at Cobo Hall in Detroit. Dave McKinnon and Dave Giard have put together a strong program (well, I’m speaking too), and it promises to be a great day.  I am speaking on async / await features in C# 5 and what that means for .NET developers.

The first two events are free, and a great way to learn and grow your development skills.  1DevDayDetroit is $99.00. Check them out. All three events do require pre-registration. 

Created: 10/2/2012 7:11:14 PM

Thanks again to Carl and Richard for inviting me to come along to Omaha to join the awesome community in Omaha. I continue to believe that the strongest development communities are in the middle of the country. There are always strong crowds, engaged people, and good old mid-western friendliness. I’d love to see more of the big name conferences try locations in the Midwest.  There’s a huge untapped community of developers that would attend these conferences if not for the extra large travel expenses.  And, these developers are so energized that they are starting their own conferences in many of these locations.

Carl, Richard and I had a great discussion that is available here on .NET Rocks. We discussed how the software we create continues to change the world around us. My talk before the recording was around the concept that as developers our career is about changing the world and creating new possibilities. Software changes the way we do everything:

  • Delivering Health care has been radically changed by software.
  • Listening to music is completely different now that we buy music as files, not discs.
  • Watching TV and Video has been transformed by software.
  • Travel, retail, education.
  • Everything we is changed by software.

Our jobs are helping our customers create and adopt new workflows and new ways of leveraging software to make things better.

I talked about looking for different ideas, and being aware that often the best ideas are dismissed. As an example, I mentioned Steve Jobs fight to get the iPod released. His board fought him on that, saying that it had no market. The interview with Steve Jobs and Bill Gates that I reference is here. It’s long (2 hours or more), but it’s worth your time to listen to these giants of our industry discuss how they navigated long careers starting with home built computers on to the modern devices we now use.

The final point was why WinRT needs iTunes (or something like it). So many people use iTunes and and iPod (of some flavor) for their music source. Personally, I find much better value from ZunePass (now XBox live music). However, with the demise of the zune player device, those files aren’t portable. Music you download using your subscription is DRMed and can only be played on a linked device. I can’t plug my Windows 8 slate into my car. I can’t use it while I work out, or while I’m walking the dog. I need to get my music on an extremely portable device.

Today, that means iTunes and and iPod.

If I can’t do that on a WinRT device, I need another computer to manage my music library. That means I’m more likely to buy an Intel Windows 8 device, even if it’s only to manage my music. If I had a way to get my Zune music on a portable device (besides my phone), I’m set.

Created: 9/29/2012 7:27:37 PM

We released our first Windows Store app earlier this week:  A calculator app that supports multiple skins. 

We’re concentrating on adding the art and user experience to make a better experience for our customers.  The first skin is a steampunk skin.  It’s   novel look at a simple application:

SteampunkLandscape                                       SteampunkPortrait                               SteampunkSnap  

 

 

The Second skin is a kids calculator skin. Note that this skin has fewer functions than the steampunk skin. we wanted to make an app you’d be happy to let small children use to check their homework:

 

KidsLandscape                                   KidsPortrait                                       KidsSnapped

 

 

We also added history and sharing features. If you use the calculator in snap mode, or portrait mode, the screen has 5 lines of display instead of 1. Also, you can share from this app, putting all the calculation history as text in an email message, or a document.

We’re working on other skins and more functions.  Please use the comments to let me know what you’d want to see.

Created: 5/14/2012 4:15:00 PM
Yes, this is yet another of those notes about one of the Metro samples. This one discusses grouped views and semantic zoom. As was true in many of the recent samples, this one focuses on many of the features of Windows RT XAML. This one shows grouped data in grid views, and semantic zoom. I didn't take notes on the headers part of the sample, because it's really quite straightforward.  The semantic zoom is pretty cool though. Even here, the code (and the XAML) is very straightforward. In fact, almost everything is in the XAML. If your app supports semantic zoom, you just add a semantic zoom control to your page, and define the two different views (the zoomed out view, and the zoomed in view):
<SemanticZoomx:Name="semanticZoom"VerticalAlignment="Bottom">
 
<SemanticZoom.ZoomedOutView>
 
<GridViewForeground="White">
 
<GridView.ItemTemplate>
 
<DataTemplate>
 
<TextBlock
 
Text="{Binding Group.Key}"
 
FontFamily="Segoe UI Light"
 
FontSize="24"
 
Foreground="Black"/>
 
</DataTemplate>
 
</GridView.ItemTemplate>
 
<GridView.ItemsPanel>
 
<ItemsPanelTemplate>
 
<WrapGridItemWidth="75"ItemHeight="75"MaximumRowsOrColumns="1"VerticalChildrenAlignment="Center"/>
 
</ItemsPanelTemplate>
 
</GridView.ItemsPanel>
 
<GridView.ItemContainerStyle>
 
<StyleTargetType="ListViewItem">
 
<SetterProperty="Margin"Value="4"/>
 
<SetterProperty="Padding"Value="10"/>
 
<SetterProperty="BorderBrush"Value="Gray"/>
 
<SetterProperty="BorderThickness"Value="1"/>
 
<SetterProperty="HorizontalContentAlignment"Value="Center"/>
 
<SetterProperty="VerticalContentAlignment"Value="Center"/>
 
</Style>
 
</GridView.ItemContainerStyle>
 
</GridView>
 
</SemanticZoom.ZoomedOutView>
 
<SemanticZoom.ZoomedInView>
 
<GridViewItemsSource="{Binding Source={StaticResource cvs2}}"IsSwipeEnabled="True">
 
<GridView.ItemTemplate>
 
<DataTemplate>
 
<StackPanelOrientation="Horizontal"Margin="10,10,0,0"HorizontalAlignment="Left"Background="White">
 
<ImageSource="{Binding Image}"Height="60"Width="60"VerticalAlignment="Center"Margin="0,0,10,0"/>
 
<TextBlockTextWrapping="Wrap"Style="{StaticResource ItemTitleStyle}"Width="200"VerticalAlignment="Center"Text="{Binding Title}"HorizontalAlignment="Left"FontFamily="Segoe UI"/>
 
</StackPanel>
 
</DataTemplate>
 
</GridView.ItemTemplate>
 
<GridView.GroupStyle>
 
<GroupStyle>
 
<GroupStyle.HeaderTemplate>
 
<DataTemplate>
 
<TextBlockText='{Binding Key}'Foreground="Gray"Margin="5"FontSize="18"FontFamily="Segoe UI Light"/>
 
</DataTemplate>
 
</GroupStyle.HeaderTemplate>
 
<GroupStyle.ContainerStyle>
 
<StyleTargetType="GroupItem">
 
<SetterProperty="Template">
 
<Setter.Value>
 
<ControlTemplateTargetType="GroupItem">
 
<StackPanelOrientation="Vertical">
 
<ContentPresenterContent="{TemplateBinding Content}"/>
 
<ItemsControlx:Name="ItemsControl"ItemsSource="{Binding GroupItems}"/>
 
</StackPanel>
 
</ControlTemplate>
 
</Setter.Value>
 
</Setter>
 
</Style>
 
</GroupStyle.ContainerStyle>
 
<GroupStyle.Panel>
 
<ItemsPanelTemplate>
 
<VariableSizedWrapGridOrientation="Vertical"MaximumRowsOrColumns="3"/>
 
</ItemsPanelTemplate>
 
</GroupStyle.Panel>
 
</GroupStyle>
 
</GridView.GroupStyle>
 
<GridView.ItemsPanel>
 
<ItemsPanelTemplate>
 
<StackPanelOrientation="Horizontal"/>
 
</ItemsPanelTemplate>
 
</GridView.ItemsPanel>
 
<ButtonVisibility="Collapsed"/>
 
</GridView>
 
</SemanticZoom.ZoomedInView>
 
</SemanticZoom>
 
  I'm not sure why, but this sample sets the DataSource for the zoomed in view using binding, and sets the source for the zoomed out sample using code:  
cvs2.Source = dataLetter;
 
(semanticZoom.ZoomedOutView as ListViewBase).ItemsSource = cvs2.View.CollectionGroups;
 
The pinch gesture support is built into the control, so that just works. This sample adds a button to switch views, and that changes from the zoomed out to the zoomed in view when pressed:
privatevoid scenario3switchViewsClickHandler(object sender, RoutedEventArgs e)
 
{
 
    semanticZoom.ToggleActiveView();
 
}
 
Sure, this isn't rocket science, but it does show a couple worthwhile design ideas. For one, semantic zoom is not that much code. If your app should support it, do so. Second, while the XAML for Windows Metro looks familiar, there is some interesting new concepts there. The most important part about this sample is that semantic zoom is not about showing the same view in a larger or smaller view. Semantic zoom done right reimagines your data in a different view. The zoomed out and zoomed in views do display different controls. You have one view when you’re zoomed out. You have a totally different view of the data when you are zoomed in on a subset of the data.
Created: 4/11/2012 3:14:44 PM

This post doesn't have much code, but there's a few important points to remember for working with WinRT apps and application suspend and activation.

When your application starts, it becomes the active app. Your application will receive events that indicate your application is being started, loaded and activated.

If you've used Windows 8, you've probably noticed that you don't have any explicit way to terminate an application. (Yes, you can close an app, using the swipe action from the top to the bottom, but that doesn't actually stop the application from running.)

The environment will close your application if there's memory or CPU pressure on the machine. The first thing that will happen is that Windows will suspend your application if the system needs more resources. Your application will receive a Suspend event, and will have 5 seconds to store its state, and then the system will suspend your application.

If the system still needs more resources, the system will terminate suspended applications to free up more resources. Since your application was already suspended, your application won't get a new event for termination; rather the system will simply unload your application.
Your users have expectations around suspending, resuming, terminating, and restarting your app.  When the system suspends your application, you must save state so that you can resume your app's state exactly where the user left off. You need to respond to those events, save and restore state correctly.

First, suspend:  Suspend is easy.  Just save your state. Do it async, and don't take more than a few seconds. App storage will backup your state into the user’s Live account storage. It will automatically be visible across Win8 machines for that user.

Next, resume: You probably don't need to do anything here. Your app was still in memory, and can simply be resumed.  However, some applications, which may have time sensitive data (think news or weather apps) should look at the elapsed time and consider if they should update content. In addition, you may store state in the cloud. When you app resumes, you should consider that you may need to update the content based on the user working on your app on another machine (think EverNote). Once again, remember that the storage will be available across WIn8 machines.

Finally, consider Activated: You will get this event when your application starts.  One of the properties in the event arguments is the Previous Execution State. If this is the enum value Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated, that means your application was run previously, and saved state on suspend, and was then terminated by the system to free resources. You should restore state, and use the same guidance I just gave on resume.

Of course, if you've got to code these capabilities, you need to be able to test and debug these scenarios.  Visual Studio 11 gives you capabilities to do that. Unfortunately, the necessary commands are bit hidden.  It took me several minutes to find the right magic to find and turn on the right commands.  One of the new toolbars in VS 11 beta is the “Debug Location” toolbar.  You need to customize your toolbar, and turn on this feature.  It’s not on by default.  The “Debug Location” toolbar (shown below) contains three new commands to suspend, resume, and suspend then terminate the app being debugged:

toolbar

Once you've turned on that toolbar, simply debug your app. You'll have buttons on the toolbar button to suspend your app, or suspend and terminate your app. You can walk through the code that handles these features and ensure that your users will get the proper behavior.

Created: 4/6/2012 5:52:54 PM

This is another in my post series on WinRT programming for C# developers. For review, I’m blogging my notes on running and modifying each of the samples from this page: http://code.msdn.microsoft.com/windowsapps/Windows-8-Modern-Style-App-Samples

The next sample provides an overview of WinRT data binding.  This sample actually has seven different scenarios; it's one of the biggest samples so far.

However, I'm only going to briefly cover this sample.  TLDR Version:  If you've used DataBinding in WPF or Silverlight, it is very familiar.

For those interested in more:

You can support one way, two way, and one time bindings:

          <
          TextBox
          x:Name
          ="tbOneWayDataBound"
        
          Text
          ="{Binding ElementName=sliderOneWayDataSource, Path=Value, Mode=OneWay}"
        
          Grid.Column="2"Grid.Row="2"HorizontalAlignment="Left"VerticalAlignment="Top"Width="150"/>
          <
          TextBox
          x:Name
          ="tbTwoWayDataBound"
        
          Text
          ="{Binding ElementName=sliderTwoWayDataSource, Path=Value, Mode=TwoWay}"
        
          Grid.Column="2"Grid.Row="4"HorizontalAlignment="Left"VerticalAlignment="Top"Width="150"/>
          <
          TextBox
          x:Name
          ="tbOneTimeDataBound"
        
          Text
          ="{Binding ElementName=sliderOneTimeDataSource, Path=Value, Mode=OneTime}"
        
          Grid.Column="2"Grid.Row="6"HorizontalAlignment="Left"VerticalAlignment="Top"Width="150"/>

You can create Converters similar to WPF or Silverlight:

          <
          TextBox
          x:Name
          ="tbValueConverterDataBound"
        
          Text
          ="{Binding ElementName=sliderValueConverter, Path=Value, Mode=OneWay, Converter={StaticResource GradeConverter}}"
        
          Margin
          ="5"
          Width
          ="150"
          />
        

 

          public
          class S2Formatter : IValueConverter
{
          //Convert the slider value into Grades
        
          public
          object Convert(objectvalue, System.Type type, object parameter, string language)
    {
          int _value;
          string _grade = string.Empty;
          //try parsing the value to int
        
          if (Int32.TryParse(value.ToString(), out _value))
        {
          if (_value < 50)
                _grade = "F";
          else
          if (_value < 60)
                _grade = "D";
          else
          if (_value < 70)
                _grade = "C";
          else
          if (_value < 80)
                _grade = "B";
          else
          if (_value < 90)
                _grade = "A";
          else
          if (_value < 100)
                _grade = "A+";
          else
          if (_value == 100)
                _grade = "SUPER STAR!";
        }
          return _grade;
    }
          public
          object ConvertBack(objectvalue, System.Type type, object parameter, string language)
    {
          throw
          new NotImplementedException(); //doing one-way binding so this is not required.
    }
}

Other scenarios in this sample show how to respond to data source changes (It looks like INotifyPropertyChanged), bind to elements in a collection (just like in WPF or Silverlight) , bind to color properties (just like WPF and Silverlight), modify collections (like WPF and Silverlight), and navigate collections (like in WPF or Silverlight).

In short, it's really familiar code, if you've done anything with WPF or Silverlight.

Created: 3/28/2012 5:44:21 PM

The next Win8 sample shows the general form of the background task contract for Windows 8 Metro applications.

There are two parts to implementing a background task for a Metro style application: 

  1. Implement the IBackgroundTask interface (contract).
  2. Register the background task with the system so that Windows starts the task at the appropriate time.

The IBackgroundTask interface has only one method: Run().  The only parameter to Run() is an IBackgroundTaskInstance.  Your background task will communicate with the Windows system through the IBackgroundTaskInstance. In this sample, the background task registers to receive the Cancelled event from the IBackgroundTaskInstance if it should stop working on the current problem. The background task also updates the IBackgroundTaskInstance.Progress property to notify the system of its progress on the current problem.

You can think of the IBackgroundTask.Run() method as similar to the Task.Run() method in today's .NET environment: it's the entry point for your background task.

Registering a background task in WinRT is a bit more involved. Remember that this background task is not the same as just running something asynchronously. Instead, these background tasks communicate with the OS, so that they can receive events while your application is suspended. For example, a Mail client will be awakened, check mail, then update its live tile periodically when suspended. That requires using the Windows system Background Task contract.


You register a Background Task in a few steps, using a BackgroundTaskBuilder object. There are several properties you need to set on the BackgroundTaskBuilder:

var builder = new BackgroundTaskBuilder();
builder.Name = name;
builder.TaskEntryPoint = taskEntryPoint;
builder.SetTrigger(trigger);

The name is simply a name you use to identify the task (uniquely) in your application. The TaskEntryPoint is the fully qualified class name for the type that implements IBackgroundTask.

The trigger specifies when the task should be started. Any of the event types you specify must also be specified in you application's package manifest. If you don't specify the event types, your registrations will fail.

Aside: Here the sample seems a bit of a kludgy demo. They trigger some of the tasks when the machine's current TimeZone changes. That, I think, is just for demo purposes. It's easy for you (as the user) to switch time zones, and make the background task start. The other scenarios use a timer, and start the background task every 50 ms. That's closer to a production scenario, but a little short of a time span.

Once you've initialized the builder, you register the task:

BackgroundTaskRegistration task = builder.Register();

That BackgroundTaskRegistration object contains some additional APIs that you use to create and communication channels between your foreground task and your background task.

task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
 
private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
{
    //
    // Update the UI with progress reported by the background task.
    //
    SampleDispatcher.InvokeAsync(CoreDispatcherPriority.Normal,
    (task, args) =>
    {
        try
        {
            var taskCompletion = task as IBackgroundTaskRegistration;
            var completionArgs = args.Context as BackgroundTaskCompletedEventArgs;
            if ((taskCompletion != null) && (args != null))
            {
                if (completionArgs.Status != null)
                    throw completionArgs.Status;
                var key = taskCompletion.TaskId.ToString();
                var settings = ApplicationData.Current.LocalSettings;
                switch (taskCompletion.Name)
                {
                    case SampleBackgroundTaskName:
                        SampleBackgroundTaskStatus.Text = settings.Values[key].ToString();
                        break;
                    case SampleBackgroundTaskWithConditionName:
                        SampleBackgroundTaskWithConditionStatus.Text = settings.Values[key].ToString();
                        break;
                    case ServicingCompleteTaskName:
                        ServicingCompleteStatus.Text = settings.Values[key].ToString();
                        break;
                    case TimeTriggeredTaskName:
                        TimeTriggeredBackgroundTaskStatus.Text = settings.Values[key].ToString();
                        break;
                }
            }
        }
        catch (Exception ex)
        {
            Error.Text = ex.ToString();
        }
    },
    sender,
    e);
}
 
private void OnProgress(IBackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs e)
{
    SampleDispatcher.InvokeAsync(CoreDispatcherPriority.Normal,
        (task, args) =>
        {
            var taskRegistration = task as IBackgroundTaskRegistration;
            var progressArgs = args.Context as BackgroundTaskProgressEventArgs;
            if ((task != null) && (args != null))
            {
                switch (taskRegistration.Name)
                {
                    case SampleBackgroundTaskName:
                        SampleBackgroundTaskProgress.Text = "Progress: " + progressArgs.Progress + "%";
                        break;
                    case SampleBackgroundTaskWithConditionName:
                        SampleBackgroundTaskWithConditionProgress.Text = 
                        "Progress: " + progressArgs.Progress + "%";
                        break;
                    case ServicingCompleteTaskName:
                        ServicingCompleteProgress.Text = "Progress: " + progressArgs.Progress + "%";
                        break;
                    case TimeTriggeredTaskName:
                        TimeTriggeredBackgroundTaskProgress.Text = "Progress: " + progressArgs.Progress + "%";
                        break;
                }
            }
        },
        sender,
        e);
    }
}
 
 

Of course, if you can register background tasks, you probably want to unregister them and make them stop.
The sample unregisters the background task by looping through each task and removing the requested task by name:

foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
    if (cur.Value.Name == name)
        cur.Value.Unregister(true);
 
}
 

I'm assuming that you can also unregister the task by using the BackgroundTaskRegistration returned by the original register task call.
The key points to this sample are that there is a contract for Background Tasks that enables the your application to be awakened by Windows to perform some functions in response to time, or system events.

The keys to this sample are that there is a contract you should follow if your application needs to do periodic work while suspended, or running in the background. By following that contract, you’ll find much of the infrastructure you need is built into the operating system.

Created: 3/26/2012 4:25:16 PM

This post is part of my Windows 8 / WInRT exploration and notes.  This time, I’m digesting the WinRT Controls sample.

This sample has quite a few more features to digest. There are six different control scenarios. This application supports landscape, portrait, and snapped orientations. As a result, this post will get longer than my average post.

Screen Orientation Support

Most of the orientation support is provided by the underlying framework. Your application must  respond to the ViewStateChanged event:

Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().ViewStateChanged += 
          new TypedEventHandler
    <Windows.UI.ViewManagement.ApplicationView, Windows.UI.ViewManagement.ApplicationViewStateChangedEventArgs>
    (MainPage_ViewStateChanged);

When you receive this event, you instruct the Visual State Manager to transition to a particular state:


VisualStateManager.GoToState(this, 
    ApplicationView.Value.ToString() + DisplayProperties.ResolutionScale.ToString(), false);

The States must be defined in your main window's XAML description.  Your XAML must include a <VisualStateManager.VisualStateGroups> node.  This element contains a sub-element called VisualStateGroup.  The VisualStateGroup element contains a number of VisualState elements. These elements are named and those names are the states used in the GoToState call above.  Here's en edited version from the Controls sample:

          <
          VisualStateManager.VisualStateGroups
          >
        
          <
          VisualStateGroup
          x:Name
          ="OrientationStates"
          >
        
          <
          VisualState
          x:Name
          ="FullScreenLandscapeScale100Percent"
          />
        
          <
          VisualState
          x:Name
          ="FilledScale100Percent"
          >
        
          <!-- elided -->
        
          </
          VisualState
          >
        
          <
          VisualState
          x:Name
          ="FullScreenPortraitScale100Percent"
          >
        
          <!-- elided -->
        
          </
          VisualState
          >
        
          <
          VisualState
          x:Name
          ="SnappedScale100Percent"
          >
        
          <!-- elided -->
        
          </
          VisualState
          >
        
          <
          VisualState
          x:Name
          ="FullScreenLandscapeScale140Percent"
          >
        
          <!-- elided -->
        
          </
          VisualState
          >
        
          <
          VisualState
          x:Name
          ="FilledScale140Percent"
          />
        
          <
          VisualState
          x:Name
          ="FullScreenPortraitScale140Percent"
          >
        
          <!-- elided -->
        
          </
          VisualState
          >
        
          <
          VisualState
          x:Name
          ="SnappedScale140Percent"
          />
        
          </
          VisualStateGroup
          >
        
          </
          VisualStateManager.VisualStateGroups
          >
        

This application supports eight different visual states.  See the documentation for the ViewStateChanged event for more details.

Once the app is loaded, it runs mostly like a familiar WPF or Silverlight application. There is a control for the list of scenarios.  When you select a different scenario, the main window loads the input and output panes for that scenario.

With only one exception, the scenarios are entirely coded in XAML. Rather than put a lot of declarative XAML in the enntry, I'll point out the big picture concept:

If you have been writing WPF or Silverlight applications at all, the XAML used for the WinRT controls will be completetly familiar to you. Run the application, and you can likely guess exactly what the XAML looks like.
So far, Windows 8 apps look a lot like WPF or Silverlight apps (if you are a C# or VB.NET developer).

Created: 3/20/2012 7:52:23 PM

Over the weekend, I read this post “6 ways Microsoft is Killing the Traditional Desktop in Windows 8”.  Like many headline hungry opinion writers, there’s a large share of hyperbole in this article.  The headline also implies an incorrect motive.  I won’t speculate on whether or not Microsoft wants to kill the traditional desktop. However, I think I’m on safe ground when I say Microsoft wants the Windows 8 Metro desktop to succeed.  If you market and sell applications on Windows, you should rephrase each of his 6 ways as motivation for getting your applications on the Metro platform:

 

Your Users Start in Metro

Do you want your application front and center in your users’ cognitive space? Do you want them starting and running your application everyday?  Once Windows 8 comes out, that means running as a Metro App. If you want your application visible on a daily basis, using live tiles to update status, and enticing customers to launch your app, your application must be in the Metro start menu.

Modern Apps win

You have a choice of environments in Windows 8:  “Modern” (meaning Metro) and “Desktop”, meaning, well, not modern.  If you’re competitors are more modern than you are, they will win.

Touch First wins

The Modern interface is a touch first experience. Chris Hoffman is not the first author to mention the phenomena of wanting to use touch on his windows 7 machine after using Metro. It really is compelling. Once your users have a touch-first experience, they will gravitate toward those applications that work for them in the touch environment. If your application is the competitor with a solid touch experience, you can successfully take marketshare from competitors that have not made a touch investment.

Desktop applications are not first-class apps

The Desktop is a Metro app. That means desktop apps do not show up as individual apps in the task bar, or in task switching. They have limited features for sharing, standard metro menus, and more.

Metro apps will be more fully integrated into the Windows 8 experience than any legacy desktop applications.

Metro Apps have greater market reach

Windows 8 runs on Intel x86 and i64 processors. It also runs on ARM processors, used on tablet devices where battery life is a key driver.  Traditional desktop applications will not install on ARM devices running Windows 8 (exceptions may be made for Office, Windows Explorer, and a few other Microsoft applications.  If you want to reach the greatest market, you must create Metro apps.

The Windows App Store sells Metro Apps

The Windows App store makes it easy to install apps, try them, rate them, and purchase enhanced versions or add ons. It makes it easier for customers to try new applications safely, and purchase those apps they like the best. The App Store keeps track of the apps a user has purchased, and automatically installs any updates and bug fixes. That lowers your support costs: users will be automatically upgraded to the latest released version.

OF course, those business features are only available for Metro apps. If you’re trying to sell legacy desktop mode apps, you must still manage this entire process yourself. Once again, Metro apps incur lower costs, and gain new benefits from the ecosystem.

Some closing remarks

Windows 8 is a big change from Windows 7.  When it is released, existing Windows 7 apps will look as dated as Windows 3.1 applications looked when Windows 95 released. That change drastically modified the marketplace at the time. Those companies that were ready to ride the wave of Windows 95 started a very impressive growth curve. Their competitors that bet against change slowly faded from relevance. Regardless of the platform, the software industry has proven time and again that betting against the latest upcoming release is a bad idea. Stay close enough to the leading edge to stay relevant.

Created: 3/13/2012 3:14:41 PM

This post contains my notes from the "File Access" sample in the Windows 8 developer samples.

Let me start by noting that all these samples are designed to show how the API is structured.  These samples do not show proper separation of concerns, or architectural patterns like MVVM. In fact, all the code is in the CodeBehind for the MainWindows.xaml.cs.  Oh well, that's not what the samples are teaching.

There are two key takeaways from this sample.  First, IO programming in WinRT is very similar to IO programming in the .NET Framework. The addition of the 'await' keyword before each call is the only new technique here. Second, Metro applications should not just browse the file system for storage locations.  Each application should restrict its storage to the application specific document library.  The code shows both of these concepts pretty clearly.

The main Window's Initialize() code initializes a StorageFile object by searching for the file on disc, and creating the associated StorageFile object (asynchronously, of course):

async void Initialize()
{
          try
        
    {
        sampleFile = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync("sample.txt");
    }
          catch (FileNotFoundException)
    {
          // 'sample.txt' doesn't exist so scenario one must be run
        
    }
}

The other file APIs all work in a similar fashion.  Reading a file looks almost exactly like reading a file with the current .NET BCL library:

async void Scenario2ReadText_Click(object sender, RoutedEventArgs e) 
{ 
          if (sampleFile != null) 
    { 
          string fileContent = await FileIO.ReadTextAsync(sampleFile); 
 
          this.Scenario2Output_textblock.Text = "The following text was read from '" + 
 
                sampleFile.Name + "':" + Environment.NewLine + Environment.NewLine + fileContent; 
 
    } 
}

The Streaming APIs are also present, and look quite familiar:

async void Scenario4WriteToStream_Click(object sender, RoutedEventArgs e)
 
{
          if (sampleFile != null)
    {
          string userContent = Scenario4Textbox.Text;
          if (!String.IsNullOrEmpty(userContent))
        {
          using (IRandomAccessStream writeStream = await sampleFile.OpenAsync(FileAccessMode.ReadWrite))
            {
          using (DataWriter dataWriter = new DataWriter(writeStream))
                {
                    dataWriter.WriteString(userContent);
                    await dataWriter.StoreAsync();
                    await dataWriter.FlushAsync();
          this.Scenario4Output_textblock.Text = "The following text was written to '" +
                        sampleFile.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine +
                        userContent;
                }
            }
        }
          else
        
        {
          this.Scenario4Output_textblock.Text =
          "The text box is empty, please write something and then click 'Write' again.";
        }
    }
}
async void Scenario4ReadFromStream_Click(object sender, RoutedEventArgs e)
{
          if (sampleFile != null)
    {
          using (IRandomAccessStream readStream = await sampleFile.OpenAsync(FileAccessMode.Read))
        {
          using (DataReader dataReader = new DataReader(readStream))
            {
          uint numBytesLoaded = await dataReader.LoadAsync((uint)readStream.Size);
          string fileContent = dataReader.ReadString(numBytesLoaded);
          this.Scenario4Output_textblock.Text = "The following text was read from '"
                    + sampleFile.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + fileContent;
            }
        }
    }
}

I won't simply repost the rest of the code. This is enough to ensure that you get the main ideas.  There are two main ideas to get across from this sample:

1. Store your application's data in the application specific sandbox.

2. Use the familiar IO APIs, but remember that they are async.

Created: 3/12/2012 12:16:14 PM

Now that the Windows 8 Consumer Preview is out, I'm starting a series of blog posts on creating WinRT / Metro applications using C# and XAML.  As with other series I have done in the past, early on, these posts are my raw notes as I work to understand the new developer APIs and libraries.

Like most of you, I'm starting from ground zero learning WinRT. I've been running the Windows 8 Developer Preview since the //build/ conference, and I'm finally getting enough time to explore the developer APIs.  In time, this series should provide a quick and handy notebook toward finding how to solve specific problems using the WinRT platform. In this series, I'm looking at each of the samples you can download here. http://code.msdn.microsoft.com/windowsapps/Windows-8-Modern-Style-App-Samples Specifically, I'll discuss what you can learn from each of the samples. In this first post, I'll disect the Splash Screen Sample.

Why have a Splash Screen Sample at all?

This sample shows a few important rules for Metro apps.  All Metro apps can specify a splash screen resource. The Windows runtime will display that splash screen when the app starts. That's all you need to do if you want the system defined splash screen behavior. Open the package.AppXManifest file in Solution Explorer and define the image to use as the splash screen.

The Application configured Splash Screen will display for a system-defined period of time. Your application should be ready to display its main UI once the splash screen is dismisssed.

There are two important techniques to learn from this sample: How to display an extended splash screen, and how to avoid the need for an extended splash screen.

To display an extended splash screen, your application's startup code must created the extended splash screen, giving it the same coordinates as the system SplashScreen.

SplashScreen splashScreen = args.SplashScreen;
ExtendedSplash eSplash = new ExtendedSplash(splashScreen, false);
          public ExtendedSplash(SplashScreen splashScreen, bool dismissed)
{    
    InitializeComponent();             
          this.splashImageCoordinates = splashScreen.ImageLocation;             
          this.splash = splashScreen;             
          this.dismissed = dismissed;             
          // Position the extended splash screen image in the same location as the splash screen image.    
        
          this.extendedSplashImage.SetValue(Canvas.LeftProperty, this.splashImageCoordinates.X);             
          this.extendedSplashImage.SetValue(Canvas.TopProperty, this.splashImageCoordinates.Y);             
          this.extendedSplashImage.Height = this.splashImageCoordinates.Height;             
          this.extendedSplashImage.Width = this.splashImageCoordinates.Width;             
    LearnMoreButton.Click += new RoutedEventHandler(LearnMoreButton_Click);             
    Window.Current.SizeChanged += new WindowSizeChangedEventHandler(ExtendedSplash_OnResize);
}
Once the main splash screen is dismissed, the extended screen will be shown.

The second technique is to use the system SplashScreen's dismissed event to delay some actions, to avoid the need for an extended splash screen at all.

In your application startup code, you register to receive the dismissed event for the splash screen. You can (and should) defer as much work as you can until this event is raised. That enables you to show your UI sooner, and your app will be more fast and fluid.

Current Projects

I create content for .NET Core. My work appears in the .NET Core documentation site. I'm primarily responsible for the section that will help you learn C#.

All of these projects are Open Source (using the Creative Commons license for content, and the MIT license for code). If you would like to contribute, visit our GitHub Repository. Or, if you have questions, comments, or ideas for improvement, please create an issue for us.

I'm also the president of Humanitarian Toolbox. We build Open Source software that supports Humanitarian Disaster Relief efforts. We'd appreciate any help you can give to our projects. Look at our GitHub home page to see a list of our current projects. See what interests you, and dive in.

Or, if you have a group of volunteers, talk to us about hosting a codeathon event.