Windows Phone Tips and Tricks

Here are some questions representing the tips and tricks for Windows Phone, 

Question: How to determine the installed OS version on Windows Phone?
  1. Version InstalledVersion = System.Environment.OSVersion.Version;  
Question: How to check whether data connection is enabled on Windows phone device?
  1. if (DeviceNetworkInformation.IsNetworkAvailable)   
  2. {  
  3.   
  4. }  
Question: How to check whether Wi-Fi Connection is enabled on Windows phone device?
  1. if (DeviceNetworkInformation.IsWiFiEnabled)  
  2. {  
  3. }  
Question: How to check whether Cellular Data Connection is enabled on Windows phone device?
  1. if (DeviceNetworkInformation.IsCellularDataEnabled )  
  2. {  
  3. }  
Question: How to check whether location is enabled on Windows Phone device?
  1. // First create the instance of "Windows.Devices.Geolocation.Geolocator" class   
  2. var geoLocator = new Geolocator();  
  3. if (geoLocator.LocationStatus == PositionStatus.Disabled)  
  4. {  
  5.     // Location Service is turned OFF  
  6. }  
  7. else  
  8. {  
  9.     // Location Service is already enabled.  
  10. }  
Question: How to display the Application list of your publisher name in Windows phone app?
  1. //In this example the publisher name is Suresh  
  2. await Windows.System.Launcher.LaunchUriAsync(new Uri("zune:search?publisher=Suresh"));  
Question: How to detect the Back Button is pressed in Windows Phone 8 app?
  1. protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)  
  2. {  
  3.    //back key is pressed  
  4. }  
Question: How to handle Back Key with Message Box Buttons Ok & Cancel?
  1. MessageBoxResult msg = MessageBox.Show("ConfirmExit_MSG""Notes", MessageBoxButton.OKCancel);  
  2. if (msg == MessageBoxResult.OK)  
  3. {}  
  4. else if (msg == MessageBoxResult.Cancel)  
  5. {  
  6.     e.Cancel = true;  
  7. }  
Question: How to Remove Navigation Back Entry in Windows Phone?
  1. // To Remove Single Entry  
  2. NavigationService.RemoveBackEntry();  
  3. //To remove all navigation back entry  
  4. while (NavigationService.CanGoBack) NavigationService.RemoveBackEntry();  
  5. //Remove navigation back entry except MainPage  
  6. if (NavigationService.BackStack.Any())  
  7. {  
  8.     var length = NavigationService.BackStack.Count() - 1;  
  9.     var i = 0;  
  10.     while (i < length)  
  11.     {  
  12.         NavigationService.RemoveBackEntry();  
  13.         i++;  
  14.     }  
  15. }  
Question: How to detect if Battery Saver is Currently Enabled on Windows Phone 8.
  1. if ((bool)typeof(PowerManager).GetProperty("PowerSavingModeEnabled").GetValue(nullnull))  
  2. {  
  3.    //Battery Saver enabled  
  4. }  
Question: How to open the Settings screen programmatically in Windows Phone?
  1. ConnectionSettingsTask connectionTask = new ConnectionSettingsTask();  
  2. connectionTask.ConnectionSettingsType = ConnectionSettingsType.WiFi;  
  3. connectionTask.Show();  
Question: How to opening Settings Screen using Launch URI in Windows Phone?
  1. await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-lock"));  
Question: The following is the list of Launch URI that can help in opening various settings from an App.

 

  1. ms-settings-airplanemode: .
  2. ms-settings-bluetooth:
  3. ms-settings-cellular:
  4. ms-settings-emailandaccounts:
  5. ms-settings-location:
  6. ms-settings-power:
  7. ms-settings-screenrotation:
  8. ms-settings-wifi:

Question: How to hide the soft keyboard in Windows Phone by focusing the other UI element?

  1. this.Focus();  
Question: How to determine the mobile operator in Windows Phone ?

 

  1. string getMobileOperatorName = DeviceNetworkInformation.CellularMobileOperator;  
Question: How to get screen resolutions in Windows Phone 8?
  1. int getResolution = App.Current.Host.Content.ScaleFactor;  
Question: How to get screen Height and width in Windows Phone 8?
  1. double getHeight = App.Current.Host.Content.ActualHeight;  
  2. double getWidth = App.Current.Host.Content.ActualWidth;  
Question: How to Navigate Page in Windows Phone?
  1. NavigationService.Navigate(new Uri("/PageName.xaml", UriKind.Relative));  
Question: How to get device battery level in Windows Phone?
  1. string batterlvelinPercentage = Windows.Phone.Devices.Power.Battery.GetDefault().RemainingChargePercent.ToString();  
Question: How to get device battery remaining discharge time in Windows Phone?
  1. string remainingTime= Windows.Phone.Devices.Power.Battery.GetDefault().RemainingDischargeTime.ToString();  
Question: How to get Windows Phone Unique Device Id?
  1. object uniqueId;  
  2. DeviceExtendedProperties.TryGetValue("DeviceUniqueId"out uniqueId);  
  3. var hexString = BitConverter.ToString((byte[])uniqueId).Replace("-"string.Empty);  
