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

Tuesday, September 29, 2015

Phone calls Windows Phone 8 vs. Windows Phone 8.1

Problem:

I am migrating a windows phone 8 app to windows phone 8.1.  The move forward involved changes to the namespaces where the phone tasks occur

Solution:

Making a call in Windows Phone 8
  1. Add the following statement to your code.
    using Microsoft.Phone.Tasks;
  2. Add the following code to your application wherever you need it, such as in a button click event. To test this procedure, you can put the code in the page constructor. This is the code to launch the task.

    PhoneCallTask phoneCallTask = new PhoneCallTask();
    phoneCallTask.PhoneNumber = "2065550123";
    phoneCallTask.DisplayName = "Gage";
    phoneCallTask.Show(); 


Making a call in Windows Phone 8.1

Add the following code to your application wherever you need it, such as in a button click event. To test this procedure, you can put the code in the page constructor. This is the code to launch the task.


Windows.ApplicationModel.Calls.PhoneCallManager.ShowPhoneCallUI("phone number", "display name");

    Source:

    1. https://msdn.microsoft.com/de-de/library/windows/apps/hh394025(v=vs.105).aspx
    2. http://stackoverflow.com/questions/23555640/make-a-phone-call-in-windows-phone-8-1


    Access Existing SQLite database in Crossplatform solutions

    Background:

    I am trying to build out a crossplatform mobile solution using MVVMCross.  Stuart Lodge's N+1 series does a great job explaining how to use a new sqlite database.  The missing use case is how to implement the solution for an existing sqlite database.  I am working on that solution currently.

    Problem:

    My immediate issue was how to get the Windows Phone sqlite database from the installation into the app storage.

    Solution:

    private async Task CopyDatabase()
    {
        bool isDatabaseExisting = false;
        try
        {
            StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("people.db");
            isDatabaseExisting = true;
        }
        catch
        {
            isDatabaseExisting = false;
        }
        if (!isDatabaseExisting)
        {
            StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("people.db");
            await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
        }
    }



    Source:

    1. http://wp.qmatteoq.com/using-sqlite-in-your-windows-8-metro-style-applications
    2. http://wp.qmatteoq.com/import-an-already-existing-sqlite-database-in-a-windows-8-application/

    Tuesday, June 23, 2015

    Localized Strings does not exist in namespace

    Problem:
    Having completed the iPhone version of our MVVM cross project, we are back to the Windows Phone version.  I created the baseline phone project and added reference to the Core.  Then I built the Windows Phone 8 project and kept getting this error:
    The name "LocalizedStrings" does not exist in the namespace

    Solution:
    Close Visual Studio. Than, delete sub folders 10.0 and 11.0 from "%LOCALAPPDATA%\Microsoft\Phone Tools\CoreCon\" Open Visual Studio and rebuild solution.

    Where
    %LOCALAPPDATA% = C:\Users\[USER]\AppData\Local

    Source:
    http://stackoverflow.com/questions/23237549/vs-2013-the-name-localizedstrings-does-not-exist-in-the-namespace

    Friday, October 31, 2014

    Missing certificate for authenticated push notifications: Certificate for authenticated push notifications

    Problem:
    Finally we have approval to push this application and I was getting the following warning in Windows Phone Store

    "Missing certificate for authenticated push notifications: Certificate for authenticated push notifications"
     
    I have no more options than before. I have no push notifications in use.
     
    Solution:
     
    You should check your WMAppManifest.xml file. Do you have ID_CAP_PUSH_NOTIFICATION defined there?
     

    Wednesday, October 1, 2014

    Unauthorized Access Exception - MvxLocationWatcher in Windows Phone 8

    I have been working through Stuart Lodge's MvvmCross tutorial.  Session 12 is working with location watchers.  I was able to compile the solution but at run time I received the Unauthorized access error.

    Solution:
    1.) Solution Explorer
    2.) Expand properties of the Windows Phone project
    3.) Open WMAppManifest.xml
    4.) Capabilities tab
    5.) Select ID_CAP_LOCATION check box

    The application must grant this permission in order to use the onboard location features.


    Tuesday, September 23, 2014

    How to simulate a low-bandwidth connection or poor signal for Windows Phone 8

    Problem:

    Testing the Windows Phone with limited bandwidth for cell coverage has been something you need to do with a device attached to a VS debug session.  This obviously is not an optimal solution.  Visual Studio now has the Simulation Dashboard.

    Solution:

    To open the Simulation Dashboard, in Visual Studio, on the Tools menu, click Simulation Dashboard. After you open the dashboard, it remains open and available even when you open and close projects in Visual Studio.

    Source
    1. http://msdn.microsoft.com/en-us/library/windows/apps/jj206952(v=vs.105).aspx

    Tuesday, September 16, 2014

    MVVM and Windows Phone application bar

    Working a cross platform mobile solution.  I have the Commands defined in my mvvm core View Model.  I need to bind my View in the Windows Phone 8 application to the command in the ViewModel. 

    Problem:
    "Windows Phone AppBar's are naive rather than Silverlight controls - so they are not bindable"

    Solution:
    Get an addon which will support app bar binding for windows phone 8. 
    https://bindableapplicationb.codeplex.com/


    Source:
    http://stackoverflow.com/questions/25466816/how-to-do-binding-for-a-global-applicationbar-in-windows-phone-with-mvvmcross

    Tuesday, July 15, 2014

    Code Sample: Return Office element from Json query in Windows Phone

    I wanted to capture this deprecated piece of code which I no longer need in my phone app.
    We are supplying a list of office specific information to the phone client via a JSON query.

    Calling Method:


    using System.Net.WebClient;
    using Newtonsoft.Json.JsonConvert;

    private static Dictionary<int, Office> _officeLookup;
    private static List<Office> theOffices = new List<Office>();

    WebClient webClient = new WebClient();
    webClient.Headers["Accept"] = "application/json";
    webClient.DownloadStringCompleted +=
                  new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
    webClient.DownloadStringAsync(new Uri(apiUrl));



    private void webClient_DownloadStringCompleted(object sender,             DownloadStringCompletedEventArgs e);
    {
          try
          {
               if(e.Result != null)
              {
               var offices = JsonConvert.DeserializeObject<Office[]>(e.Result);
               theOffices = offices.ToList();
               int id = 0;
               foreach(Office office in offices)
               {
                    _officeLookup.Add(id,office);
                   id++;
                 }
              }
             }
             catch (Exception ex)
             {
                   //Error handling here
             }


    }

    Thursday, July 10, 2014

    Using progress indicator in windows phone systemtray

    I am going to add a progress bar to my existing phone app and found a good explanation at Microsoft's site.  It includes an example for implementing the progress bar programmatically or
    declaratively.


    Code Behind
    using Microsoft.Phone.Shell;

    namespace SystemTrayTest
    {
        public partial class MainPage : PhoneApplicationPage
        {
            ProgressIndicator prog;

            public MainPage()
            {
                InitializeComponent();

                SystemTray.SetIsVisible(this, true);
                SystemTray.SetOpacity(this, 0.5);
                SystemTray.SetBackgroundColor(this, Colors.Purple);
                SystemTray.SetForegroundColor(this, Colors.Yellow);

                prog = new ProgressIndicator();
                prog.IsVisible = true;
                prog.IsIndeterminate = true;
                prog.Text = "Click me...";

                SystemTray.SetProgressIndicator(this, prog);
            }
        }
    }


    XAML
    <shell:SystemTray.ProgressIndicator>
        <shell:ProgressIndicator IsIndeterminate="True" IsVisible="True" Text="Click me..." />
    </shell:SystemTray.ProgressIndicator>

    Source:
    http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff626537(v=vs.105).aspx

    Tuesday, June 10, 2014

    Connecting Windows Phone 8 Emulator to localhost.

    A while back I blogged on connecting to localhost from windows phone emulator.  I was trying out a new dev build today and having issues.  Debugging was failing to connect on my VS 2013 build. I realized that I was having firewall issues.
    I started by turning off all the firewalls to determine if this was the issue. Once the firewall was down I was able to connect from the emulator to localhost. I then modified the netsh command.

    Change the profile to public on the firewall connection.

    > netsh advfirewall firewall add rule name="IISExpressWeb" dir=in protocol=tcp localport=58938 profile=public remoteip=localsubnet action=allow

    Tuesday, May 13, 2014

    Windows Phone 8 photo/image resizing


    Problem:

    I am trying to wrap up my first phone application which submits text and photos to an email server.
    I wanted to control file size since the user can send anything on their phone.  I had been using the BitmapImage captured directly from the e.ChosenPhoto Task.  There are a number of great tutorials on basic photo capturing.  What they overlook is the the whole resizing issue.   The object for that is WriteableBitmap but you can't just cast the BitmapImage to WriteableBitmap.

    The BitmapImage is pretty much immutable once you create it.  That is there is no implicit cast to an object like WriteableBitMap.  Most solutions involve reading the content of the BitmapImage as a stream or array into an image and then casting to to WriteableBitmap.


    Solution 1:

    Mike Ormond's post was very helpful.  He used a memory stream and saved the resulting byte array to the MediaLibrary.

    void task_Completed(object sender, PhotoResult e)
    {
      if (e.Error == null)
      {
        BitmapImage bi = new BitmapImage();
        bi.SetSource(e.ChosenPhoto);
        Image image1 = new Image()
        {
          Width = 800,
          Height = 600,
          Visibility = System.Windows.Visibility.Collapsed,
          Source = bi
        };
        ScaleTransform st = new ScaleTransform()
        {
          ScaleX = 0.1,
          ScaleY = 0.1
        };
        WriteableBitmap wb = new WriteableBitmap(image1, st);
        ThreadPool.QueueUserWorkItem(callback =>
        {
          MemoryStream ms = new MemoryStream();
          wb.SaveJpeg(ms, 80, 60, 0, 80);
          using (MediaLibrary lib = new MediaLibrary())
            lib.SavePicture("Test", ms.ToArray());
        });
      }
    }

    Solution 2:
    Take the resulting source photo directly to a WriteableBitmap.


    WritableBitmap bitmap = new WritableBitmap(); //Use appropriate constructor
    bitmap.SetSource(e.ChosenPhoto);
    or

    ScaleTransform st = new ScaleTransform()
    {
    ScaleX = 0.1,
    ScaleY = 0.1
    };
    WriteableBitmap wb = new WriteableBitmap(e.ChosenPhoto, st);

    Source:
    http://msdn.microsoft.com/en-us/library/dd638675(v=vs.95).aspx
    http://stackoverflow.com/questions/8252001/wp7-5e-chosenphoto-issue

     Solution 3:

    public void DecodePhoto(byte[] byteVal)
            {
                if (byteVal == null) return ;

                try
                {
                    MemoryStream strmImg = new MemoryStream(byteVal);
                    BitmapImage myBitmapImage = new BitmapImage();
                    myBitmapImage.BeginInit();
                    myBitmapImage.StreamSource = strmImg;
                    myBitmapImage.DecodePixelWidth = 200;
                    myBitmapImage.EndInit();
                    MugShot.Source = myBitmapImage;
                }
                catch (Exception ex)
                {
                    string message = ex.Message;
                }
            }
    Source:
    http://stackoverflow.com/questions/8897210/byte-to-bitmapimage
    http://stackoverflow.com/questions/14718855/how-to-create-writeablebitmap-from-bitmapimage

    Writable bit map SDK

    https://www.blogger.com/blogger.g?blogID=8256225704949716108#editor/target=post;postID=5955005466364600781

    http://stackoverflow.com/questions/5774038/resizing-resulting-camera-stream

    Monday, May 12, 2014

    Wednesday, May 7, 2014

    Calling Web API from a Windows Phone 8 Application

    Robert McMurray has posted a great tutorial on the ASP.Net site from Microsoft.
    It combines some APIs want to get a better handle on Web API, HttpClient and
    the Windows Phone API


    http://www.asp.net/web-api/overview/web-api-clients/calling-web-api-from-a-windows-phone-8-application

    How to do a multipart post with file upload using WebApi HttpClient

    Problem:  My app needs to submit a user form to a web backend.  There are a number
    of easy ways to do this via the WP8 SDK to upload files.  These are all done pretty much
    with GETs vice POSTS.  I looked around for some solutions to do a multipart submittal since
    my form will have files as well as text to submit. The only issue is getting the files as byte arrays.
    I will do a post on this particular issue at another time.



    Solution:

    Form:

         <form action="/api/workitems" enctype="multipart/form-data" method="post">
            <input type="hidden" name="type" value="ExtractText" />
            <input type="file" name="FileForUpload" />
            <input type="submit" value="Run test" />
        </form>


    Code behind
     using (var client = new HttpClient())
    {
        using (var content = new MultipartFormDataContent())
        {
            var values = new[]
            {
                new KeyValuePair<string, string>("Foo", "Bar"),
                new KeyValuePair<string, string>("More", "Less"),
            };
            foreach (var keyValuePair in values)
            {
                content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
            }
            var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "Foo.txt"
            };
            content.Add(fileContent);
            var requestUri = "/api/action";
            var result = client.PostAsync(requestUri, content).Result;
        }
    }

    Source:
    http://stackoverflow.com/questions/10339877/asp-net-webapi-how-to-perform-a-multipart-post-with-file-upload-using-webapi-ht

    Tuesday, May 6, 2014

    Windows Phone 8 - How to get a certain IsolatedStorageSetting Key

    Problem

    I was puzzling over this issue due to isolated storage which I am using on one of my applications.
    I need to retrieve a setting from storage but was could not assume that the key exists.  If I attempted to query a null value then I would get an error. 

    Solution

    ICollection<string> sKeys = (ICollection<string>) IsolatedStorageSettings.ApplicationSettings.Keys
    if(!sKeys.Contains(AppResources.SavedReportKeyName))
    {
    //Create key in isolated storage
    }


    Source:
    http://social.msdn.microsoft.com/Forums/wpapps/en-US/529d6dad-fcfe-4609-9a64-097dcd0bae33/how-to-get-a-certain-isolatedstoragesetting-key?forum=wpdevelop

    Friday, March 14, 2014

    Screen Masking for Windows Phone 8 Textbox Control

    This is a pretty common theme on google.  Given the variety of explanations which were quite interesting and thorough but not exactly what I needed.  I finally reverted back to MSDN and found
    what I was looking for.  the Textbox control in Silverlight supports a property called InputScopeNameValue.  This allows one to determine the keyboard layout of the SIP (software input panel).    One just sets the property to the desired setting to control input on the textbox.

    <TextBox Text="HelloWorld">
        <TextBox.InputScope>
            <InputScope>
                <InputScopeName NameValue="Url" />
            </InputScope>
        </TextBox.InputScope>
    </TextBox>

    SIP layoutXAML or enumeration valueSIP description
    DefaultDefault, and other standard input scope valuesStandard QWERTY layout
    TextTextStandard layout with features such as autocorrect and text suggestion
    WebUrlStandard layout with .com and customized Enter key for typing URLs.
    E-mail addressEmailSmtpAddressStandard layout with .com and @ key.
    E-mail name or addressEmailNameOrAddressStandard layout with .com and @ key, and easy access to phone number layout.
    MapsMapsStandard layout with a customized Enter key. Used to type a location to search for on a map
    Phone numberTelephoneNumber12-key layout
    SearchSearchSemi-transparent layout with a Search and .com key.
    SMS contactNameOrPhoneNumberStandard layout with access to phone number layout. Used to type in the SMS To field
    ChatChatText input that uses intelligent features such as abbreviations

    Source:http://msdn.microsoft.com/en-us/library/ff426929(v=vs.95).aspx

    Thursday, March 6, 2014

    Getting out of the SIP (Soft Input Panel) programmatically

    I have been cranking on my first phone application and working with some basic user requirements.
    I did not get to far in before I ran into this issue.  Most of the how apps just blow by the simple issue
    of going from one text element to the next.  I just assumed it was like working with a web form.  Well forgot I am not working with a the benefit of a browser which defines a lot of this default behavior. 

    The text box control will display the SIP as soon as you focus on it.  The issue is when you want to leave the textbox.  The return key and tab key will not kick you back out to the page level.  You need to handle the event Keyup or LostFocus.


    XAML

    <TextBox Name="Input" KeyUp="Input_KeyUp" LostFocus="Input_KeyUp"  FontSize="40"></TextBox>
     
    C# Code Behind

    private void Input_KeyUp(object sender, KeyEventArgs e){ if (e.Key == Key.Enter) { this.Focus(); }}


    The call to the main page will return the focus from the current textbox back to the phoneapplicationpage. 


    Source:
    http://blogs.msdn.com/b/silverlight_sdk/archive/2010/07/02/programmatically-dismiss-the-sip-keyboard-in-windows-phone-silverlight-app.aspx