Jaime Rodriguez
On Windows Phone, Windows Presentation Foundation, Silverlight and Windows 7

  • Jaime Rodriguez

    transcript from background agents Q&A..

    • 3 Comments

    Last week we did a video on background agents for the Inside Windows Phone show..    If you want to go deep into agents, you must watch the video. It is here.

    To lure the super starPeter Torr into coming and doing yet another video on background agents, I had to prove to him the questions were deeper than what had already been covered in his knowledge chamber video and on his blog post series on agents. This is the email thread with the Qs and Answers that we covered in the video.  The email thread on questions ended up being (imo) a good way to document the details, so sharing it below as a supplement to the video  - again, go watch the video now.

    Full disclaimer: these are implementation specific details that might change in the future; or might even change under specific circumstances in Mango.  Use them (as a developer) to plan and design a great experience, but in the end it is still a phone, so code safely.

    Q: How much memory does each agent get ?
    Peak working set is 6MB for periodic and idle agents. Note that the runtime takes > 2MB of memory, so your agent really gets < 4MB.
    When agents exceed the memory limit, even momentarily, they get terminated with or without an OOM exception (depending on whether OOM happened in managed or native memory).
    For periodic and resource intensive agents, the scheduling service will auto-disable agents that crash or OOM twice in a row. Note that RI agents are also run in RR cycles.

    Q: How much CPU does each agent get? what can people do to not exceed it..
    t is a different story for audio and generic agents.  For Audio: the OS ‘guarantees’ that the agent gets ~10% of CPU time every 5s. Depending on the foreground activity, the agent can use more – the average CPU is not limited in most cases).
    Note that audio player and streaming agents share the same process and the resources (memory, CPU).

    For periodic agents, expect to get 10-20% CPU in real time use due to parallel execution: we run up to 5 agents in parallel when the phone is locked.
    This means an agent that uses L2S and networking and finishes in 15s may take more than 25s when run with other agents.

    The CPU ‘guarantee’ here is 10% every 15s (which is rarely useful unless you are dealing with a foreground CPU-heavy app like IE). Again no CPU limit.
    When there is low CPU activity in the foreground, agents can use as much CPU as they need.

    One way to present this is: agents and foreground experiences share the same priority but run with different thread quantum allocation that ensures that, in most cases, the foreground app gets at least 70% of the CPU time.

    Q:. How often do generic agents run? 
    Around  every 28 minutes.  See details below.

    Q: What is the algorithm for generic agents? what is the battery threshold?  Do they still run in battery saver mode?
    Periodic agents don’t run when battery saver mode is On. They also don’t run when the phone battery is low (<20%). RI agents can’t run until the battery is at least 91%.
    The periodic schedule is a little fuzzy to align with other scheduled network activities (for example email sync and push client keep-alive signals). It is scheduled to run every 28 minutes but the schedule can be invoked earlier in some cases (delta can be up to 10min). Also agents don’t run immediately after boot – they are delayed for ~30min.

    Q: What is limit on # of agents in a phone? What error do devs get when that limit is reached?
    No limit for Resource Intensive. Max of one audio agent at a time. For Periodic the limit is phone memory dependent. On devices with limited RAM (under 384MB), it is 9 agents, otherwise it is 15. You get an exception when the limit is hit (you have to check the error string unfortunately).


    FAQ on things you can or can’t do from background agent:
    Q:Can I pin  a new tile?

    No.

    Q: Can I update a pinned tile?
    Yes, and you can delete pinned tiles

    Q: Can I instantiate UIElements (even if not in a visual tree)? For example to create an image?
    Yes, and you can probably also enable properties by adding controls to the ‘invisible’ RootVisual, e.g. with something like:((Panel)(Application.Current.RootVisual)).Children.Add(control);
    You can use this for example to render user controls in the background (e.g. to create dynamic tiles). Watch out for the memory impact though always aim for <4.5MB peak.

    Q: Can I create sockets, files, etc. open database, etc.. 
    Yes, with one caveat: RI agents cannot go over cellular connection. This means RI agents will need a wifi connection to use sockets.
    (The desktop connection is disabled when tethered for sockets in general, but that is more noticeable for RI agents).

    Q:  During debug, is it possible to run my agent more often than every 30 mins?  
    Yes, use the LaunhForTest APIs;  Peter covered this in the video.  

    Happy Windows Phone coding.  I will be back in full swing soon. 



  • Jaime Rodriguez

    Useful Mango Developer Resources

    • 2 Comments

    With the Windows Phone (codenamed) Mango beta release, the Windows Phone team thrived to have great documentation and useful learning resources for WP7 developers.
    I think they did a superb job and given it came after MIX (and we had lots of great video content) the docs have gone unnoticed a bit, so I want to highlight a couple of these resources to make sure developers are getting the most out of these.   Today, I will cover the documentation improvements and the new “Mango” training kit.

    <shortcut>
    If you rather watch videos, here are two that summarize this post:
    Luke Nyswonger, lead for Windows Phone online documentation does a video walk through of all the new stuff in the docs.
    Yours truly does a walk-through of tidy, one of the apps in the training kit. It is a scenario that we use for five labs: sql ce, background agents, tiles, background transfer, and reminders.
    </shortcut> 

    New Mango training kit:
    With the new Windows Phone training kit for Mango release, we did a few things different:

    • The kit is aimed at intermediate level developers. It goes straight into Mango features and the labs are shorter because we skipped a lot of the intro stuff.. Most of the readers for this blog will feel very comfortable and new developers will pick it up quickly and still have the prior Windows Phone Training Kit for introductory material.  
    • The kit takes a scenario approach where instead of having ten or twelve disaggregate/unrelated labs, you have a few hands-on labs that show how multiple features come together to fulfill a scenario.

    Here are some of the new samples you will find in the training kit:

    • “Tidy” is a proof of concept to-do list application that takes advantages of Mango features to do smarter tasking. 
      Again, you can see Tidy in action in this video walk-through. If you do Mango presentations or demos, Tidy is a good demonstrator of how new Mango features make an existing application much better. 
      The hands-on labs map quite well to the features it showcases
      • Local database hands-on-Lab. Tidy uses SQL CE as its data store and the hands-on lab will show you how to attribute the object model to create LINQ to SQL mappings. How to create databases at run-time, and how to query the database.
      • Alerts and Reminders hands-on-lab.  Tidy allows you to create reminders for a task. The hands-on lab shows you how to query it a reminder exists, how to create and delete a reminder.
      • Start Tile pinning hands-On-Lab. Tidy allows you to pin every project so you can deep-link into a project. This way if your tasks are organized you can deep-link into project specific views and get the tasks for that specific project.
      • Background Transfer hands-On-Lab shows you how to use the new background transfer APIs to upload and download a backup of the database to your local machine.
      • Background agents hands-on-lab shows you how to create background agents in Mango.  The background agents check your location every 30 minutes and if you are nearby a location where tasks are due, it will prompt you a shell toast notification to remind you to complete the task while you are at that location. 
        The background agent also demonstrates how to update the tiles from an agent – it checks tasks that are overdue and it updates the tile for the project with the count-.
    • The “Photofun”  hands-on lab demonstrates the new live camera stream APIs. It captures the live camera stream and applies effects to it; it integrates with the camera hardware button to capture images when the button is pressed.
    • The XNA 3D Model Viewer hands-on-lab shows you how to use the new shared graphics model so you can visualize XNA-based 3D models in a Silverlight application.   It also demonstrates using the new background transfer APIs to download the models from an Azure store.
    • The new device capabilities hands-on lab shows you how to use the new Mango APIs (and some 7.0 APIs) to query device capabilities.  With the new APIs you can detect if compass and gyro are supported, you can detect the type of network connection the device is using, and other generic device information.

    Great improvements and additions to the documentation

    The documentation team also did a few things different. 

    • There is a great “What’s new” page that you can use to get to all the feature overviews, code-samples, etc..
    • The samples and how-to walkthroughs are now a bit more scenario oriented. For example, their sockets demo is a full blown tic-tac-toe game.
      They have a lot of comprehensive how-tos on the new APIs. Including the profiler, camera APIs, Background APIs, etc.  If it’s new, you will find a how to! 
    • They have moved the User experience Design guidelines from a PDF to an HTML format and they literally doubled the amount of content that went into the UX guidelines.
    • They have moved the certification requirements from a PDF to an HTML format, and they have included the test steps so you can ensure you test ahead of time (or if you fail certification you have repro steps.
    • They have a very nice “developer resources page” in the apphub that aggregates all the content that Windows phone developers will need

    Again, if you want to see a brief video of these changes, Luke will give you a walk through in this video

    With all the above changes, developers can find every thing easily, they get a very comprehensive (and deep) view into the features, and they can even have fun while doing it.
    Thanks to the doc teams (and the PMs that reviewed it ) for all this goodness; I am sure I missed some; if you find it, comment on it please (or write your own blog post about it ).

    Happy Windows Phone coding! Don’t forget to read the docs.

  • Jaime Rodriguez

    Windows Phone emulator software input panel and orientation

    • 0 Comments


    I hope I am not the only person who did not know this (apologies if that is the case).

    <context>
    A few weeks ago while at an event in Finland, my emulator did not detect an orientation change during a demo. Some one suggested I restart the emulator, I did, and it worked (against my instinct). Today, I found out what’s going on.
    </context>

    <answer>
    When you use the Page Up/Page down button, the emulator let’s you toggle the Software Input Panel (SIP) on and off.  Also when you use the Pause/Break button the emulator disables the SIP and let’s you enter text via your keyboard.   All that works neatly as expected. I use that all the time.   The part I did not know is that the emulator does not support orientation changes when the keyboard is enabled. This is all well documented in the keyboard mapping page: http://msdn.microsoft.com/en-us/library/ff754352(v=VS.92).aspx but I did not know.
    Not sure if it has always been documented and I missed it or it is new; either way, fooled me once.. but not again..
    </answer>

    Happy Windows Phone coding (and don’t forget to read the manual now and then !!)

  • Jaime Rodriguez

    System Tray Progress Indicator

    • 1 Comments

    In my last post, I teased that system tray in Mango is now customizable and data binding friendly Winking smile 
    On top of that, the SystemTray now has a ProgressIndicator  that you can use to replace your PerformantProgressBar and display progress on async operations.  

    Here is everything you need to know (or everything I know) about ProgressIndicator. ProgressIndicator

    It is a DependencyObject so  you can data bind to it.. 
    You can use these properties to customize and manage the indicator:

    • IsVisible (type boolean) to show/hide it.  This is separate from SystemTray.IsVisible. The SystemTray must be visible for the progress indicator to be visible too.
    • IsIndeterminate (type boolean) property. When this property is set, you will see the infamous ‘dancing dots’ that we show for indeterminate progress every where on the phone.
    • Value property (type double) that you can use to show value (normalized 0 to 1) when your indicator is not indeterminate.
      It also
    • Text property is used to display a message in the progress indicator.

    A few small quirks and tips :

    • The Text has a margin that you can’t control.  Not a huge deal, I assume consistent with OS.
    • The progress indicator’s text does pickup the Foreground color you are using for the SystemTray, but the indeterminate dancing dots (or the progress bar) do not pickup the color though. They are using PhoneAccentBrush.
    • I found out that I could not access (programmatically) the SystemTray.ProgressIndicator property until page is loaded. I got an InvalidOperationException saying “To get SystemTray ProgressIndicator the RootVisual must be a PhoneApplicationFrame and its Content must be a PhoneApplicationPage”. Not a huge deal, you can listen to loaded and check if you have initialized it before (since Loaded can fire multiple times in a page instance).
    • Use BindingOperations.SetBinding ()  to bind to DependencyObjects (where you normally use FrameworkElement.SetBinding).

    The screenshot to the right  shows you all of SystemTray’s properties in action.   It has a white foreground and green background with 60% opacity, indeterminate progress indicator and (obviously) custom text in the indicator.
    You can turn everything on and off to see the impact as you tweak each property.
    It is all data bound; there is no manual setting of any properties.  I am running on light theme with orange highlight.

    You can get the source  from my skydrive.

    Happy Windows Phone “Mango” coding.

  • Jaime Rodriguez

    Customizing SystemTray’s Background in Mango

    • 0 Comments

    A missing feature from Windows phone 7.0 was the ability to set the Background and Foreground color in the SystemTray.
    For branded apps (like Facebook) this was a problem cause the tray looked ugly, so most of these apps had to hide it, hiding important notifications (like clock, battery indicator ) from the user..

    In Mango, you can finally set Foreground (of type System.Windows.Media.Color ), and Background (type Color too) on SystemTray
    I hope that going forward, all apps start setting IsVisible=”true” on the system tray. There is no excuse now for hiding it any more.

    I just looked at the API and found two other nice surprises:

    1. SystemTray has an Opacity property.   The reason this is nice is because PhoneApplicationFrame applies the same logic to SystemTray than it does to ApplicationBar:
      If your SystemTray is not 100% opaque (that means if Opacity < 1.0) , the space for the tray is not reserved in layout, so you can get a few pixels back… Your page gets full height and it is up to you to reserve space for the tray).
      If your SystemTray is opaque (Opacity = 1.0) and visible,  then frame reserves the space, and your page loses 32 pixels at the top when in portrait and
    2. SystemTray is a DependencyObject and since we are now running on SL4, DependencyObject can be data bound;  hooray for SL4 on phone.

    Of course, there is one more nicety in SystemTray (ProgressIndicator).  I will share my code on that in the next post (hopefully tomorrow)..

    Happy Windows Phone “Mango” coding!!

  • Jaime Rodriguez

    Where is RichTextBox in the Mango beta?

    • 0 Comments

    if you try using RichTextBox in the recently released Mango Beta tools, you might notice the control does not have a default control template applied to it.  [That means when you try to use it, you will see nothing but not get an error either]. 

    This is a known issue for the beta.  To get around it, simply apply this current Style to the page (or the App.xaml) for your project .

    <Style TargetType="RichTextBox">
          <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeNormal}" />
          <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}" />
          <Setter Property="Background" Value="Transparent" />
          <Setter Property="BorderBrush" Value="Transparent" />
          <Setter Property="BorderThickness" Value="0"/>
          <Setter Property="HorizontalContentAlignment" Value="Stretch" />
          <Setter Property="VerticalContentAlignment" Value="Center" />
          <Setter Property="Padding" Value="0" />
          <Setter Property="Template">
            <Setter.Value>
              <ControlTemplate TargetType="RichTextBox">
                <Grid Background="Transparent">
                  <Border Background="{TemplateBinding Background}" 
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}"
                Margin="{StaticResource PhoneHorizontalMargin}">
                    <ContentControl x:Name="ContentElement"
                  HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                  VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                  Padding="{TemplateBinding Padding}"/>
                  </Border>
                </Grid>
              </ControlTemplate>
            </Setter.Value>
          </Setter>
        </Style>
    

    Notice we are using an implicit style (yay for Silverlight 4 on the phone!! )

    Another known issue with the current beta build is that images are not showing up in the rich textbox (they show up in the designer in Visual Studio/Blend )but not at run-time.  This is also fixed in later builds.  Still, the template above should be enough to get you rolling with RichTextBox.

    Happy Windows Phone coding!!

  • Jaime Rodriguez

    Slides and samples for the Helsinki mobile day event..

    • 1 Comments

     

    Thanks to those that attended our all-day Mobile Day event in Helsinki.     
    As promised, the content follows.

    • The decks are here.
    • The sample code is here.

    Thanks again for attending.

    Happy Windows Phone coding!

  • Jaime Rodriguez

    Inside Windows Phone show is back

    • 0 Comments

    With all the new coming features in Mango, I had to bring the show back..  Every Friday expect an episode or two between now and Mango’s RTM].

    This week, we have two new episodes

    Please help me get the word out on the show’s comeback. We have lots of good, deep!! content coming..

  • Jaime Rodriguez

    An update from Windows Phone developers themselves

    • 3 Comments

    The past few days have been very exciting for Windows Phone developers:

    I am very excited about the roadmap, but I am also jazzed about our success to date, so I thought I would let developers in the marketplace tell you about their successes today.

    Two weeks ago, a few developers participating in LG’s hAPPiness program were here in Redmond and I was invited to join them for an hour of “tips and tricks.”
    [Sideline, the hAPPiness program is a great offer that allows LG phone owners to download and keep 10 great free apps from their marketplace. It is a wonderful promotion for apps, and as a value-add to LG phone owners, apps will rotate over time, so you will be able to pick from far more than the original twenty selected to-date].

    I was able to meet most of the developers, and was impressed with their excitement, passion, and eagerness to write new apps or improve their current ones. It was so cool that I asked if I could record them to show to our internal platform teams, who always get a rise out of seeing cool apps and hearing from developers.

    Here are my personal conclusions from meeting the group1:

    • Developers are making good money! None of them are retiring tomorrow or ordering a Ferrari (yet), but the money is adding up nicely. Even free applications with ads are making money. You don’t have to take only my word for this; check out this article from Inside Mobile Apps for download comparisons between Android and Windows Phone.2
    • Developers are having a lot of fun! The platform is easy to use and it is very RAD, the tools are free, we have great phones that users love, and a growing user base--not a bad playground for developers.
    • The Silverlight and Windows Phone community rocks. I don’t get to say this often, so I will use this chance to shout out to the Insiders, MVPs, early adopting partners, and all the other community folks who are on the forums, sharing their stories and their feedback (both good and bad)3.

    Those were my conclusions; but you don’t take my word for it. Take time to watch the interviews  below.  
    [Disclaimer: We were focused on the developer’s stories. Though they all demo their apps, the crappy recording (me), the room (improvised), and our goal of keeping the chat to just a few minutes, did not do the apps justice.
    Check out the apps in the marketplace links below, and don’t forget, if you are an LG user, these are free for a limited time.

    • Balint Orosz is one of the folks from Cocktail Flow. You can watch his interview here.
      In just a month he created a very successful app leveraging the skills he had (.NET, Silverlight); he might take it to other platforms now that the concept is vetted and much better funded.
      My summary from his story:“It is OK to get started on Windows Phone, leverage your skills if you are .NET or Silverlight developer”.
    • Emad Ibrahim is the creator of  Envision, Notesly+, QuoteZen, Picasa Viewer (and possibly others since he codes faster than I blog). You can watch his interview here.
      Emad is super fast at creating apps, and is getting great ROI from his apps.  My take away on his story: “Get started now, while the competition is low.”
    • Andy Beaulieu (creator of Talking Rag Doll) and Jeff Weber creator of Krashlander.  You can watch their video here.
      Jeff is one of the original creators of the open source farseer physics engine on codeplex . Andy was the first person to wrap it in Blend, contributing some cool Blend behaviors for it. 
      I thought it was great to see community contributors meet and finally get financial benefits from their community efforts.  They seem happy that other developers are cashing and using their library/behaviors. My take away for their video, have fun!!
      [Sideline,
      according to Inside Mobile Apps, KrashLander has had 15,900 $.99 downloads in January]

    Thanks to all of the devs for playing along on such short notice and letting me share their recordings. Check out their apps--and good luck creating your own!

    Foot-notes:

    1 I have to emphasize these are my personal conclusions. Don’t over-generalize it to my employer or folks in the Windows Phone team.
    2 I don’t want to spin the numbers and compare to Android (you can ignore that part or not, your call). I only refer to the article because they have independent numbers on how well apps some are selling.
    3 Again, the platform and phone have been rock-solid. The area where we have been less than stellar is the marketplace. I can assure you that the right people are listening; there have been a huge number of improvements, and there are more on the way. There are 8,000+ apps in the marketplace, so clearly it ain’t all broken; be persistent and keep pushing us. I will come back to the marketplace topic in a future post (hold me to this).

     

  • Jaime Rodriguez

    FAQ about copy paste functionality in upcoming release

    • 0 Comments


    I received a few questions about this post, and the nodo bits that were released last week, some of the answers are worth sharing broadly.

    About the UI guideline comment
    [this is the one worth the clarification]

    What is the UI guideline about not using TextBox in pivot/pano?  Where is it documented?
    This is mostly a recommendation (similar to keeping panorama UIs simple and clean).

    It is not a formal guideline since it varies by app layout/scenario.  As you know, panoramas and pivots do  listen for touch gestures, and the guidelines have always said you should avoid controls that fight for touch (such as sliders, map, etc.);  a textbox is a bit more dependent on the scenario: copy/paste is not the primary function of a textbox; it should come down to what the textbox does; if the app is filling a form and you have lots of textboxes, then I too would avoid putting them inside a panorama or pivot.  On the other hand, if you have a scenario that mostly presents data and really shines in a panorama or a pivot but you need a textbox that fits well into the scenario (such as a search box), it should be OK to use.  The new controls mitigate touch conflict a little, and as long as you position your textbox and the usage is appropriate, my early preview testing says it is OK.  

    Will my app fail if I have a textbox in a pano?
    Again, no. This is not a requirement.

    What you should know and maybe act/upon:

    My app does not have a pivot/panorama.  Do I need to recompile and resubmit?
    For the most part, you should not have to resubmit (if you don’t have textbox inside pivot/pano).  The exception are people that were manipulating TextBox’s focus and selection.  If you manipulate these, it is safe to test to make sure it all works.

    if I don’t recompile, will I get copy/paste in my app?
    Yes. Without recompile and resubmit, your app will get copy/paste in updated phones, and the performance improvements will also be there.
     
    Will I get the performance improvements?
    Yes, these are also coming for free.

    Details on the API
    Can I get programmatic access to the clipboard?
    Not in this release.

    Can I disable copy/paste?
    No. That would be awkward to the user.

    What controls get copy/paste?
    TextBox, PasswordBox.  WebBrowser control includes support c/p too (if you have textboxes in the HTML).
    TextBlock does not get it, but you can re-template a TextBox to look like a TextBlock  (do make sure to set it read-only).

    Will new features be added to the API in future releases (e.g. programmatic access or clipboard access)?
    Of course.  This current update is mostly an OS release, that is why the Copy/Paste is not very platform focused; but expect improvements in future platform releases.

     

    Of course I have also heard the question:
    When does the release go live?  Unfortunately, I don’t know the exact date (and I am bad at guessing). You can leverage the developer tools today and recompile your app with the new pivot/pano and submit to the marketplace any time. You do not have to wait for the release.  Don’t wait until date is announced and end up fighting the certification queues.

  • Jaime Rodriguez

    Communication between HTML in WebBrowser and Silverlight app

    • 0 Comments


    Two people asked on this post about communication between HTML and Silverlight, so I thought I would share broadly about the more 'advanced' techniques. 
    [Don't be misled, advanced is still easy, just explaining all you can do].

    Silverlight on Windows Phone allows you to host HTML content in a WebBrowser control. You get bi-directional communication between the control and the HTML content:

    • For HTML to host comunication, the WebBrowser control injects script into the page, and your javascript can call window.external.notify (<param>) to communicate with Silverlight.
      There is nothing you need to do (like include a js file). You just call the function in HTML and  calling it will trigger the WebBrowser.ScriptNotify event on the Silverlight side.

     

    • For host to HTML, webbrowser control calls the WebBrowser.InvokeScript method, passing a string with the function name, and an array of string params ).

    If you own the HTML page you are hosting, the infrastructure above is all you need to get anything done (since you can just add the javascript to communicate). 
    If you don’t own the page you are calling things are slightly more interesting but still very doable – these are the scenarios that fuel this post –.
    These are the communication mechanisms I use when talking to HTML on a page that comes from a server that I can’t control or influence.

    1. Use the execScript javascript function to call arbitrary javascript. execScript does not return a value, but you can call methods that don’t need to return one, for example:
      webBrowser.InvokeScript("execScript", "history.go(-1)"); 
    2. Use the eval javascript function to call arbitray javascript, and return a value from that javascript.  The return must be a string, but you can easily solve it by doing a toString() on any type (or using JSON if you need to return some thing complex).  For example:
      // this will fail, it returns null 
      // object height = webBrowser.InvokeScript ( "eval", "document.body.offsetHeight" );  
      // this works
      string height = (string) webBrowser.InvokeScript ( "eval", "document.body.offsetHeight.toString()" );
    3. You can even take these techniques to the next level and inject scripts into the DOM, listen for events, and call back to your host. All of this without owning the page you are hosting.
      For example: this snippet below is C# on the host WebBrowser control that inserts a function into the DOM, and then wires a listener for the click on a button in the page,  the event handler that we are wiring up  calls window.external.notify  () to let our host know the event was clicked.  Without owning the page, we can listen to events in the HTML. What more can we ask for?
      Here is the code:

      StringBuilder bldr = new StringBuilder();
      bldr.Append("var script = document.createElement('script');");
      bldr.Append("script.text = 'function cb () { "); 
      bldr.Append("window.external.notify (\"this text was injected on the fly\");}';");
      bldr.Append("var headNode = document.getElementsByTagName('HEAD'); "); 
      bldr.Append( "if (headNode[0] != null);headNode[0].appendChild(script); ;");
      bldr.Append("var element= document.getElementById('btn'); "); 
      bldr.Append("if ( element != null ) element.onclick = cb;");
      webBrowser.InvokeScript("execScript", bldr.ToString());


    I am sure there are more techniques, but the combination of the 3 above has gotten me pretty far in communicating between JS and Silverlight.

    If you want to see the code above in action, download this sample.

    Happy Windows Phone coding!

    If you want to keep up with Windows Phone on a more frequent basis, subscribe to my Windows Phone question of the day RSS feed.

  • Jaime Rodriguez

    Back button press when using webbrowser control in WP7

    • 3 Comments

    If you have a Windows Phone application that hosts the WebBrowser control and allows or encourages the users to navigate within the WebBrowser control’s space,  you are going to run into the 5.2.4.b certification requirement:

                    “Pressing the Back button must return the application to the previous page”

    This requirement is easy to understand for PhoneApplicationPages; but for HTML, I am still undecided on how intuitive it would be to a user that is navigating inside a WebBrowser control. 
    Most of the apps I have been involved with that use the WebBrowser control, do not encourage navigation ( they show small HTML inline) or show HTML it in a popup that only has a close button on the top right, so I have never worried about integration between WebBrowser and back button.  It was always a “Back” closes the transient popup.
    That said, I saw a news reader  app last week that had a full screen WebBrowser, and a back and forward button in the appbar, this felt weird ( to see a back button in the appbar) I thought the hardware back button should integrate with this “perceived” navigation stack .  This got me thinking about 1) how hard it is to code and 2) how error prone it would be.

    Yesterday, I quickly threw in an HTML page that I felt would cover most linking scenarios. It has regular navigations (A HREF) , shortened URLs (that lead to redirects), navigates using script, and has fragment navigations.   I then created a project with WebBrowser to integrate with back button.

    Here is my one-hour exploration:

    1) Listen to WebBrowser.Navigated event;  keep track of the pages that have been visited.

    Stack<Uri> history= new Stack<Uri>();
    Uri current = null; 
    private void WebBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
    {
        Uri previous = null;           
        if (history.Count > 0)
            previous = history.Peek();
    
        // This assumption is NOT always right. 
        // if the page had a forward reference that creates a loop (e.g. A->B->A ), 
    //
    we would not detect it, we assume it is an A -> B -> back () if (e.Uri == previous) { history.Pop(); } else { if (current != null) history.Push(current); }
    current = e.Uri; } 2) Listen to OnBackKeyPress on the page. If the WebBrowser has a navigation stack, cancel the backkeypress and navigate within the webbrowser control’s stack.
    protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
    {
        base.OnBackKeyPress(e);
    
        if (!isPerformingCloseOperation) 
        {
            if (history.Count > 0)
            {                        
                    Uri destination = history.Peek();
                    webBrowser.Navigate(destination);
                    // What about using script and going history.back? 
                    // you can do it, but 
    //
    I rather use that to keep ‘track’ consistently with our stack e.Cancel = true; } } }

    As you can see, code is trivial, but it has an issue I did not solve.  I can’t tell the difference between:

    1. Navigate(a) –> Navigate ( b) –> back ();
    2. Navigate(a) –> Navigate ( b) –> Navigate ( a ) ;

    I tried letting the browser do the work, and peeking at history.length (you can see the code in the sample, commented out), but that does not help since the sequence #1 above leads to a length of 2, instead of a length of 0.    Since that does not solve it (and I don’t see a different way, is this good enough?   I think it is, because:

    • I believe scenario #2 above does not happen a lot. So, I optimized for #1, it does the trick because worst case it gets user out quicker.
    • If you are concern on #2, you can add an ‘escape valve’.  I put a close button on the top right hand of the page, so the user can close the browser page if they want to; you could also use appbar if your page has one.

    Unless I missed another major gotcha, I think this does nicely.   It is intuitive to the user in most typical navigations. It lets them out of the browser page (history.length was getting stuck since it never decreased to 0).    I also asked internally to the Microsoft folks building apps, and the ones that integrate back button and webbrowser navigation are using the same pattern, and have not had any complaints from users. 

    To conclude, here is my personal advise/summary:

    • Not all apps need this integration. If you are just showing a single page, and don’t want to encourage navigation, use a UX pattern that hints the user that the UI is transient – make it look like a popup, put a close button on the popup’
    • If you have an app that does encourage navigation in the browser,  consider the pattern above. Don’t do it because of the certification requirement, do it because it is intuitive to the user. That is why the requirement exists. 
    • If you feel that your app does not fall under one of the above, then do ask for an exception to the certification team. That said, I emphasize you should thrive to create an intuitive experience for your user. I think the two options do that best so I recommend them –as opposed to the excuse/exception route-.

    Sample code is here.

    Happy Windows Phone coding!

    If you want to keep up with Windows Phone on a more frequent basis, subscribe to my Windows Phone question of the day RSS feed.

  • Jaime Rodriguez

    Details on the Push Notification app limits

    • 4 Comments

    Yesterday, Kevin Marshall wrote a blog post  with a good developer tip: to code defensively for the 15 application limit in push notification. 

    I know the post was well intended (as a developer tip) and fair criticism (to platform limit); but a few people got confused or misinterpreted and we ended up with tweets or posts that said “Windows phone allows only 15 live tiles”, or “you must uninstall apps to free tiles”, etc..

    Here are a few details you might care to know, so you can plan your app and be a good citizen:

    • Yes, the limit is fifteen third party applications can be concurrently subscribed  to receive push notifications (whether that is a live tile or toast).  Parsing it out, the applications that come out of the box (like outlook, people hub, etc.) will not count towards this limit.    So there is no limit on 15 live tiles.  You can have 20+ if you add it up (that is about 2.5 screens worth of tiles on star menu)
    • An application is only counted if it has push notification or tiles push enabled and is subscribed to a channel.  If you install an application but you do not enable push, it would not count towards the limit.
    • You should not have to go uninstall an application in order to free a slot.  If an application is coded well, it should be prompting users and giving them the option on whether they want to use push notifications and/or live tiles (since there is potential bandwidth charges from the operator when these are pushed).   if the user never agrees or it unchecks the box to subscribe, the application should free the channel; there fore uninstall should not be required.
    • Applications that use just scheduled tiles updates do not count towards the limit. If that is all you need be a good citizen and
    • If an application subscribes for tile updates, and is never pinned it unfortunately does count. Again, we count the channels.

    To handle the error, as Kevin pointed out it is just a matter of listening for the exception, and right error message.  Then prompt user to turn-off push notifications in another app.   There is no API to list the applications using it – and I have not heard of a plan for this API –.

    Is the limit too low, Kevin wonders.  Obviously there is no perfect answer as it varies by user. I do know that the product team did research on types of apps, categories, how many a typical user would pin, enable push, etc. and they went with 15 for v1, so it is not an arbitrarily low number.   I saw the data and it made good sense to me.  I also hear that the limit can increase later, as we get more apps and better data.  Full clarification, “can increase” only means we are constantly evaluation. it does not mean the next update will have this limit increased. Nothing to announce.  

    Again, the key there is the planning was done for typical users. As developers, we tend to install more apps, and often enable the features just to try them out, but we are also power users that know when and how to turn these off.   On the rest, we will have to trust (and hope) that the data the researchers and planners had for typical users holds us until the limit is increased.

    Why is there a limit?  The usual thrive to ensure there is a great user experience, good battery life, quality of service on back-end and front-end, bandwidth (cost) , etc.  Limit will increase as we get right data on how people use push, impact, etc.  Kevin’s feedback on there not being an API to enumerate all push apps is still valid.  I know the product team has heard it (from Kevin, me and others) so I hope that gets addressed or the limits go high enough that the problem becomes a moot point.

    Hope that helps. 

    My take,  when it comes to push,

    1. Don’t panic, code your app to take advantage of the platform. Tiles and push can be a nice differentiator for an app.  Let the user decide (15 is still a good number for average users).
    2. Code defensively against this limit. it is not hard (though mitigation prompt to the user is not perfect, but it does leave them in control )
    3. Prompt your users and ask if they want to use push, and if you are using live tiles give them the option to turn tiles off too..  If user opts out of both, free the channel.

    Happy Windows Phone coding!

  • Jaime Rodriguez

    UpdateSourceTrigger on Windows Phone data bindings

    • 5 Comments


    I am writing this tiny demo app, that has a TextBox data bound to a ViewModel. 
    I want the TextBox to fire notifications to the ViewModel whenever the text changes (as opposed to only firing notifications when the textbox loses focus).
    In WPF, this is trivial to do, you just set the UpdateSourceTrigger on the Binding to PropertyChanged  (in fact, I think that is the default).
    On the phone, I only see UpdateSourceTrigger supporting:

    • Default (which for TextBox appears to be LostFocus ) and
    • Explicit.  Which is just telling me to man-up and do it on my own logic.
      No option for PropertyChanged.

    What to do? 
    [12/5  (Update part 1) -- Updating this post due to enough feedback that the semantic of TextChanged is better than my post’s KeyUp.
    I did try that before suggesting KeyUp on my original post but I was seeing TextChanged fire more often than KeyUp (aka more times than I felt necessary).
    Now that I have seen there is no big perf hit (since others are doing it with TextChanged) I am back to proper semantics.
    Also you made me second guess and I tested on a keyboard and noticed that arrows can even the score firing KeyUp events. 

    How about:

    1. Setting the UpdateSourceTrigger to Explicit 
    2. Listening to TextBox TextChanged event, then firing the explicit update?

    Here are the snippets:
    In my XAML,

       1: <TextBox x:Name="empIdTextBox" Text="{Binding Id, Mode=TwoWay, UpdateSourceTrigger=Explicit}"                    
       2:             TextChanged="empIdTextBox_TextChanged"/>
    code-behind,

       1: private void empIdTextBox_TextChanged(object sender, TextChangedEventArgs e)
       2:     {     
       3:       TextBox box = (TextBox)sender;
       4:       BindingExpression be = box.GetBindingExpression(TextBox.TextProperty);
       5:       be.UpdateSource();
       6:  
       7:     }

     

     
    [12/5 Update part 2]
    Corrado Cavalli and Curt Nicholas emphasize that I should use Behaviors.  
    My sample was part of the intro to data binding chapter in Learning Windows Phone, so I did not want to go to behaviors (yet). Still, for production apps, here is the behavior.
    Curt also mentions I can cache the BindingExpression.  I tested it and seems to work, but I was not sure when (or if) binding expression gets invalidated so I leave it for you to complete the research for your scenario.
       1: public class UpdateSourceOnTextChangedBehavior : Behavior<TextBox>
       2:   {
       3:  
       4:     protected override void OnAttached()
       5:     {
       6:       base.OnAttached();
       7:       this.AssociatedObject.TextChanged += this.OnTextChanged;
       8:     }
       9:  
      10:     private void OnTextChanged(object sender, TextChangedEventArgs e)
      11:     {
      12:       BindingExpression be =
      13:         this.AssociatedObject.GetBindingExpression(TextBox.TextProperty);
      14:       be.UpdateSource(); 
      15:     }
      16:  
      17:     protected override void OnDetaching()
      18:     {
      19:       base.OnDetaching();
      20:       this.AssociatedObject.TextChanged -= this.OnTextChanged;
      21:     }
      22:   }
       1: <TextBox x:Name="empIdTextBox" Grid.Column="1"                 
       2:                 Text="{Binding Id, Mode=TwoWay,UpdateSourceTrigger=Explicit}" > 
       3:          <interactivity:Interaction.Behaviors>
       4:            <local:UpdateSourceOnTextChangedBehavior />                             
       5:          </interactivity:Interaction.Behaviors>          
       6:        </TextBox>         
    Happy Windows Phone coding!
  • Jaime Rodriguez

    Windows Phone Application Performance at Silverlight Firestarter

    • 0 Comments

    Yesterday I did a dry-run of my performance talk for today’s Silverlight fire starter.

    Conclusion was that the talk is like drinking from a fire-hose. It is tight for 45 minutes, but the content is good and we could not agree on what to cut. It was all too good and useful to cut stuff.  

    So,  I am going to cheat Smile  and give you an early preview and a guide to make it easy to follow along.

    • Here is the deck (might get a few edits between now and 4:30 PM)
    • Here is a cheat-sheet. It is in draft mode. It is incomplete, but if you are a beginner, it should help get you through my 86 mph talk. I  will be updating it and completing it as we go in next few days.  Expect an update over the weekend ( booked tomorrow and hopefully partying with firestarter folks tonight).  Full disclaimer, this is a stream of consciousness draft, very rough, not even spell checked (just realized the latter, but have already published in sky drive).
    • Here is the sample code.

     

    Join me today at 4:30 PST. Live at Silverlight fire starter
    if you can’t make it, check later for final document, including a part 2 and the video recording.

    Happy Windows Phone coding!

  • Jaime Rodriguez

    ISO image for the Windows Phone developer tools..

    • 0 Comments


    For those of us who have multiple machines or re-install often and don’t like to download every time using the web installer,  there is an ISO image for the Windows Phone Developer tools

    Download using this link.. http://go.microsoft.com/fwlink/?LinkId=201927.

    This is the RTM version ( so what we released around 9/15).   Don’t forget to install the October update for the tools after you have installed the tools from this iso.

    Also, if you are a VB developer, you will have to get the VB tools support  that RTMed yesterday  

    Happy Windows Phone coding!

  • Jaime Rodriguez

    Working with GIF images in Windows Phone

    • 0 Comments

    As you know, Silverlight does not have native support for decoding gif images. That is downer, but not a showstopper since several 3rd party, opensource libraries for decoding Gifs. GifCompare

    The Twitter for Windows Phone team used the ImageTools project from Codeplex to decode gifs.   It worked well, but when we implemented there were two things that bothered me a little:

    1. The decoder was not perfect.  In our experience, it does ~90% of the images we tested  [and that was thousands of images, so representative test]
    2. There was one infinite loop that bothered me.  Has to do with nextflag during decoding. The Decoder checks for flags to be != 0, and for some odd reason we have seen gifs with nextFlag = –1; this can send your app into an infinite loop.

    I knew there were other libraries and partners were using these (for example,  the GifDecoder library shared a long while ago by Joe Stegman).
     
    Today, I finally compared these two libs side-by-side.  I used ~400 images.  25% came from a list of Gifs that had known issues. The other 75% was a random selection by looking at a Twitter user, and downloading his followers and filtering for the ones that used gifs.

    The results:  
    Decoding wise, these two libraries are pretty much the same code.  I should have started by comparing that before I wrote my test.  Instead, I found it by accident as I dived in to fix the infinite loop above.
    The results are pretty inline with our original ~90% assessment.  My tests are a bit lower but again it is because I spiked the test.

    The codeplex library is getting updated a lot more, and is growing and getting fixes, so that is what I am sticking with for my projects.
    They have done a lot of work on their AnimatedImage control (which supports animated gifs, looks pretty neat (though I have to say animated gifs feels like going back in time).

    If you need to decode Gifs, I do recommend you use this library. It is better than nothing.   Please do make sure you:

    1. Download the latest from codeplex. It is getting updated often.
    2. Test it for infinite loops.  You can download the source for my comparison app. I am attaching it to this post.  Or you can just check the source for the library.  The current issue is at ImageTools.IO.Gif.GifDecoder.Decode ()  their loop checks for  while nextFlag != 0 ….   and I simply tweaked it to  while nextFlag > 0 …    I have no idea what my changed does to GIF decoding since I know nothing about the format, but I know that I can get  ~90% of my Gifs to decode and I don’t have the infinite loop, so it works for me..

    I am sure the library will improve over time,  I pinged the folks with my tests and my results in case it helps improve. 
    Source for my little test, and source for the libraries I used (with small changes) are in skydrive

    Happy Windows Phone coding!

  • Jaime Rodriguez

    Windows phones hardware reviews

    • 1 Comments


    Kevan Hutson (or some one in his team) created this great ‘aggregation’ of reviews of different Windows Phone models.
    It is a bit US-centric, because it aimed at helping the MS-based US Employees order their phones now that Windows Phone is launched in the US.
    Still think it might be useful to many of the people reading this blog.. and if not, it can influence others to share better links, or even their own reviews..
    So, with Kevan’s permission, sharing his internal list.  

    Take it with three grains of salt; I did not read all the reviews, this is very unofficial, and I am sure not comprehensive.. Still, it did help me, so I thought was worth sharing..

    Samsung Focus | AT&T

     Brilliant 4” Super AMOLED Screen  
    Thinnest, lightest Windows Phone
    Audience Noise Reduction

    Consumer Reports: Samsung Focus is sharp, with a few dull spots
    The Samsung Focus looks like a winning smart phone, thanks to its gorgeous display and the efficient and attractive operating system behind it.

    Gizmodo: The first Windows phone that matters
    [Samsung Focus is] the thinnest and lightest Windows Phone, and its Super AMOLED display is the best screen too. If you're going to get a Windows Phone, this is the one to stare at the hardest.

    PCMag.com
    The Samsung Focus plays up Windows Phone 7's strengths and plays down its weaknesses for a great Windows Phone experience.

    Engadget
    The Focus is kind of the everyman of the Windows Phone 7 line. It doesn't really have any fancy features and isn't especially stylish... but it gets the job done.

    MobileBurn: Windows Phone 7 and great hardware
    The build quality on the Focus is amazing. It is a very solid and rich-feeling device. That it is good looking and features the best looking display on the market, in my opinion, certainly doesn't hurt.

     

     

    LG Quantum | AT&T

    Full QWERTY Keyboard
    16 GB Internal Memory
    Play To (DLNA) Support

    Engadget: LG Quantum first hands-on!
    We're very torn on the LG Quantum. From the outside you've got a design that can only be named as "frumpy," with wasteful curves and rubberized edges, along with the smallest screen of the AT&T bunch. Still, slide this puppy open and you're treated with one of the best QWERTY keyboards in the business.

    ZDNet
    The Quantum takes a stand as it is the only Windows Phone 7-based device with a slide-out full QWERTY keyboard.

    PCMag
    The LG Quantum could be a quantum of trouble. The first Windows Phone 7 device with a full keyboard that will be sold through U.S. carrier stores, it has a balky sliding mechanism and a really bizarre keyboard layout that could kill its appeal.

     

    HTC Surround | AT&T

    Slide-out speakers w/ kickstand
    SRS Dolby Mobile Surround Sound
    16 GB internal memory

    MobileTechReview.com
    It's business as usual for HTC: attractive and understated finishes that avoid looking plasticky, a solid feel in the hand and considerable heft thanks to the slider design.

    PCMag.com
    The HTC Surround promises a big entertainment experience with its kickstand and huge slide-out speaker, but Windows Phone 7 just isn't up to the task.

    Engadget
    The Surround needed to bring a lot to the table in order to justify being bigger and heavier than the Samsung Focus while lacking the QWERTY keyboard of the LG Quantum, and we just don't think a pair of average speakers and a kickstand provides that justification

    Gear Live
    The HTC Surround is a good phone, and its the one we'd recommend if watching movies and listening to music is your jam.

     

    HTC HD7 | T-Mobile

    Largest 4.3” Screen
    T-Mobile TV built-in

    CNET
    The hardware could use a bit of updating, but the HTC HD7 for T-Mobile combines the power of Windows Phone 7 with a large touch screen and delivers satisfying performance.

    PCMag.com
    The T-Mobile HD7 is a good-looking phone that's a fine canvas for Windows Phone's services, but it's not at the top of its class.

    Gizmodo
    Overall, the HD7 is not a bad phone, and it's a perfect serviceable vehicle for Windows Phone 7. It's just not a great phone.

    Boy Genius Report
    The Windows Phone 7 OS on HTC’s HD7 is absolutely fantastic in many respects, and yet in other areas, it is an OS filled with almosts.

    Engadget
    The reason we like the HD7 is that it seems to be just about the perfect size for us. It trades little in the way of added bulk for an awful lot in added real estate and general usability.

    SlashGear
    The HD7′s large display, responsive interface and our generally positive feelings about Windows Phone 7 all stand in its favor, but there are still niggling flaws and frustrations that mar the overall experience.

     

    Dell Venue Pro | T-Mobile

    Vertical QWERTY Keyboard
    Scratch & Shatter Resistant Screen
    Available on T-Mobile, sold through Dell

    Engadget: Dell Venue Pro (aka Lightning) first hands-on!
    No matter what you call Dell's Windows Phone 7 portrait slider, it's downright awesome.

    CNET
    The smartphone feels very solid in the hand. In addition to the slide-out QWERTY keyboard, the Venue Pro also offers a 4.1-inch WVGA AMOLED touch screen, which was both sharp and responsive in our brief hands-on time with the device.

    Gizmodo
    The Venue Pro has a bit more heft than some of the other WP7 devices launching today, but it's not overly bulky. It just feels solid, durable.

    PCMag.com:  Windows Phone 7's dark horse? Hands on
    I want to love the Dell Venue Pro. This is the Windows Phone 7 with a keyboard that might actually work. But it's from Dell, and even T-Mobile doesn't seem to have complete faith in the phone.


    Additional reviews worth reading:
    CNET - First impressions: HTC HD7, Dell Venue Pro
    Engadget - Windows Phone 7 in review: the good, the bad, and the Surround
    InformationWeek - Review: AT&T's Windows Phone 7 handsets tested
    Maximum PC - Windows Phone 7 impressions: The first 24 hours
    PhysOrg - Review: Microsoft hits refresh on smartphones
    ZDNet - Hands-on with the HTC Surround and Samsung Focus WP7 smartphones


    Additional Model Reviews - EU and APAC
    LG Optimus 7 E900 review (Stuff Magazine)
    Samsung Omni Review (Telegraph)
    Trophy (TechRadar)
    Mozart (Pocketlint)

  • Jaime Rodriguez

    The Windows Phone platform and Windows Phone devs are both doing great

    • 4 Comments


    Yesterday, I saw a few posts, tweets and personal emails from smart, professional developers  who are building great windows phone apps and did not appreciate getting caught in the recent slew of press and marketing exchange around Windows Phone perf.   I am going to share my personal experiences to try to clarify the likely misinterpretation..

    The problem/story:
    Press goes to marketing (not engineering folks) and tells them “when are you going to fix the perf problems in the platform, we are seeing a few apps lag?” … 
    Windows Phone marketing answers it the way they see it “there is no problem with the platform, we are working on education for developers to improve their apps”..
    Some developers then get upset and respond with a “what are you talking about? We know our stuff, our apps are good, some are even great, we just need you to improve <insert a feature or a hardware component here> so it is faster..” ..

    At first glance, the stories are in partial conflict.. and the developers get caught in the middle (since they are not in the conversation that is getting reported), so I have to share my personal experience as a developer collaborating with partners and developers  to build build good and great Windows phone apps(disclaimer, I still work for Microsoft so I am biased, and all that, but I also like to tell it like it is so read on and decide).

    Answer or state of the union:
    Every platform always needs performance improvement. Users will always demand more.  Engineers will always aim to provide more. I know our Windows Phone engineering team has improvements and fixes coming into the platform to make things better/faster…

    At the same time, the journalist question around “fixing the performance in the platform” is a loaded question and implies “it is broken”. 
    Every platform has small bugs and short-falls so the question is whether this is a systemic problem or a big hole that really qualifies ours as “broken”.  I can’t speak for every developer but my experience has been that there is a very reasonable (low) number of bugs as expected, and the platform works and performs well with-in user expectations, so I can understand why MS marketing folks are  responding with the “it is not broken, we just need to advise developers to get the most out of their apps”.

    So, why do they say that?  I won't speak for all developers, but I can share that  100% of the apps I have been involved with, can use performance improvements that developers can make today but simply need more time to implement or did not understand a month ago; these are new apps, new usage patterns, etc.. There is also changes that will (eventually) come for free to the platform as improvements (you can call them bug fixes if you want but I would call them optimizations) that will make existing apps better (with out neding changes).

    On my partner’s projects, we had to balance between features, optimizations, and polish within the constraints we had to get us to launch – biggest constraint being time,  beta of the platform was shipped ~3 months from RTM, most apps were built in this time-frame.   As developers and engineers, we discover new characteristics or niche scenarios in the platform every day. We are are thriving with all these great new lessons or lessons that others are sharing, and we are improving the apps, lots of these apps are already released their first or second update, and I am sure every one of these is better than their previous release.   

    That is why Microsoft is emphasizing education and broad sharing. It is not blame, it is just a natural partnership for any brand new platform ..

    To the developers:

    When you hear MS marketing folks say “we are working to train and educate developers to improver performance on their apps” please don’t misinterpret as an insult or blame . What Microsoft folks are trying to say is “we have a great platform, but the hardware has been available only for a short time, the new amazing experiences we are seeing every day have never been built before on any platform.  We know we have a strong foundation, but we learn new stuff every day,  and we want to share it as guidance and education so you (developers) can leverage the tips can make your apps even better. 

    In my opinion, there is a lot to be proud of..   There is some amazing apps, and some great reviews.  The fact that reviewers like Gizmodo are comparing the Windows Phone apps to apps that have been in other platforms for 18 months to 3 years, and we are comparing neutrally or favorably is pretty amazing.   It has been ~8 months since developers even heard of our platform.  It has been only four months since beta and only a few weeks of marketplace being open.  What do we have to show for?  Thousands of apps in the marketplace, tens of thousands of developers registered,  over half a million downloads of the tools..   All-up, this is a great story…  The read I get from peers at Microsoft is that we are very proud of the platform and the tools,  and we are very impressed (often amazed) with some of the the apps that are getting in the marketplace.  We are heavily invested in providing the best tools and the best guidance.  When we say  we are working on education, all that means is we are ready to partner with you  (our developers).  Your success is the pillar to our own platform’s success. Long-term, we will optimize the platform even further , and half of the issues that are annoying us today will be gone,  but interim, we will have to work together to create great apps.   We know the platform can do it since plenty of you devs already proved it.. 

    Let’s keep rocking and don’t over analyze sensationalist titles to news stories..
    That is my personal 2c.  Back to my writing some good tips on my upcoming Windows Phone book Winking smile ..

  • Jaime Rodriguez

    GeoCoordinateWatcher tips part1

    • 0 Comments

    A few tips for those using GeoCoordinateWatcher in Windows Phone 7.

    The data:

    • GeoCoordinateWatcher events fire in the UI thread.  Yes, StatusChanged and PositionChanged fire in the UI thread. 
      This is not due to thread affinity or any thing similar. Even if I start the GeoCoordinateWatcher in a background thread, it still fires events in the UI thread. They wanted to make it easy for developers.
       
    • GeoCoordinateWatcher PositionChanged will fire as often every second if you do not give it a MovementThreshold. Yes, you can not move at all and it is firing (on your UI thread).  Note, that is what I see on my phone, I do know the phone is optimized for battery life, so maybe it throttles with battery .. but when fully charged I see a ~1 Hz rate.
    • Getting a GPS fix out of GeoCoordinateWatcher can some times take a second or two. GPS is never a trivial operation (if you have ever turned it on in your car, I am sure you would know).  This can be a pain if you have an app that needs a fix in milliseconds, for example, if you are in search, and you want to do a local search, you want it to have location immediately, you don’t want to wait a second …

    The Tips:

    • Avoid doing a lot of work on the GeoCoordinate events.  They are in the UI thread. Avoid as much work as you can (send to background thread if needed).
    • Absolutely set a MovementThreshold on the GeoCoordinateWatcher   20 meters is probably lowest you should you.  I most often use 250m. Most of the services I use ( twitter, facebook, search, etc.  are doing searches in a > mile radius, 250m is great threshold for these services)…
      • if you do set MovementThreshold you should know that GeoCoordinateWatcher fires event in a weird order and the order can get you when you use MovementThreshold.
      • GeoCoordinateWatcher has a StatusChanged,  which you would expect fires when the GCW is ready…   my experience is that when subscribing to GCW I see this sequence
        • StatusChanged to Initializin
        • PositionChanged   -- with a valid location
        • StatusChanged to ready
        • If you have a high threshold, PositionChanged might not fire again…  so if you were a cautious developer and checked that Status is ready before accepting the location, you might not get a PositionChanged.   
      • The answer (from the devs) is that it is fair to assume that if PositionChanged fires, the status is ready.  It is OK to not check status in this event.
    • If  you read above, when there is no threshold it fires every second…  I am told the threshold does affect sampling rate (we are preserving battery as much as we can) but I am also thinking they are doing work sampling more often than most of my apps need.. I am not writing some thing that requires a position every few seconds..  so what I do for most of my apps is Start () and Stop () the GCW every 2 minutes (or longer pending on the app)…   Start and Stop is not an expensive operation…    Just have your GCW be wrapped by a singleton, and start it and stop it often..  Avoid calling Dispose () on GCW..   I have very seldomly (when stress testing) seen a race condition on Dispose () that could crash my app…   again, happens seldomly but I still don’t like the chances, since it is a singleton, and you can start and stop.. I don’t see a need to Dispose ()..

    That should be all you need to really optimize your location-aware apps… Don’t forget to prompt the user before you use their location ..  
    Feel free to beat me to the next part… you should know what that is..

    Happy Windows Phone coding !!

  • Jaime Rodriguez

    Slides and demos from TechEd sessions..

    • 0 Comments

     

    I have uploaded my slides and demos from my teched sessions.  alt
    Thanks for attending and staying awake Smile 

     

    Happy Windows Phone coding!

  • Jaime Rodriguez

    XAPAthons at Teched Europe 2010

    • 0 Comments


    On my way to TechEd Europe today, and just found out there is a room available to host a Windows Phone XAPathon..
    There was also room for T-shirts for first 12 XAPathon RSVPs.   If you are at the event. Below is the likely places you will find me..
    Tshirt

    XAPAthons

    What is a XAPathon?
    A casual short ( less than an hour unless schedule allows for more) meeting with a so-named Windows Phone expert (in this case me and/or Oren Nachman, a perf expert).
    You can do anything you want with the time:

    • We will have phones, some tools, and eagerness to help you with your app.
    • You can join us for an hour and ask questions, chat, or just borrow a phone and see how your app performs on it.
    • If you are an expert and have already coded an app, you can still join and shoot a brief 15 minute video about your app and your experiences hacking on WIndows phone.  I can then put it as part of my “Windows

    How do I sign-up for a XAPathon ?
    Email me via the link on this blog post.. or contact me via twitter @jaimerodriguez  or Just stop by at the Passau 4 room  (yes, you have to be a registered attendee, sorry).


    Break out sessions

    Monday:
    09:00 Windows Phone Pre-Conference
      ( a ~5 hour dive into building WIndows Phone apps..
    Taught by yours truly.  
    Still working on the timings for the session but slides and decks are done. It will flow like this:

    1. Intro to phone (goals, design, hardware audience)   - Intro
    2. Phone UX – pragmatic
    1. Metro – intro
    2. Interactions – pragmatic
    3. Includes deepdive into phone controls – pragmatic
    • Integrating w/ hardware – pragmatic
    1. Accelerometer, location, mic,  etc.
    2. Keyboard,
    3. Touch
    4. Choosers and launchers
    • Navigation – deepdive
    • tomb stoning – deepdive
    • Push notification – deepdive
    • Lessons learned from a few apps – deepdive
    1. Data
    2. Perf
    3. Other ..

    [intro == 15 mins or less, and it is 200 level] ,
    [pragmatic == 200 to 300 level intro+good practices]
    [deep dive == all you will ever have to know about it]

    Tuesday:

    10:30 WPH101 - Changing our Game : Windows Phone 7 and the Windows Phone 7 Application Platform
    12:00 WPH202 - User Experience Best Practices for Building Applications on Windows Phone 7
    16:30 WPH305 - Understanding the Windows Phone 7 Development Tools

    Wednesday:

    9:00 WPH306 - Silverlight for Windows Phone 7
    12:00 WPH307 - Building Windows Phone Games with Microsoft XNA and Visual Studio 2010
    16:00 WPH309 - Developing Windows Phone 7 Web Applications with WebMatrix

    Thursday:

    09:00 WPH310 - Giving your Windows Phone XNA Games Plenty of Whizz and Bang
    12:00 -WPH311 - Microsoft Silverlight Performance on Windows Phone
    16:30 -WPH214 - Understanding Marketplace and Making Money with Windows Phone 7 Applications
    18:00 WPH315 - Developing for Windows Phone 7 - End to End

    Friday:

    09:00 WPH316 - Building Offline Experiences for Windows Phones and Other Devices using Sync Framework
    10:30 WPH117-IS - Come and Meet the Windows Phone 7 Team
    12:30 WPH318 - Developing Code for Windows Mobile and Windows Phone 7


    Silverlight Focus groups

    At TechEd Europe, the Microsoft Silverlight team will be conducting several focus groups (60-90 min) on-site November 11th, and the purpose is to solicit opinions about Rich Internet Applications (RIA) platforms. The team would love to learn more about your thought process when evaluating these technologies and about your experiences building applications with various solutions!

    All focus group participants will be given a gratuity (Microsoft software) for their contribution.

    To participate, please enter the URL below into your Web browser and fill out a brief form with your name, contact information, and your level familiarity with various RIA platforms, http://www.surveymonkey.com/s/GKG3RN6

    Note: We will only use this information to schedule some time to talk with you while you are at the show, and will not add you to a mailing list or share your information with third parties.

     
    Hope to c u there.. 
    Happy WIndows Phone coding..

  • Jaime Rodriguez

    Guessing if the SIP is visible in a Windows Phone application

    • 1 Comments

    For Silverlight applications, Windows Phone does a good job at abstracting the keyboard from the platform. 
    As a developer, you drop a TextBox any where in your app and whenever the textbox gets focus:

    • The platform will launch the SIP if the hardware keyboard is not available.  When the SIP comes up,  the platform also applies a TranslateTransform to the RootFrame of the application, so that the SIP takes its space, but the textbox is still visible. 
    • The platform does nothing if the hardware keyboard is available. SIP does not come up, does not get on the way, etc.

    Again, all of the above comes for free, and is pretty convenient most of the time.   Unfortunately, every now and then, you do run into a scene that maybe has a button underneath the textbox ( for example, a login window or a  sign-up window with a button near the bottom).   If you are in one of these situations,  the news are not so great. There are no platform events or classes to tell you if a SIP is available and/or when it is shown or hidden.    There is a “hack” that works most of the time:

    When SIP is visible, and the screen has been translated,  the transform is applied at the App.RootFrame (which is a PhoneApplicationFrame).   The easiest way to get notified when this Transform changes (to avoid polling) is to data bind to it; using a DependencyProperty, you get free notifications when the property changes (which of course would happen if the SIP is visible. 
    Here is a sample snippet, that sets an IsChecked property in a checkbox whenever we think the SIP is visible.

       1: public partial class MainPage : PhoneApplicationPage
       2:    {
       3:        // Constructor
       4:        public MainPage()
       5:        {
       6:            InitializeComponent();
       7:            BeginListenForSIPChanged(); 
       8:            
       9:        }
      10:  
      11:        private void BeginListenForSIPChanged()
      12:        {
      13:            PhoneApplicationFrame frame = (App.Current as App).RootFrame;
      14:            Binding b = new Binding("Y");
      15:            b.Source = (frame.RenderTransform as TransformGroup).Children[0] as TranslateTransform;
      16:            SetBinding(RootFrameTransformProperty, b);
      17:        }
      18:  
      19:  
      20:        public static readonly DependencyProperty RootFrameTransformProperty = DependencyProperty.Register(
      21:          "RootFrameTransform",
      22:          typeof(double),
      23:          typeof(MainPage),
      24:          new PropertyMetadata(OnRootFrameTransformChanged));
      25:  
      26:        static void OnRootFrameTransformChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
      27:        {
      28:            double newvalue = (double) e.NewValue;
      29:            MainPage page = source as MainPage;  
      30:            if ( newvalue < 0.0 )
      31:            {
      32:                page.IsSipVisibleGuess.IsChecked = true; 
      33:            }
      34:            else if ( newvalue == 0.0 )
      35:            {
      36:                page.IsSipVisibleGuess.IsChecked = false ; 
      37:            } 
      38:  
      39: #if DEBUG 
      40:            else 
      41:                System.Diagnostics.Debug.Assert ( false, "I assumed this would never happen, let me know if it does"); 
      42: #endif 
      43:             
      44:        }
      45:     
      46:    }


    Full disclaimer, this post begins with guessing. it is not 100% fail-safe.
    The scenario where it fails is when you set focus on a textbox and SIP comes up, and then you open the hardware keyboard on the phone. The platform does not always apply the transform immediately.  The snippet is still right, since the transform has not been removed, but it is annoying that hardware keyboard is readily working and transform is still there.

    The snippet also does not tell you if the SIP is visible when the TextBox is so high enough on the scene that the rootframe does not get translated at all.

    I would recommend you avoid using the trick when you can,  the easiest way to avoid it is not to put buttons that can be covered by the SIP (so no buttons underneath the textbox). . Put the buttons either above the textbox, or on the ApplicationBar. The latter being my preferred approach.

    If you want to try it, the source is here.

    Happy Windows Phone coding.

  • Jaime Rodriguez

    Tips for debugging WP7 media apps with WPConnect

    • 0 Comments

    Monday’s blog post on  running under screen lock generated a couple of questions around media not playing when medialibrary is locked ( and Zune locking Media Library).
    So, today, I remind you about a recently announced tool that shipped with the Windows Phone Developer Tools October Update.

    The tool is called Windows Phone Connect Tool ( internally we know it as either WPDTConnect, or WPConnect, the latter is the final name of the exe as it made it out externally).
    Full instructions on running and troubleshooting WPConnect are here.   My personalized version is below.

    Requirements:

    • Of course, this requires you have the WIndows Phone Developer Tools installed (dah!) . Get the tools from here
    • This also requires you have a version of Zune capable of connecting to Windows Phone. That is version 4.7.1404.  Get it from here
      You will not be running Zune during the debugging, but WPConnect is still using some of that infrastructure that Zune installs.
    • At last, you need to install the WPDT October Update.  Get it from here.


    To run WPConnect:
    You simply need to run the WPConnect.exe. 
    By default it will be installed at  %ProgramFiles%\Microsoft SDKs\Windows Phone\v7.0\Tools\ or at %ProgramFiles(x86)%\Microsoft SDKs\Windows Phone\v7.0\Tools\WPConnect.
    The instructions on MSDN talk about opening a command prompt and navigating to that directory; that is Microsoft internal instructions. For the rest of the world that does not use DOS and command prompt as much as we do inside , you can do any of these and it will work equally well.

      • Run WPConnect from a short-cut on your desktop. 
      • Copy the WPConnect executable some where in your path or your desktop or what ever and run it.

    The really important stuff is to:

    1. Do connect once with Zune before running WPConnect. As I mentioned, the infrastructure is shared.
    2. Make sure you stop Zune before you run WPConnect.
    3. Run WPConnect [any way you want, command prompt not required]

    The results:
    What you  will get is ability to debug applications that play Media on the phone without media library getting locked. You can also debug applications that interact with MediaLibrary.

    A couple of FAQs and or known issues:

    • The update to the tools is an MSP. It is pretty silent. Run it and as long as you do not get an error you will be fine. If you need to test if it succeeded, check for WPConnect.
    • There is no significant advantage or disadvantage between debugging using WPConnect and/or Zune. One is not faster than the other or any thing like that. It is same communication services underneath.
    • WPConnect runs for a few seconds and then exits.  This is expected, don’t be looking for it in taskmgr. If you launch it and it says it connected, you will be able to debug for hours without having to relaunch it. It is like a silent ninja, you don’t see it but it is there ready to strike.
    • Launching Zune any time after WPConnect is running will disconnect WPConnect. This most often happens if you disconnect your phone and connect it again.  The workaround is to close Zune and WPConnect again. 

    That should be all you need.  Read the full instructions for more troubleshooting tips. Hope that helps.

    Happy Windows Phone coding!

  • Jaime Rodriguez

    Hail to the swiss army knife of Silverlight Windows Phone Apps LongListSelector

    • 2 Comments


    Today,  David Anson announced the second release of the Silverlight for Windows Phone  toolkit.   

    This release doubles the number of controls in the kit, includes page transitions, ListPicker, and the new Swiss Army style control for Windows Phone: LongListSelector..
    I am still getting deep into LongListSelector and trying to fit into some apps, but the potential for it is so great, I am doing a preview post on it..

    LongListSelector started as a list that would address the requirements for lists similar to the people hub list.. 
    Headers and Footers that scrolls with the items in the list (see how the “new releases” header scrolls with the list items, this is great for panoramas )

    , WP7_1 (62)                      WP7_1 (63)WP7_1 (65)

    It then morphed into grouping ( similar to Quick Jump Grid control )  

    WP7_1 (67)

    WP7_1 (66)

     

     

     

     

     

     

     

     

    And finally but still equally important as a very performant listbox where you have a lot of control on how items are virtualized, how fast the list scrolls, how big your bounces are, etc.
    LongListSelector  uses a different scrolling mechanism ( animation on render thread ) and different virtualization strategy ( not a VirtualizingStackPanel) that results in better, smoother scrolling in most ListBoxes…

    image

    What are you waiting for???  Go download the toolkit from codeplex

    Happy Windows Phone Coding!

    PS --- Test thoroughly.. With this high degree of customization and so many features into a single control, it is not too hard to make a mistake..  Make sure as you replace your standard listboxes with LongListSelector, you tune the knobs so it works just right for your app..

Page 1 of 9 (210 items) 12345»