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

Wednesday, August 26, 2015

“Unable to connect to a phone. Make sure the Windows Phone IP over USB transport service is running”

Problem

Upgraded to Windows 10 and now VS will not connect to my windows phone over the usb cable!

Solution

  1. Restart IpOverUsbSvc service. (Control Panel > Administrative Tools > Services)
  2. Restart phone, and turn off Set Automatic in date+time.

Source

http://stackoverflow.com/questions/24153897/getting-error-unable-to-connect-to-a-phone-make-sure-the-windows-phone-ip-over

Tuesday, August 18, 2015

Windows Phone kill application everytime

Problem:


One issue I have with a windows application is application lifecycle.  I need to make sure that the app is terminated each time a user leaves the app.  The app can be Closed or deactivated.  The deactivation can leave the app running in the background.

 

Solution:

Add the following code block to the App.xaml.cs at the root level of your windows phone project.
Locate the method Application_Deactivated.

private void Application_Deactivated(object sender, ClosingEventArgs e)
{
      App.Current.Terminate();
}

MVVMCross - System.Reflection.TargetInvocationException was unhandled Message: An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in System.Windows.ni.dll

Problem:


I have my Windows phone project working great with my pcl core.  The MVVMCross libraries are working without issue.  What I have occurring is bug in the UI.  I open my app and run it just fine.  I then hit the windows button which puts the application into background.

When I reactivate the application it crashes with this error:

System.Reflection.TargetInvocationException was unhandled Message: An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in System.Windows.ni.dll

Solution:

I thought at first it would be an IoC error but it occurs to early for that.  I had to set a breakpoint in the app.xaml.cs in the Windows UI project.  The key was to set it at the Application_Activated event.
Otherwise the crash occurs and it goes straight to the dump.  I was able to walk through the issue until I hit the event RootFrame_NavigationFailed event.  Here I discovered the issue.  I took a look at the e.Exception (e is type NavigationFailedEventArgs).

e.Exception