Question: How to find how much space available and used in isolated storage?
  1. IsolatedStorageFile getIsoInfo = IsolatedStorageFile.GetUserStoreForApplication();  
  2. long avilableBytes = getIsoInfo.AvailableFreeSpace;  
  3. long usedBytes = getIsoInfo.Quota - getIsoInfo.AvailableFreeSpace;  
Question: How to terminate the current Windows Phone app?
  1. Application.Current.Terminate();  
Question: How to get the string from AppResources file in Windows Phone?
  1. string ApplicationTitle = AppResources.ApplicationTitle;  
Question: How to prevent the app deployment in SD card?
  1. Open the WMAppManifest.xml file. This will open the WMAppManifest.xml in GUI designer.

  2. Navigate to the Packaging tab.

  3. Enable “Prevent deployment to SD cards” and save the project.

    Enable

Question: How to increase the Windows Phone App limited memory?

Windows Phone App is limited to use 150 MB at maximum per app. But sometimes it is required to be more than this limit at least to run in high spec devices. To solve this problem, you can define on your App to ensure you have high availability of application memory.

To increase the size of memory usage we add the following node to the Manifest file of Windows Phone App:

  1. ?  
  2. <App>  
  3.    <FunctionalCapabilities>  
  4.       <FunctionalCapability Name="ID_FUNCCAP_EXTEND_MEM"/>  
  5.    </FunctionalCapabilities>  
  6. </App>  
There is another functional capability which will ensure that the large memory is available before running the application and opt out the Low memory phones from running the app. If this is your requirement you can use:
  1. ?  
  2.    <App>  
  3.    <Requirements>  
  4.    <Requirements Name="ID_REQ_MEMORY_300"/>  
  5.    </Requirements>  
  6. </App>  
If you use the above capability, the App won’t appear in Windows Phone Store for lower memory phones and it can’t be installed in low end devices.

Based on your requirement, you can increase the size boundary from 150 MB to 300 MB or for some devices up to 1GB of application memory usage.

Question: How to find if the user has tapped on the Screen in Windows Phone 8 App?
  1. Touch.FrameReported += Touch_FrameReported;  
  2. void Touch_FrameReported(object sender, TouchFrameEventArgs e)  
  3. {  
  4.    TouchPoint touchPoint = e.GetTouchPoints(this.Content).FirstOrDefault();  
  5. }  
Question: How to Get the Windows Phone App version from WMAppManifest file ?
  1. string appVersionNumber = XDocument.Load("WMAppManifest.xml").Root.Element("App").Attribute("Version").Value;  
Question: How to detect the audio endpoint device in Windows Phone App?
  1. AudioRoutingEndpoint currentEndpoint = AudioRoutingManager.GetDefault().GetAudioEndpoint();  
Question: The AudioRoutingEndpoint is enum which contains one of the following values:
  1. public enum AudioRoutingEndpoint  
  2. {  
  3.     Default = 0,  
  4.     // An earpiece.  
  5.     Earpiece = 1,  
  6.     // The speakerphone.  
  7.     Speakerphone = 2,  
  8.     // A Bluetooth device.  
  9.     Bluetooth = 3,  
  10.     // A wired headset.  
  11.     WiredHeadset = 4,  
  12.     // A wired headset for output only; the input is received from the default microphone.  
  13.     WiredHeadsetSpeakerOnly = 5,  
  14.     // A Bluetooth device with noise and echo cancellation.  
  15.     BluetoothWithNoiseAndEchoCancellation = 6,  
  16. }  
Note: You need to add the ID_CAP_VOIP capability in your WMAppManifest file.

Question: How to test Windows Phone App on device without a Developer account?

Simply use your Microsoft account (live id), since it is enough for testing the app on device.
Only one device is allowed for per live id.

Question: How many device can be allowed to unlock the device using Developer account?

You can have up to 3 devices to be developer unlocked for app development and testing.

Question: How to Get the list of IP Address of the Windows Phone?
  1. List<string> IPaddressList = new List<string>();  
  2. var Hosts = Windows.Networking.Connectivity.NetworkInformation.GetHostNames().ToList();  
  3. foreach (var Host in Hosts)  
  4. {  
  5.    string IP = Host.DisplayName;  
  6.    IPaddressList.Add(IP);  
  7. }  
Question: How to Get the Current Location in Windows Phone 8?
  1. Geolocator geoLocator = new Geolocator();  
  2.   
  3. Geoposition position = await geoLocator.GetGeopositionAsync();  
  4.   
  5. Geocoordinate coordinate = position.Coordinate;  
  6.   
  7. string Location = "Latitude = " + coordinate.Latitude + " Longitude = " + coordinate.Longitude;  
