Windows Phone 7 CTP Refresh and InputScope#

If you haven’t heard the Windows Phone 7 CTP April Refresh has been released.  Prepping for my Toronto CodeCamp Session tomorrow I found an issue with setting an InputScope to TextBox.  I am basically doing the same demo Mike Harsh did at MIX10 where all InputScopeNameValues were used to populate a ListBox and then dynamically change the InputScope on a TextBox.

Pre April CTP you could use the following code

textBox1.InputScope = new System.Windows.Input.InputScope() { Names = new InputScopeName() { NameValue = InputScopeNameValue.AddressCity} };

with the April CTP for Windows Phone 7 this breaks now and gives an error of  “Property or indexer 'Names' cannot be assigned to -- it is read only”

Don’t know if it’s a bug or not but there is an alternative as follows.

textBox1.InputScope = new System.Windows.Input.InputScope() ;
textBox1.InputScope.Names.Clear();
InputScopeName isn = new InputScopeName() { NameValue = InputScopeNameValue.AddressCity };
textBox1.InputScope.Names.Add(isn);

Peter Foot also mentioned that you can use XAML to make this happen:

<TextBox Height="32" HorizontalAlignment="Left" Margin="324,70,0,0"
Name="textBox1" Text="TextBox" VerticalAlignment="Top" Width="137" InputScope="Text" />

and then dynamically set it with the following:

((InputScopeName)textBox1.InputScope.Names[0]).NameValue = val;

This is expected with CTPs, just wish it didn’t happen the day before a presentation!


Friday, April 30, 2010 11:21:17 PM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

Screen Capture on Windows Phone 7#

In some instances when working on projects we would require to take a screen capture of the current screen the user is working on.  I regularly did this on .NET Compact Framework 3.5 (pre Windows Phone 7) and is a little bit of mess because of all the PInvokes involved. 

I decided to create a quick sample app that captures the screen on both platforms to compare the code.  The sample app basically just places the captured screen inside a pictureBox control (NETCF 3.5) or Image control (Silverlight for WP7).  The outer PictureBox/Image control just displays some standard images that come with Windows 7.

Compact Framework 3.5   Silverlight (Windows Phone 7)
image   image

Here is a comparison of capture an image of the current screen on Windows Phone 7 using Silverlight and .NET Compact Framework

.NET Compact Framework

private Bitmap CaptureScreen()
{
    Bitmap b = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
    using (Graphics g = Graphics.FromImage(b))
    {
        IntPtr hdcSrc = IntPtr.Zero;
        IntPtr hdcDest = g.GetHdc();
        try 
        {
            //get the entire window by passing in IntPtr.Zero
            hdcSrc = GetWindowDC(IntPtr.Zero);
            //blit to the graphics object g
            BitBlt(hdcDest, 0, 0, b.Width, b.Height, 
                hdcSrc, 0, 0, SRCCOPY); 
        }
        finally
        {
            //Release any native src hdcs
            if (hdcSrc != IntPtr.Zero)
            {
                ReleaseDC(hdcSrc);
                DeleteDC(hdcSrc);
            }

            //Release the graphics hdc
            g.ReleaseHdc(hdcDest);
        }
    }

    return b;
}