{System.InvalidOperationException: No XAML found at the location /MainPage.xaml ...

So that was my issue!   The modifications to use MVVMCross means we do not need this page since the setup.cs file does the IoC transfer of the app at startup.  This transfer pushes control down to the PCL layer. My oversight was that the WMAppManifest.xml file has a navigation Page attribute which was set too MainPage.xaml.


NOTE to MVVMCross Users:
What I neglected to do was what Stuart Lodge points out in his N+5 series.  The key event RootFrameOnNavigation in App.xaml.cs needs to handle the IoC redirection.  I did not do this in my Windows project.  Thus the event should include the following code

Fix 1:
private void RootFrameOnNavigating(object sender, NavigatingCancelEventArgs args)
{
args.Cancel = true;
RootFrame.Navigating -= RootFrameOnNavigating;
RootFrame.Dispatcher.BeginInvoke(() => { Cirrious.CrossCore.Mvx.Resolve<Cirrious.MvvmCross.ViewModels.IMvxAppStart>().Start(); });
}

Fix 2:
I continued to have problems due to some code I dropped into the InitializePhoneApplication event.
It says don't touch very clearly!  I did anyway and this was also causing load time issues.  I eliminated my extra code and the method should look like this:

// Do not add any additional code to this method
private void InitializePhoneApplication()
{

            if (phoneApplicationInitialized)

                return;
            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
}


Now that I have done both of these steps I no longer receive the error.

Source:
  1. https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/blob/master/N-05-MultiPage/MultiPage.Phone/App.xaml.cs
  2. http://mvvmcross.blogspot.com/

Monday, August 17, 2015

MVVMCross Core solution throws error - Unhandled managed exception

Problem:

I just completed the Windows Phone UI project for an MVVMCross solution.  The core project is used by iPhone and Windows Phone UI.  Upon completion of testing for WP, I decided to run a few tests against iPhone which I had completed earlier.  I was immediately confronted with an error -

"An Unhandled exception occurred"

The Xamarin log shows the error occurring at load time.  The compiler built out the bits.  The attempt to run in debug did reveal some more interesting leads. 

[3641:134567] Unhandled managed exception: Could not load file or assembly 'Windows' or one of its dependencies.  The system cannot find the file specified.  (System.IO.FileNotFoundException)

I continued to play around with the changes I had made to the Core PCL.  Then I found the issue.

Solution:

In the course of building the Windows Phone project I used the LongListSelector. This Windows Phone control has several dependcies which are specific to Windows Phone.  The Core PCL included some code which depended on the library Microsoft.Phone.dll.  This reference is not compatible with the Monotouch framework.  My code worked fine when I compiled to Windows Phone but as soon as I tried to run the exe to Monotouch I raised the error. 

My solution was to surround the code with conditional compilation commands

#if USE_MVVMCROSS_WP8

....

#endif

Source:
http://typecastexception.com/post/2012/08/18/Visual-Studio-Use-Conditional-Compilation-to-Control-Runtime-Settings-for-Different-Deployment-Scenarios.aspx

Monday, August 10, 2015

Mulitline Xaml button in Windows Phone

Problem:
I was trying to get a button to include multiple lines.  I tried using the declarative syntax in the button

<Button
Content="My Main Title \n Subtitle"/>

This did not work since this is going to render without the formatting implied inline.

Solution:
Really straight forward just add the textbox control into the button control and move on.

<Button
 Command="{Binding MVVMControl}"
 Name="MyFabulousButton">

<TextBlock
TextAlignment="Center"
TextWrapping="Wrap">
First Line
<Linebreak/>
Second Line
</TextBlock>
</Button>






Source
http://stackoverflow.com/questions/1449276/multline-text-in-a-wpf-button

Monday, April 27, 2015

MVVMCross Extended Splash Screen Crossplatform (iOS/Android/WP)

Problem:
Trying to get the splash screen of the application to run longer then the default for each platform.  The typical answer I see posted on most sites is to use the default properties for each of the platform projects.  I wanted something I had more control of.  We are using the MVVMCross pattern for the application and so I wanted to put the solution into the PCL for use on all 3 platforms.  This solution creates a View with the splash screen image which can be extended via the timer function.  This allows us to display the image as long or short as we need it.


Solution:
I found several sites with tips and some hints from Stuart Lodge.  I managed to come up with a solution which builds on some code I found over at the Xamarin developer site.  The timer class should be placed in the PCL of your project.  It can then be referenced by your ModelView and this in turn binds to the View.

1.) Timer Class

using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace iReport.Core
{
 

    /// <summary>
    /// Missing from PCL, except if targeting .NET 4.5.1 + Win8.1 + WP8.1
    /// </summary>
    internal sealed class Timer : CancellationTokenSource
    {
        internal Timer(Action<object> callback, object state, int millisecondsDueTime, int millisecondsPeriod, bool waitForCallbackBeforeNextPeriod = false)
        {
            //Contract.Assert(period == -1, "This stub implementation only supports dueTime.");

            Task.Delay(millisecondsDueTime, Token).ContinueWith(async (t, s) =>
            {
                var tuple = (Tuple<Action<object>, object>)s;

                while (!IsCancellationRequested)
                {
                    if (waitForCallbackBeforeNextPeriod)
                        tuple.Item1(tuple.Item2);
                    else
                        Task.Run(() => tuple.Item1(tuple.Item2));

                    await Task.Delay(millisecondsPeriod, Token).ConfigureAwait(false);
                }

            }, Tuple.Create(callback, state), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
                Cancel();

            base.Dispose(disposing);
        }
    }


}

2.)Model View

using Cirrious.MvvmCross.ViewModels;
using iReport.Core.Services.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;