Question: How to get the address of the location using latitude and longitude?
  1. WebClient client = new WebClient();  
  2. client.DownloadStringCompleted += client_DownloadStringCompleted;  
  3. string Url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=""123235.4""," + "7643643" + "&sensor=true";  
  4. client.DownloadStringAsync(new System.Uri(Url, UriKind.RelativeOrAbsolute));  
Question: How to retrieve the Remaining time and percentage of the Windows Phone 8 device battery?
  1. string remainingtime= Windows.Phone.Devices.Power.Battery.GetDefault().RemainingDischargeTime.TotalMinutes.ToString();  
  2.   
  3. string remainingPercentage= Windows.Phone.Devices.Power.Battery.GetDefault().RemainingChargePercent.ToString();  
Question: The Battery class includes the property RemainingDischargeTime which is a read only property that gets the time left for the windows phone device battery to be fully discharged.

Get the access to the Battery instance with the Battery.GetDefault() and then use the property RemainingDischargeTime to retrieve the time left and RemainingChargePercent percentage left.

Question: How to Create a Toast Prompt in Windows Phone 8?
  1. var toastPrompt = new ToastPrompt  
  2. {  
  3.    Title = "Suresh M",  
  4.    TextOrientation = System.Windows.Controls.Orientation.Vertical,  
  5.    Message = "https://windowsapptutorials.wordpress.com/"  
  6. };  
  7. toastPrompt.Show();  
Question: How to Vibrate the Windows Phone?
  1. VibrateController vibrate = VibrateController.Default;  
  2. vibrate.Start(TimeSpan.FromMilliseconds(1000));  
  3. How to Format the String in XAML TextBlock Control in Windows Phone?  
  4. Text Formatting  
  5. <TextBlock>  
  6.    <Run Text="String with 5 characters length: "/>  
  7.    <Run Text="{Binding Text, StringFormat=\{0\,5\} }"/>  
  8. </TextBlock>  
Number Formatting
  1. <TextBlock>  
  2.    <Run Text="The number with 3 decimal point: "/>  
  3.    <Run Text="{Binding Number, StringFormat=\{0:n3\}}"/>  
  4. </TextBlock>  
Date Formatting
  1. <TextBlock Text="{Binding SendingDate,StringFormat='dd/MM/yyyy HH:mm'}"/>  
Question: How to run both 512MB and 256MB Windows Phone emulator simultaneously?

Sometimes we need to test the performance of the app in different version, so I tried to find out a way and share here.
  • Launch the app under 512 MB emulator
  • Stop the debugger (don’t close the emulator)
  • Change the debug target to 256 MB emulator and launch the app gain.
  • Now you can see both the emulators Up & Running.
  • Now do your testing.

Question: How Windows Phone App Developer Getting Help to develop windows phone app?

Question: How to support Portrait and Landscape orientation in Windows Phone Screen?

In your Xaml page change the default SupportedOrientations="Portrait" to SupportedOrientations="PortraitOrLandscape"

To set default Orientation set the orientation="Landscape" or Portrait

Question: How to get all the contact details in windows phone?

  1. Contacts cons = new Contacts();  
  2.   
  3. //Identify the method that runs after the asynchronous search completes.  
  4. cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted_Many);  
  5.   
  6. //Start the asynchronous search.  
  7. cons.SearchAsync(String.Empty, FilterKind.None, "Contacts Test #3 Picture");  
  8. void Contacts_SearchCompleted_Many(object sender, ContactsSearchEventArgs e)  
  9. {  
  10.   
  11. }  
Question: How to get all pictures from Camera Roll in Windows Phone?
  1. var mel = new MediaLibrary();  
  2. var Pictures = mel.Pictures;  
  3. PictureAlbumCollection picture = mel.RootPictureAlbum.Albums;  
  4. PictureAlbum cameraRoll = picture.Where(album => album.Name == "Camera Roll").First();  
  5. var CameraRollPictures = cameraRoll.Pictures;  
Windows Phone performance killers and tips

Don’t use too many Converters and Bindings, since they are Performance Killers

Converters are one of the most significant killers of performance (second perhaps to binding itself) in an XAML application.
  • Load only the content needed.

    The smaller the content, the faster loading occurs.

  • Use DXT to compress textures.

    Compressing the content is smaller, sometimes dramatically smaller. This reduces loading time.
    Allocate memory for Reusable Objects.

    Allocate a set of reusable objects and reinitialize them as needed. Reusable objects never need to be freed, and reduce the number of additional allocations.

  • Manually call GC.Collect()

    Manually call the garbage collector at the time of loading screen.

  • Measuring Performance

    Several tools are available for analyzing the .NET garbage collection heap. One tool available from Microsoft is the CLR Profiler. The tool is free and it is available for download at:

    CLR Profiler for the .NET Framework 2.0.

  • Steps to run the CLR profiler

    Download the CLR Profiler, and then extract the files.

    Navigate to CLRProfiler\Binaries\x86 (or x64), and then run CLRProfiler.exe.

    Click Start Application, and then select your application.

It will generate a graph that displays information about all objects in the garbage collection heap, and references related to these structures.

Keep overall memory use under 90 MB.


Similar Articles