Here are some questions representing the tips and tricks for Windows Phone,
Question: How to determine the installed OS version on Windows Phone?
- Version InstalledVersion = System.Environment.OSVersion.Version;
Question: How to check whether data connection is enabled on Windows phone device?
- if (DeviceNetworkInformation.IsNetworkAvailable)
- {
-
- }
Question: How to check whether Wi-Fi Connection is enabled on Windows phone device?
- if (DeviceNetworkInformation.IsWiFiEnabled)
- {
- }
Question: How to check whether Cellular Data Connection is enabled on Windows phone device?
- if (DeviceNetworkInformation.IsCellularDataEnabled )
- {
- }
Question: How to check whether location is enabled on Windows Phone device?
-
- var geoLocator = new Geolocator();
- if (geoLocator.LocationStatus == PositionStatus.Disabled)
- {
-
- }
- else
- {
-
- }
Question: How to display the Application list of your publisher name in Windows phone app?
-
- 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?
- protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
- {
-
- }
Question: How to handle Back Key with Message Box Buttons Ok & Cancel?
- MessageBoxResult msg = MessageBox.Show("ConfirmExit_MSG", "Notes", MessageBoxButton.OKCancel);
- if (msg == MessageBoxResult.OK)
- {}
- else if (msg == MessageBoxResult.Cancel)
- {
- e.Cancel = true;
- }
Question: How to Remove Navigation Back Entry in Windows Phone?
-
- NavigationService.RemoveBackEntry();
-
- while (NavigationService.CanGoBack) NavigationService.RemoveBackEntry();
-
- if (NavigationService.BackStack.Any())
- {
- var length = NavigationService.BackStack.Count() - 1;
- var i = 0;
- while (i < length)
- {
- NavigationService.RemoveBackEntry();
- i++;
- }
- }
Question: How to detect if Battery Saver is Currently Enabled on Windows Phone 8.
- if ((bool)typeof(PowerManager).GetProperty("PowerSavingModeEnabled").GetValue(null, null))
- {
-
- }
Question: How to open the Settings screen programmatically in Windows Phone?
- ConnectionSettingsTask connectionTask = new ConnectionSettingsTask();
- connectionTask.ConnectionSettingsType = ConnectionSettingsType.WiFi;
- connectionTask.Show();
Question: How to opening Settings Screen using Launch URI in Windows Phone?
- 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.
- ms-settings-airplanemode: .
- ms-settings-bluetooth:
- ms-settings-cellular:
- ms-settings-emailandaccounts:
- ms-settings-location:
- ms-settings-power:
- ms-settings-screenrotation:
- ms-settings-wifi:
Question: How to hide the soft keyboard in Windows Phone by focusing the other UI element?
Question: How to determine the mobile operator in Windows Phone ?
- string getMobileOperatorName = DeviceNetworkInformation.CellularMobileOperator;
Question: How to get screen resolutions in Windows Phone 8?
- int getResolution = App.Current.Host.Content.ScaleFactor;
Question: How to get screen Height and width in Windows Phone 8?
- double getHeight = App.Current.Host.Content.ActualHeight;
- double getWidth = App.Current.Host.Content.ActualWidth;
Question: How to Navigate Page in Windows Phone?
- NavigationService.Navigate(new Uri("/PageName.xaml", UriKind.Relative));
Question: How to get device battery level in Windows Phone?
- string batterlvelinPercentage = Windows.Phone.Devices.Power.Battery.GetDefault().RemainingChargePercent.ToString();
Question: How to get device battery remaining discharge time in Windows Phone?
- string remainingTime= Windows.Phone.Devices.Power.Battery.GetDefault().RemainingDischargeTime.ToString();
Question: How to get Windows Phone Unique Device Id?
- object uniqueId;
- DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId);
- var hexString = BitConverter.ToString((byte[])uniqueId).Replace("-", string.Empty);
Question: How to find how much space available and used in isolated storage?
- IsolatedStorageFile getIsoInfo = IsolatedStorageFile.GetUserStoreForApplication();
- long avilableBytes = getIsoInfo.AvailableFreeSpace;
- long usedBytes = getIsoInfo.Quota - getIsoInfo.AvailableFreeSpace;
Question: How to terminate the current Windows Phone app?
- Application.Current.Terminate();
Question: How to get the string from AppResources file in Windows Phone?
- string ApplicationTitle = AppResources.ApplicationTitle;
Question: How to prevent the app deployment in SD card?
- Open the WMAppManifest.xml file. This will open the WMAppManifest.xml in GUI designer.
- Navigate to the Packaging tab.
- Enable “Prevent deployment to SD cards” and save the project.
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:
- ?
- <App>
- <FunctionalCapabilities>
- <FunctionalCapability Name="ID_FUNCCAP_EXTEND_MEM"/>
- </FunctionalCapabilities>
- </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:
- ?
- <App>
- <Requirements>
- <Requirements Name="ID_REQ_MEMORY_300"/>
- </Requirements>
- </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?
- Touch.FrameReported += Touch_FrameReported;
- void Touch_FrameReported(object sender, TouchFrameEventArgs e)
- {
- TouchPoint touchPoint = e.GetTouchPoints(this.Content).FirstOrDefault();
- }
Question: How to Get the Windows Phone App version from WMAppManifest file ?
- string appVersionNumber = XDocument.Load("WMAppManifest.xml").Root.Element("App").Attribute("Version").Value;
Question: How to detect the audio endpoint device in Windows Phone App?
- AudioRoutingEndpoint currentEndpoint = AudioRoutingManager.GetDefault().GetAudioEndpoint();
Question: The AudioRoutingEndpoint is enum which contains one of the following values:
- public enum AudioRoutingEndpoint
- {
- Default = 0,
-
- Earpiece = 1,
-
- Speakerphone = 2,
-
- Bluetooth = 3,
-
- WiredHeadset = 4,
-
- WiredHeadsetSpeakerOnly = 5,
-
- BluetoothWithNoiseAndEchoCancellation = 6,
- }
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?
- List<string> IPaddressList = new List<string>();
- var Hosts = Windows.Networking.Connectivity.NetworkInformation.GetHostNames().ToList();
- foreach (var Host in Hosts)
- {
- string IP = Host.DisplayName;
- IPaddressList.Add(IP);
- }
Question: How to Get the Current Location in Windows Phone 8?
- Geolocator geoLocator = new Geolocator();
-
- Geoposition position = await geoLocator.GetGeopositionAsync();
-
- Geocoordinate coordinate = position.Coordinate;
-
- string Location = "Latitude = " + coordinate.Latitude + " Longitude = " + coordinate.Longitude;
Question: How to get the address of the location using latitude and longitude?
- WebClient client = new WebClient();
- client.DownloadStringCompleted += client_DownloadStringCompleted;
- string Url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=""123235.4""," + "7643643" + "&sensor=true";
- client.DownloadStringAsync(new System.Uri(Url, UriKind.RelativeOrAbsolute));
Question: How to retrieve the Remaining time and percentage of the Windows Phone 8 device battery?
- string remainingtime= Windows.Phone.Devices.Power.Battery.GetDefault().RemainingDischargeTime.TotalMinutes.ToString();
-
- 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?
- var toastPrompt = new ToastPrompt
- {
- Title = "Suresh M",
- TextOrientation = System.Windows.Controls.Orientation.Vertical,
- Message = "https://windowsapptutorials.wordpress.com/"
- };
- toastPrompt.Show();
Question: How to Vibrate the Windows Phone?
- VibrateController vibrate = VibrateController.Default;
- vibrate.Start(TimeSpan.FromMilliseconds(1000));
- How to Format the String in XAML TextBlock Control in Windows Phone?
- Text Formatting
- <TextBlock>
- <Run Text="String with 5 characters length: "/>
- <Run Text="{Binding Text, StringFormat=\{0\,5\} }"/>
- </TextBlock>
Number Formatting - <TextBlock>
- <Run Text="The number with 3 decimal point: "/>
- <Run Text="{Binding Number, StringFormat=\{0:n3\}}"/>
- </TextBlock>
Date Formatting - <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?
- Contacts cons = new Contacts();
-
-
- cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted_Many);
-
-
- cons.SearchAsync(String.Empty, FilterKind.None, "Contacts Test #3 Picture");
- void Contacts_SearchCompleted_Many(object sender, ContactsSearchEventArgs e)
- {
-
- }
Question: How to get all pictures from Camera Roll in Windows Phone?
- var mel = new MediaLibrary();
- var Pictures = mel.Pictures;
- PictureAlbumCollection picture = mel.RootPictureAlbum.Albums;
- PictureAlbum cameraRoll = picture.Where(album => album.Name == "Camera Roll").First();
- 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.