namespace iReport.Core.ViewModels
{
    public class TimerViewModel : MvxViewModel
    {
        private DateTime? _whenToFinish;
        private Timer _timer;
        public TimerViewModel()
        {
                    _timer = new Timer(OnTick, null, 1000, 1000);
                    _whenToFinish = DateTime.UtcNow.AddSeconds(3);
        }

        #region Timer Test
            private void OnTick(object state)
            {
                if (!_whenToFinish.HasValue)
                    return;

                if (DateTime.UtcNow >= _whenToFinish.Value)
                {
                    base.ShowViewModel<MainViewModel>();

                    _whenToFinish = null;
                }
            }

        
        
        #endregion

    }
}


3.)View


using Cirrious.MvvmCross.Binding.BindingContext;
using Cirrious.MvvmCross.Touch.Views;
using Cirrious.MvvmCross.ViewModels;
using iReport.Core.ViewModels;
using iReport.Touch.Controls;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;

namespace iReport.Touch.Views
{

    [Register("TimerView")]
    public class TimerView : MvxViewController
    {
        private BindableProgress _bindableProgress;


        public override void ViewDidLoad()
        {

            View = new UIView() { BackgroundColor = UIColor.Gray };

            base.ViewDidLoad();

            this.NavigationController.ToolbarHidden = true;
            this.NavigationController.NavigationBarHidden = true;

            UIImage splashscreen = MaxResizeImage(UIImage.FromFile("Default.png", UIScreen.MainScreen.Bounds.Width,UiScreen.MainScreen.Bounds.Height);

             UIImageView splashView = new UIImageView(splashscreen);
             Add(splashView);

            var set = this.CreateBindingSet<TimerView, Core.ViewModels.TimerViewModel>();
           

          
            set.Apply();

        }
    }
 // resize the image to be contained within a maximum width and height, keeping aspect ratio
public UIImage MaxResizeImage(UIImage sourceImage, float maxWidth, float maxHeight)
{
    var sourceSize = sourceImage.Size;
    var maxResizeFactor = Math.Max(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
    if (maxResizeFactor > 1) return sourceImage;
    var width = maxResizeFactor * sourceSize.Width;
    var height = maxResizeFactor * sourceSize.Height;
    UIGraphics.BeginImageContext(new SizeF(width, height));
    sourceImage.Draw(new RectangleF(0, 0, width, height));
    var resultImage = UIGraphics.GetImageFromCurrentImageContext();
    UIGraphics.EndImageContext();
    return resultImage;
}



}

Source:

  1. http://stackoverflow.com/questions/5429746/how-to-get-width-and-height-of-iphone-ipad-using-monotouch
  2. http://forums.xamarin.com/discussion/4170/resize-images-and-save-thumbnails
  3. http://forums.xamarin.com/discussion/27327/ios-background-image-scale
  4. http://stackoverflow.com/questions/20447787/system-threading-timer-issue-only-timer-in-mvvmcross
  5. http://stackoverflow.com/questions/15961664/viewmodel-lifecycle-when-does-it-get-disposed
  6. https://code.msdn.microsoft.com/windowsapps/Splash-screen-sample-89c1dc78
 

Wednesday, July 2, 2014

How to load XML file located inside the folder of the application in window phone 8

Problem:

I have some onboard xml files which I needed to load into memory.  I was puzzling over how to load them into memory for use in my app.  I tried using XDocument library but I kept getting the error:
"Cannot find file '/XML Files/A.xml' in the application xap package.

XDocument doc = XDocument.Load( "XML Files/MyXmlFile.xml" );

This was not working.  I tried several variations but still was getting the error every time I ran to code.

Solution:
It turns out that my syntax was not the problem.  I needed to set the properties on the xml file correctly. 

1.) Build Action=Content
2.)Copy to output=Copy if newer (or Copy always).


Source:

http://stackoverflow.com/questions/4538874/how-to-load-xml-file-located-inside-the-folder-of-the-application-in-window-phon