[DllImportAttribute("coredll.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);

[DllImport("coredll")]
public static extern int DeleteDC(IntPtr hdc);

[DllImportAttribute("coredll.dll")]
internal static extern IntPtr ReleaseDC(IntPtr hdc);

public const int SRCCOPY = 0x00CC0020;

[DllImport("coredll.dll")]
public static extern bool BitBlt(IntPtr hdcDest, 
    int nXDest, int nYDest, int nWidth, 
    int nHeight, IntPtr hdcSrc, int nXSrc, 
    int nYSrc, uint dwROP);

Windows Phone 7 using Silverlight

private void btnCaptureScreen_Click(object sender, RoutedEventArgs e)
{
    //Capture the screen and set it to the internal picture box
    WriteableBitmap bmp = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
    bmp.Render(this, null);
    bmp.Invalidate();
    this.image1.Source = bmp;
    
    //Set a new background
    ImageBrush brush = new ImageBrush();
    brush.ImageSource = new BitmapImage(new Uri(NextImage,UriKind.Relative));
    ContentGrid.Background = brush;
    
}

Essentially the apps do the same thing but it’s a lot easier to do it on one than the other.  Here are some quick highlights on the differences.

  1. Silverlight for Windows Phone 7 has 7 lines of code while the .NET Compact Framework version has 28 lines of code
  2. With Silverlight for Windows Phone 7 you don’t have to deal with PInvokes anymore.
  3. Windows Phone 7 codebase is a lot smaller and more maintainable.
  4. With silverlight for Windows Phone 7, controls automatically support transparencies which was a challenge on NETCF 3.5 (notice the white box on NETCF 3.5 screen, that’s a PictureBox control
  5. Currently on Windows Phone 7 there is no way to get the images from your device in the form of a file unless you upload to a web service or something similar

Give it a try for yourself and download the sample code here.


Monday, April 19, 2010 1:42:59 PM (Eastern Daylight Time, UTC-04:00) #    Comments [2]  |  Trackback

 

Can Windows Phone 7 Multitask?#

[UPDATE – April 12, 2010: the test below is a bug in the Windows Phone 7 CTP Emulator as I expected.  Expect the Pause/Resume/Suspend functionality to be fixed in future emulators and to work on a real device.  Don’t rely on your threads running in the background in future versions and offload background processing to a server and use Push Notifications to update/notify device.]

There has been a lot of talk about how Microsoft is behind the ball on Windows Phone 7 since it can’t multitask since Apple announced iPhone 4.0 OS will now include multitasking.

What’s my take on this?  Well, Windows Phone 7 is based on Windows Embedded CE.  Without going into too much details on Windows CE, it is basically a real-time operating system and is not a trimmed down version of their desktop Windows OS.  Windows CE is it’s own full fledged real-time operating system and yes it can do multitasking. 

In all the years I’ve been developing Windows Phone and Windows CE software for customers, I have seen lots of applications that just go out and kill the battery, launch X number of threads or do things that are just not too smart and really kills the end user experience on the device. Think about it, when an app kills the battery in 1hr, the end user will usually say “this phone sucks” and returns it. In reality it’s not the phones fault, it’s the crappy app! This has always been a problem that has plagued Pocket PC/Windows Mobile/Windows Phone 5.x – 6.x for some time.  Windows Phone 7 is about the end user and making sure their experience with the phone is top notch.  This post on Windows Phone 7 and “Focus” by Charlie Kindel talks a bit more about the end user experience.

Back to the question, Can Windows Phone 7 Multitask?  Of course it can, it’s just not fully exposed to third party developers.  Things like the Zune player will continue to run in the background even if it’s not the foreground app.  What the Windows Phone 7 team has done is scale back some of the power a third party developer has so the end user experience is not compromised. 

So as a third party developer what’s available to us?  Peter Torr gave a session at MIX10 called Building Windows Phone Applications with Silverlight (Part II) and shows this diagram of application state when jumping to another application.

 

image

So your application has four states:

  1. Running – Here your application is started by the user and will run
  2. Paused – User decided to switch over to another application or answered a phone call (remember the device is a phone too :).  Here you should save your application state in case you go into “Suspended” state
  3. Suspended – Here you could assume your application is being killed by the OS.  That’s ok as long as you saved your state when you are paused.
  4. Resume – The user has started your app again and you want to resume where they left off since you saved state when paused

Because there is a suspended state, it doesn’t mean your app will always get suspended.  Your app will only get suspended if they OS feels that it is running low on resources.  (Remember, the phone doesn’t run a quad core processor with 8GB of ram :)  Once the OS is running low on resources it will start Suspending (or killing) apps most likely starting with the one that has not been in the foreground for the longest time.  To me it sounds very similar to WM_HIBERNATE and old school Windows Phone and Windows CE developers will know all about this.

So, being a curious developer, I tested the “Paused” state above but because the Windows Phone 7 Dev tools are CTP I can’t come to a definite conclusion.  Basically I created a simple app that continues counting on a background thread and updates the UI

image

Without hitting the “Back” button (because that will close my app), I clicked on the “Start” button and started the EnergizeIT Mobile app and logged in to get to the main screen.  I then clicked on the “Start” button again, opened the Start Menu and opened the WPMultitask1 sample app and my counter was incremented to 1724 from 1676.  In fact, I’ve been running it in the background for about 1,700s while I was writing this post.

image

Because I am using a CTP, maybe the “Pause” state does not work yet.  Couldn’t really test the “Suspended” state because all the Windows Phone 7 emulator has is Internet Explorer so most likely can’t use up all resources on the device.

In the end, Windows Phone 7 can do multitasking but is just limited to third party developers.  My test above shows a Thread in an app will continue to run while not being the foreground app.  Since iPhone OS 4.0 was just announced and now will support multitasking, my guess is the Windows Phone 7 team may consider opening up multitasking a bit more to third party developers.  Maybe during marketplace submission there will be a check box that says “My application requires access to run in the background” and the testing process will be more rigorous (yes I’m over simplifying it). The OS has the power to do multitasking, it’s just a matter of doing it right and preserving the end user experience.

Here is the code to run the threads:

/// <summary> /// thread to update the counter /// </summary> private Thread m_counterThread; /// <summary> /// Waithandle to tell the thread to stop /// </summary> private ManualResetEvent m_waitHandle = new ManualResetEvent(false); /// <summary> /// The current count to display /// </summary> private int m_count = 0; public MainPage() { InitializeComponent(); SupportedOrientations = SupportedPageOrientation.Portrait |
SupportedPageOrientation.Landscape; //enable disable the buttons btnStop.IsEnabled = false; } private void btnStart_Click(object sender, RoutedEventArgs e) { if (m_counterThread == null) { m_waitHandle.Reset(); WaitHandle[] handles = new List<WaitHandle> {m_waitHandle}.ToArray(); m_counterThread = new Thread(() => { //Main counter thread int index = WaitHandle.WaitTimeout; while (index == WaitHandle.WaitTimeout) { //incrememnt the counter m_count++; //update the counter label this.Dispatcher.BeginInvoke(new Action(() => { //Update the lable counter.Text = m_count.ToString(); })); //Wait for the stop handle index = WaitHandle.WaitAny(handles, 950); } }); //Start the thread m_counterThread.Start(); } //enable disable the buttons btnStart.IsEnabled = false; btnStop.IsEnabled = true; } private void btnStop_Click(object sender, RoutedEventArgs e) { if (m_counterThread != null) { //tell the main thread loop to stop m_waitHandle.Set(); //wait here till the thread stops m_counterThread.Join(); m_counterThread = null; //enable disable the buttons btnStart.IsEnabled = true; btnStop.IsEnabled = false; } }

And here is the partial Xaml for the page (ContentGrid)

<Grid x:Name="ContentGrid" Grid.Row="1">
    <TextBlock x:Name="counter" Text="[Counter Text]" 
               Style="{StaticResource PhoneTextPageTitle2Style}" 
               Margin="0,119,0,414" 
               TextAlignment="Center" />
    <Button x:Name="btnStart" 
            Content="Start Thread" 
            Click="btnStart_Click" 
            Margin="70,334,76,205" />
    <Button x:Name="btnStop" 
            Content="Stop Thread" 
            Click="btnStop_Click"
            Margin="70,453,76,90" />
</Grid>

Friday, April 09, 2010 2:30:11 AM (Eastern Daylight Time, UTC-04:00) #    Comments [1]  |  Trackback

 

Going from Windows Phone 6.5 to Windows Phone 7#

I recently blogged about the EnergizeIT Insurance mobile app we built for Microsoft as part of the From the Client to the Cloud tour across Canada. (BTW there is still time to register for this as the last event is April 14 2010 in Toronto).

We did create this project before any announcement on Windows Phone 7 was made so it was created for Windows Phone 6.5. Since the announcement of the Windows Phone 7 developer tools I decided to port the existing .NET Compact Framework 3.5 code to Silverlight for Windows Phone 7.  Considering I have only ‘played’ with Silverlight for the web and opened up some samples in Expression Blend, I figured it would be a good opportunity to learn the tools. 

Porting the application was pretty straight forward.  I was able to reuse some of the code but most of the code was not portable like pInvoke code and some custom controls primarily because it is not supported on Silverlight for Windows Phone 7.  This is a good thing because there is less code to maintain and allows you to focus on your software and not the intricacies of the Windows Phone platform.  This is a welcomed change!

In terms of re-using existing C# code, a lot of the business logic code was able to be re-used (since it was C#) which I believe to be more important.  I was also able to leverage the existing WCF services in the Windows Phone 7 app without any modifications to the backend services or database.

From a BCL perspective, there are a few differences in the Silverlight for Windows Phone 7 APIs compared to .NET Compact Framework 3.5. Primarily there are different classes or namespaces to integrate with the phone such as the Application Bar instead of System.Windows.Forms.Menu and things like your mobile app running in a ‘sandbox’ and you have no access to things like the file system. But, making the transition from .NET Compact Framework to Silverlight for Windows Phone 7 was extremely easy.  By far the easiest part was creating a ListBox, once I figured out how to DataBind and use DataTemplates, where the ListItems contained images and more than one line of text and each line having different fonts.  This I have to say was a snap!

The most effort for myself was learning Expression Blend and figuring out how to do transitions and animations within Expression Blend. Once I figured out storyboards and timelines, making an animation was just too easy. I also took some time to learn how to create custom controls and modifying some existing Silverlight samples that are available on the web to work on Windows Phone 7.  Since Windows Phone 7 also brings some new design principles called Metro, I also took the time to read and understand the Windows Phone UI Design and Interaction Guide and re-watched the Windows Phone UI and Design Language after seeing it at MIX10.

Overall, porting the app took about 7 days in total with most time going into porting 15 forms, creating 2 custom controls and experimenting with animations within Expression Blend.  Porting the C# code was extremely straight forward as most of the previous code was re-used and nothing was touched on the backend services.  In fact, both the Windows Phone 7 and 6.5 client use the exact same services.  I would estimate about 50% of my time was used in creating the UI primarily in learning Expression Blend, creating custom controls, creating transitions and animations and porting forms.  The rest was porting/re-using C# code and learning the new BCL and Windows Phone specific namespaces/classes.

Conclusion, developing good looking applications for Windows Phone 7 is a hell of a lot easier than building a good looking application for Windows Phone 6.x!  Existing Silverlight and Windows Phone developers should not have any issues developing beautiful and compelling mobile applications for Windows Phone 7 using Silverlight. 

The first time I saw Silverlight for Windows Phone (Windows Mobile back then) was in 2007 at MIX and MEDC Conferences from Scott Holden (who coincidently is now part of the XNA for Windows Phone 7 team).  I even have a few posts on Silverlight for Mobile from 2008! For me it’s been three years for Silverlight to come to the phone and it’s a very welcomed change.

In the next few posts I’ll follow up with some more details on things like code sharing, custom controls that were created and some differences on going from .NET Compact Framework to Silverlight for Windows Phone 7 such as saving application state.

Here are some screens with a comparison of the Windows Phone 6.5 and 7 versions.  Stay tuned!

Login Screen

image

Main Screen

image 

On The Road Screen

image

Settings Screen

image

Insurance Card Screen

image

New Claim Screen

image

Location Screen

image

Other Incident Info Screen

image


Thursday, April 08, 2010 9:56:13 PM (Eastern Daylight Time, UTC-04:00) #    Comments [1]  |  Trackback

 

Developing for the Third Screen - Windows Phone 7#

The Toronto .NET Code Camp is coming up and I’ll be presenting my first Windows Phone 7 developer session titled Developing for the “Third Screen” – Windows Phone 7

For the longest time Microsoft has been talking about their “Three Screens and the Cloud” strategy but did not really have a compelling mobile story. With the arrival of Windows Phone 7, the third screen has arrived and with that the new Windows Phone developer story has arrived. During this session you will get a high level overview of the platform plus go into some of the new APIs available for Windows Phone 7. We will cover the new application model, themes, Windows Phone 7 specific services, sensors, Bing Maps, software keyboard, multimedia and briefly the new Design Language ‘Metro’. Come and learn how to build for the third screen, build for Windows Phone 7.

 

I’ll have lots of sample code and you will get up to speed on what is available on for developers on Windows Phone 7. If you have developed for previous versions of Windows Phone be sure to check out this session because all developer tools have changed.

There are some other sessions on Windows Phone 7 specifically using Bing Maps and XNA presented by Nick Landry and another on using Silverlight and Windows Phone by Mano Kulasingam.

Not interested in Windows Phone 7 (I don’t see why not!) then there are a whole host of other session covering a wide range of topics.

If you are in the Toronto area be sure to register for the event on May 1 2010.


Wednesday, April 07, 2010 4:53:27 PM (Eastern Daylight Time, UTC-04:00) #    Comments [1]  |  Trackback

 

EnergizeIT: From the Client to the Cloud – The Mobile App#

I few months ago RedBit was asked by Microsoft to help them create a Windows Phone 6.5 demo application for EnergizeIT: From the Client to the Cloud tour across Canada. 

The purpose of the mobile software was to allow a fictitious insurance company to AppLogo_Splash_VGA_thumb[7] collect car accident information from a consumer. The consumer would be able to fill in basic information about the accident, take pictures of the incident, get the GPS location including address of the accident and submit this to a backend system where the data can be collected and acted upon.  The goal was to show EnergizeIT attendees how to leverage the Microsoft based platform and tools such as Silverlight, .NET 4.0, Azure and Visual Studio 2010.  The mobile software used .NET Compact Framework 3.5 but I’ll have a future post on porting it to Windows Phone 7.

RedBit’s role was to get the data from the Windows Phone to the backend database.  Our goal was also to make the mobile app look a little nicer than traditional Windows Mobil apps. What we created is a mobile client to have the consumer enter accident information and also created a WCF service to allow consumers to submit the data for the insurance company to act on. 

image image image

For location support we created a WCF service to reverse geocode a location to provide a readable address and an image of the location via Bing Maps API.

image image

The user would also be able to see their insurance card and the autos that are insured cars under their policy.

image image

We also included a feature called On The Road that allowed you to search for various services around you. 

imageBy the way, you can download Find My Bru from Windows Phone Marketplace now.

Overall, I think we were able to deliver a pretty good looking functional app on Windows Phone 6.5 (with a lot of effort for the UI).  Thanks to Christian Beauclair and the rest of the Canadian DPE team for giving us the opportunity to build this app for Windows Phone. 

Unfortunately, I won’t be publishing the source to this app but will be following up on blog posts showing some code snippets that I think will be useful to the developer community. 

I’ll also be following up in another blog post on porting this mobile application to Windows Phone 7 and what code we were able to re-use and most importantly, how easy it is to make a good looking app on Windows Phone 7.

If you want more info on the app please feel free to contact us at info[@]redbitdev[dot]com


Tuesday, April 06, 2010 3:16:49 PM (Eastern Daylight Time, UTC-04:00) #    Comments [1]  |  Trackback

 

All content © 2010, Mark Arteaga
Related Sites
Archives
Sitemap
Disclaimer

Powered by: newtelligence dasBlog 1.9.7174.0

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts