Google Windows App Development Tips:Top Basics for Beginners (C#-XAML) | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Friday, 11 July 2014

Windows App Development Tips:Top Basics for Beginners (C#-XAML)

This post is only for knowing about tips which is helpful in our daily development ,some times basic tips will be very silly,but if you don't know about them,then those makes may be one day or much time to learn them .And it is very very important thing is to knowing some useful tips ,which are helpful to boost up our development without wastage of our valuable time.I thought this post is going to much useful for blog visitors.So i just add the new tip when i got it in my development.Stay tuned up-coming tips by book mark this post. 

***************************************************************************************

54)Underline Text in WinRT & Silverlight Windowsphone

We can use same below code in both WinRT & Silverlight windows phone to underline textblock text in xaml:
  1. <TextBlock Foreground="Black" FontSize="25" >  
  2.                  <Underline>  
  3.                     <Run Text="SubramanyamRaju" />  
  4.                 </Underline>  
  5.    </TextBlock> 

Tips date:Jan 07,2016

53)Minimum Sizes of Buttons in Windows Phone Store 8.1

WindowsPhone  store 8.1:
Ordinary buttons can not be set smaller than 109px, if we want to set smaller width to button then we have to set 'MinWidth' instead of 'Width' property.
<Button Content="b1" MinWidth="52"/>  
Tips date:August 29,2015 
52)WP Silverlight vs Universal Apps : Check file exist in Local Storage C#

When we move from Silverlight to WinRT can feel some gaps, especially when trying to check if a file exists or not in the isolated / local storage.
WindowsPhone Silverlight:
  1. IsolatedStorageFile.FileExists("FileName");  
WindowsPhone Store(WinRT):
In WindowsPhone store 8.1 ,We will use the GetFileAsync function, this function returns the file data if it exists, throwing an exception if it does not exist.
  1. public  static  async Task < bool > FileExists ( this  StorageFolder folder, String filepath)    
  2. {    
  3.    
  4. #if WINDOWS_APP    
  5. return  await folder.TryGetItemAsync (filepath)! = null ;    
  6. #endif    
  7.    
  8. #if WINDOWS_PHONE_APP    
  9.      
  10. try    
  11. {    
  12. await folder.GetFileAsync (filepath);    
  13. return  true ;    
  14. }    
  15. catch  
  16. {    
  17. return  false ;    
  18. }    
  19. #endif    
  20. }    
Tips date: January 29,2015

51)WP8.0 vs WP8.1: Hide soft keyboard C#

WindowsPhone 8.0:
In WP8.0,you can easily hide the soft keyboard by focusing the other UI element.


  1. //To hide the soft keyboard,focus the current page  
  2.   this.Focus();  


WindowsPhone 8.1:

In WP8.1,Fortunately we have InputPane class which is available from 'Windows.UI.ViewManagement'.So InputPane class having two methods 'TryHide' & 'TryShow' for hiding as well as showing keyboard.

  1. //To hide keyboard  
  2. InputPane.GetForCurrentView().TryHide();  
  3.   
  4. //To show keyboard  
  5. InputPane.GetForCurrentView().TryShow();  
Tips date: January 27,2015

50)WindowsPhone 8: How to display the Application list of particular publisher name C#

With help of URI associations in Windows Phone 8 ,we can directly launch the WindowsPhone app store. To display the application list of given publisher name we need to write a small piece of code like below, 

Output:


Note: URI schemes are not supported in windowsphone 7 sdk

Tips date: December 24,2014

49)WindowsPhone: TextBox stretch to fill horizontal space in StackPanel

Some times when you place TextBox inside stackpanel,it may not fill available horizontal space .In this case we need to set HorizontalAlignment="Stretch".So the following code will be work for you.

  1. <StackPanel>  
  2. <TextBox HorizontalAlignment="Stretch" />  
  3. </StackPanel> 

Tips date: December 17,2014

48)WindowsPhone SilverLight: Limitation for Application Bar 

 1) We are limited to four application bar buttons.

 2) We are limited to five application bar menu items to prevent scrolling. 

 Tips date: December 1,2014

47)How to determine the mobile operator in Windows Phone 8.1

Previously  in WP8.0,To determine mobile operator we are using DeviceNetworkInformation.CellularMobileOperator.

WP8.0:
  1. string MobileOperatorName = DeviceNetworkInformation.CellularMobileOperator;  
 WP8.1:
  1. public void GetMobileOperatorName()  
  2.         {  
  3.             var result = NetworkInformation.GetConnectionProfiles();  
  4.             string CarrierName = "";  
  5.             foreach (var connectionProfile in result)  
  6.             {  
  7.                 if (connectionProfile.IsWwanConnectionProfile)  
  8.                 {  
  9.                     foreach (var networkName in connectionProfile.GetNetworkNames())  
  10.                     {  
  11.                         CarrierName = networkName;//Get mobile operator Name  
  12.                         break;  
  13.                     }  
  14.                 }  
  15.             }  
  16.         }  
Note: You must enabled your data connection.  
Tips date: November 28,2014

46)WindowsPhone: Removing default 'Tick' button in Coding4Fun MessagePrompt(C#)

By default MessagePrompt showing 'Tick' button like this

So we can remove it by using below code to add our custom buttons.

ObjMessagePrompt.ActionPopUpButtons.Clear();

Tips date: November 18,2014

45)WindowsPhone: Making listpicker in ExpansionMode with more than 5 items(C#)

By default for more than 5 items, ListPicker switches to full screen mode.But if you don't want full screen mode,then we need to set ItemCountThresholdProperty after 'InitializeComponent();' in c# like this

ListPickerDataSync.SetValue(Microsoft.Phone.Controls.ListPicker.ItemCountThresholdProperty, 10);

Note:ItemCountThresholdProperty will not work if you set it using xaml

Tips date: November 17,2014

44)App.xaml.cs: Null Exception was unhandled - IdleDetectionMode.Disabled in WindowsPhone

Some times in App.xaml.cs file ,we may get an exception like "Null Exception was unhandled" at line 
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;

So solutions are 

Solution1:

Clearing the \bin and \obj folders and then recompile ,it will resolve your issue.

Solution2:

By adding PhoneApplicationService = new PhoneApplicationService() on the line above code.

Tips date: November 03,2014

43)WindowsPhone:Difference between two dates c#

In windowsphone, especially in calender applications we may need to find difference between two dates like this
DateTime date1= DateTime.Now;
DateTime date2= DateTime.Now.AddDays(-1);
double diff = (date1 - date2).TotalDays;

Tips date: September 02,2014

42)WindowsPhone Disable the Screenshot Functionality c#

In Windows Phone 8.1, anyone can take a screenshot by pressing the power button and the volume-up key at the same time. A customer was concerned about privacy in their enterprise app and asked me if they could disable this functionality for Windows Phone 8.1 (both WinRT and Silverlight apps).

WindowsPhone 8.1:
public MainPage()
{
    this.InitializeComponent();
    
    if (this.CanSetScreenCaptureEnabled())
    {
        this.SetScreenCaptureEnabled(false);
    }
 
}
WindowsPhone store 8.1:
public MainPage()
{
    this.InitializeComponent();
 
    ApplicationView.GetForCurrentView().IsScreenCaptureEnabled = false; 
 
}

Tips date: August 14,2014

41)[Solution]WindowsPhone Facebook Integration Error:Oauthexception (#200) the user hasn't authorized the application to perform this action

Recently when i am trying to post message on facebook from my windowsphone app ,i got above error.I don't know "why it happened?" after doing lot of research i found the reason is my current facebook code is works fine for my previous "facebook apps" and not working for my newly created facebook app.Because now new facebook app approval is very strict and we need to submit all details of our app to facebook for approval and it will be take 7-14 days .Please read this from facebook developer site.
So my question is "Is it possible to share status on FB without waiting for approval process?".Yes its possible .Just i create the facebook app as previously .and changed permissions in my current code like this 

Please note here i changed only one permission "publish_stream" to "publish_actions".Because now ""publish_stream" permission is no longer available in new facebook version.
Note:I found now this tip is no longer working for another facebook username
Tips date: August 12,2014

40)WindowsPhone:"String" vs "string" in c#


This is the most confusing question.When i am using these ones in my development,i don't found any differences and both makes same results.But i have always question "is there really difference?" and answer is "Yes and NO" :) how it is joke? Lets see answer is

  • In technically no difference .Because 'string' is an alias for 'System.String'.But we must follow guidelines while using both.So the question is "when we need to use them?
  • I use string to declare types - variables, properties, return values and parameters. This is consistent with the use of other system types - int, bool, var etc (although Int32 and Boolean are also correct).
         string Name= "subbu";
  • I use String when using the static methods on the String class, like String.Split(),String.Format(), or String.IsNullOrEmpty(). I feel that this makes more sense because the methods belong to a class, and it is consistent with how I use other static methods.
        string greet = String.Format("My Name is {0}!", Name);
Tips date: August 11,2014

39)WindowsPhone xml parsing : Embedding html content inside of xml document c#:


In general xml-parser can try to parse all elements in the xml document.But its failure when we try to kept html content inside of xml doc's.like this

<xml>

<mydata><html><h1>SubramanyamRaju</h1></html></mydata>

</xml>

Because Html content tag includes ('<' &'/>') which treated as xml element and at this case xml parser is failed to parse.

To solve this we need to kept html content inside of CDATA like this

<![CDATA[..html content..]]>

Example:<xml>

<mydata><![CDATA[<html><h1>SubramanyamRaju</h1></html>]]></mydata>
</xml>
CDATA:Text inside a CDATA section will be ignored by the parser.
Tips date:August 8,2014

38)Windows Phone : "Deployment failed because an app with target platform Any CPU cannot be deployed to Device" Error

It is very regular development error,when we are trying to deploy and debug a Windows Phone  app from Visual Studio , and we ended up getting the following error.
“Deployment failed because an app with target platform Any CPU cannot be deployed to Device. If the target platform is win32/ x86, select an emulator. If the target platform is ARM, select Device.”
To resolve the error, following steps were followed.
1)Go to "Configuration Manager"
2)In the Configuration Manager screen, set the platform to ARM and then click close button.

3)Rebuild the application and run it. Now, the app should run without any error
Tips date:August 7,2014

37)WindowsPhone App Store: Allows only release build to submit app

When publishing the Windows Phone 8 App to the Windows Phone store, it is important to build the project in the release configuration mode.To change configuration from debug mode to release mode.Do like this and run your app once.Finally found your .xap in Bin\Release folder
Tips date:August 6,2014

36)Silverlight WindowsPhone vs Windows store Phone (W8/W8.1/WP8/WP8.1)


  • Windows Phone 7, Windows Phone 8 & Windows Phone 8.1 (Targeting Silverlight) uses Silverlight API's. And how Windows Phone 8 & Windows Phone 8.1 relate to Silverlight, well they use the Silverlight API's that are available for mobile application framework.
  • Windows 8 & Windows 8.1 both target WinRT API's. Currently Windows Phone 8.1 also support WinRT API's. So, if you want to create Windows 8.1 & Windows Phone 8.1 applications that you can do by creating a Universal application targeting both the platforms (They have convergence of 90%).
  • You can develop Windows 8, Windows 8.1, Windows Phone 7, Windows Phone 8 & Windows Phone 8.1 applications using C# & XAML.
Tips date:August 5,2014

35)WindowPhone :Pragmatically set TextBlock Foreground Color with color code(RGB) C#

We can set foreground color to windowsphone controls using "SolidColorBrush" class which is available from "System.Windows.Media" namespace like this

C#
textblockobj.Foreground = new SolidColorBrush(Color.FromArgb(100, 255, 125, 35)); 
Here a:100,r:255,g:125,b:35
Tips date:August 4,2014
34)WindowPhone :Maximum allowed .XAP & .AppX File size in Windows Phone Store

I hope You already known about like windowsphone 8.0 ,now no .XAP files in windowsphone stroe 8.1 build file,so wp8.1 store build file having only AppX package and not Xap.In windowsphone 8.0 manifest file name is "WMAppManifest.xml",but in windowsphone store 8.1 it is renamed to "package.appxmanifest" file .And you may read more here.

WindowsPhone 8.0:
The maximum size of the XAP package file is 1 GB.
Windowsphone store 8.1:
The maximum allowed size of an AppX package or bundle is 4 GB.

Read more at Installation package max size: Tips date:June 21,2014

34)WP8.0 vs WP8.1 :How to make a function to wait for a specific time C#

Some times we may need to make execute a function after a specific time.However in windowsphone 8 "Thread.Sleep()" method used to make a function to wait for specific time,but it is no longer available in windowsphone store 8.1 hence alternative is "Tasks.Task.Delay()" method.And both method takes timespan as parameter to be wait for specific time.

WindowsPhone 8.0:
TimeSpan time = TimeSpan.FromMilliseconds(1000);
System.Threading.Thread.Sleep(time); //halts execution for 1000 milliseconds
WindowsPhone store 8.1:
async void DelayMethod()
        {
            TimeSpan time = TimeSpan.FromMilliseconds(1000);
            await System.Threading.Tasks.Task.Delay(time);//halts execution for 1000 milliseconds
        }

Tips date:June 18,2014

33)Windows Phone:Supported Image formats

In windowsphone Image control supports JPG/JPEG and PNG file formats.But directly Gif image file doesn't supported.if you  want to work with Gif ,you must read this post in my blog.

Tips date:June 17,2014

32)Windows Phone: ActualHeight and ActualWidth of control is always zero that is set as Auto 

When you didn't measure the control width and height ,then you may get ActualHeight & ActualWidth value's zero if you are trying these values in earlier of "InitializeComponent()" statement. Because of page hasn't actually been drawn yet.So if you want to looking for control actual width & height values ,you should wait until page has been loaded that is "Loaded" event fire.
XAML

<StackPanel Background="Red" Height="auto" Name="ParentStack"      <TextBox Text="Subramanyamraju windowsphone tutorials" TextWrapping="Wrap" AcceptsReturn="True"></TextBox> 
</StackPanel>

Here stack panel (i.e,ParentStack) doesn't measured with height and width.But actually its child item TextBox having two lines of text, so indirectly stack panel having some height and width values to fill child item content .When i tried to get those values in constructor its actualwidth and actualheight always returns zero,but in Loaded event i get correct actual width and height values because of page has fully drawn.
C#

public Page1() 
        { 
            InitializeComponent(); 
            string width=ParentStack.ActualWidth.ToString();//Resulted width 0.0 
            string height = ParentStack.ActualHeight.ToString();//Resulted height 0.0 
            this.Loaded+=Page1_Loaded; 
         } 
private void Page1_Loaded(object sender, RoutedEventArgs e) 
        { 
            string width = ParentStack.ActualWidth.ToString();//Resulted width 456.0 
            string height = ParentStack.ActualHeight.ToString();//Resulted height 106.0 
        }
Tips date:June 16,2014

31)WP8.0 vs WP8.1:Set focus to TextBox C#

In wp8.0 we just need to call Focus() method,but in wp8.1 we need to pass "FocusState.Programmatic" as parameter to Focus().
WindowsPhone 8.0:
TextBoxName.Focus();

WindowsPhone store 8.1:
TextBoxName.Focus(Windows.UI.Xaml.FocusState.Programmatic); 

Read more at:Focus Control in wp8.1-Tips date:June 14,2014

30)WP8.0 vs WP8.1:Make a phone call C#

WindowsPhone 8.0:
PhoneCallTask phoneCallTask = new PhoneCallTask();
phoneCallTask.PhoneNumber = "1234567891";
phoneCallTask.DisplayName = "Subbu8.0";
phoneCallTask.Show(); 

WindowsPhone store 8.1:
Windows.ApplicationModel.Calls.PhoneCallManager.ShowPhoneCallUI("1234567891", "subbu8.1"); 
Read more at:Launchers and Choosers WP8.1-Tips date:June 11,2014

29)Windows Phone 8.1:How to get screen resolutions

Previously in windowsphone 8.0,to determine screen resolutions we are using the "App.Current.Host.Content.ScaleFactor" .But now its not working in windowsphone 8.1,So this post is explained about what is the alternative way for detecting screen resolutions in windowsphone store 8.1.
var scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
string currentresolution = Window.Current.Bounds.Width * scaleFactor + "*" + Window.Current.Bounds.Height * scaleFactor;
MessageDialog messageDialog = new MessageDialog(currentresolution);
await messageDialog.ShowAsync();
Read more at: Screen Resolutions WP8.1-Tips date:July 10,2014

28)WP8.0 vs WP8.1:Enable Rating & Review screen option to our app C#

It is very very good idea to promote our app by providing rate and review option for our app users."MarketplaceReviewTask" is no longer available in windows phone store 8.1
WindowsPhone 8.0:
MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
marketplaceReviewTask.Show(); 
WindowsPhone store 8.1:
Launcher.LaunchUriAsync(new Uri("ms-windows-store:reviewapp?appid=" +PlaceYourAppIDHere));

For example:
Launcher.LaunchUriAsync(new Uri("ms-windows-store:reviewapp?appid=e498cf4c-d075-4fa9-8cad-44c15418f509"));




















Tips date:July 09,2014

27)WP8.0 vs WP8.1:MessageBox C#

In windows phone store 8.1 ,alternative for "MessageBox" is "MessageDialog"
WindowsPhone 8.0:
MessageBox.Show("Hi iam message to be display"); 
WindowsPhone store 8.1:
MessageDialog messageDialog = new MessageDialog("Hi iam message to be display");                                 await messageDialog.ShowAsync();
Read more at:MessageDialog -Tips date:July 08,2014

26)WP8.0 vs WP8.1:Page Navigation C#

There is a deference while navigating one page to another in WindowsPhone Silverlight &WindowsPhone store 
Ex:Here i am trying to navigate to "MainPage.xaml" page.
WindowsPhone 8.0:
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); 
WindowsPhone store 8.1:
Frame.Navigate(typeof(MainPage)); 
Read more at:Navigating between pages (XAML)-Tips date:July 07,2014

25)Windows Phone:Breaks the backwards compatibility tradition

Microsoft had always maintained backwards compatibility with most of their products.Compatibility has been one of the main reasons Windows has seen such great success,But unfortunate it wont work for windowsphone.I mean all higher version OS apps can't run on below versions. 

Ex:If you develop a app targeting Windows Phone 8.0 , then this will run on Windows Phone 8.1 device but if you are developing an app targeting Windows Phone 8.1 , then it will not run on Windows Phone 8 device.

Tips date:July 06,2014

24)Universal apps:Detect the Current device C#

So when you develop universal apps for windows&windowsphone,you may need to check which platform device is currently targeted to run the app.
#if WINDOWS_PHONE_APP
    // windowsphone 8.1
#elseif WINDOWS_APP
    // windows 8.1
#endif
Tips date:July 05,2014

23)Windows Phone Web Browser Launch c#

We can Launch URL in Web Browser using LaunchUriAsync in Windows Phone 8

Windows.System.Launcher.LaunchUriAsync(new Uri("https://bsubramanyamraju.blogspot.com"));
Read more at:URI Schems in WP8-Tips date:July 04,2014

22)Windows Phone Geolocator:Get current Location c#

Geolocator class is used to  get the current location
async private void GetCurrentLocation()
        {
            var geolocator = new Geolocator();

            Geoposition position = await geolocator.GetGeopositionAsync();

            Geocoordinate coordinate = position.Coordinate;

            MessageBox.Show("Latitude = " + coordinate.Latitude + " Longitude = " + coordinate.Longitude);
        }
Read more at:Geolocation-Tips date:July 03,2014

21)Windows Phone Maps application Launch c#

MapsTask launches the Maps application.And also you can provide a search string that is used to find and mark locations on the map.
MapsTask task = new MapsTask();
task.SearchTerm = "india";
task.Show();

Read more at:MapsTask-Tips date: July 02,2014

20)WindowsPhone Listbox: List item unresponsive on second click c#

You may faced this issue,because when you tap on particular list item it will be set as selected item for your listbox .So again when you tap on same item,it will never responsive with selected item object results until you selected another item and back to tap on it.So the solution is make clear the slection item after selection changed event fire.l

private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
       .
       .
        //Your working code when you click list item
       .
       .
      //Finally reset the selection
      (sender as ListBox).SelectedItem = null; 
}

Tips date:July 01,2014

19)Windows Phone:Back to previous page on Button click c#

So some times we may need to back to previous page with programming like this
private void BackButton_Click(object sender, RoutedEventArgs e)
  {
      if (NavigationService.CanGoBack)
        NavigationService.GoBack();
  }
Tips date:June 30,2014

18)Windows Phone BackKey handling with MessageBox Buttons Ok&Cancel:

It is most of cases,we need to handling back key with messagebox having 'ok' & 'cancel' button,if 'ok' button is pressed app will exit,and if 'cancel' button is pressed will stay on same page
 protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBoxResult.OK == MessageBox.Show("App will exit???", "Warning", MessageBoxButton.OKCancel))
            {
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
            base.OnBackKeyPress(e);
        }
Note:In Windows Phone 8, if you call Show in OnBackKeyPress(CancelEventArgs) or a handler for the BackKeyPress event, the app will exit.and you must read this link.




Tips date:June 29,2014

17)Windows Phone:Alternative methods for page navigations

We already know "NavigationService.Navigate" method is used to navigating one page to another.But have you ever tried these below two methods
Using Hyperlink button:

Xaml
<HyperlinkButton x:Name="HyperLnk" Content="GoToMainPage" NavigateUri="/MainPage.xaml"/>
C#
HyperlinkButton HyperLnk = new HyperlinkButton();
HyperLnk.Content = "GOToMainPage";
HyperLnk.NavigateUri = new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute);
ContentPanel.Children.Add(HyperLnk);
Here after clicking on hyperlink from your page will be redirect to "MainPage".

Using NavigationService Source Property:

C#
NavigationService.Source = (new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
Here NavigationService "Source" property used to Get/Set the URI of the page .By Setting this property, the Application Frame loads the specified page.

Tips date:June 28,2014

16)Windows Phone:Opening external links using HyperlinkControl XAML

Xaml
<HyperlinkButton x:Name="HyperLnk" Content="GoTo" TargetName="_blank" NavigateUri="http://www.bsubramanyamraju.blogspot.com"/>
Note:For wp8.0 you need to specify the TargetName to _blank for opening the external link or else you will receive the “NavigationFailed” error.And for wp store 8.1 no need to set it.

Tips date:June 27,2014

15)WindowsPhone :System.Windows.Markup.XamlParseException error?

Unfortunately it is difficult to find this kind of error ,because there's not enough information in the stack trace rather than It just tells you that something is going on at XAML load time.
Most of time this error occurred when you use the unknown resource your xaml page and these errors happen very early in the XAML booting process after InitializeCompoent() method is called.

1)it may be unknown resource key your referred in your xaml
2)You may be forgot to check corresponding permission to access the resources used by the application from AppManifest.xml page 

Example's:
1)If you are using maps in your xaml page,you should check ID_CAP_MAP in the capabilities tab from WMAppmanifest.xml file,otherwise you will get System.Windows.Markup.XamlParseException error.

2)Bad attribute value,for example Margin="12,17,0,28," see here extra "," at end,so it is also cause the above error.

Tips date:June 26,2014

14)Windows Phone 8 Build Action Types: Why you must set Image  "Build Action" to "Content" instead of the default "Resource"?

Generally there are two ways to include an image(other resource) in a Windows Phone project  : as build action "Content" or build action "Resource". So to set image build action ,Open solution explorer right click on your image file and choose properties then set 'Build Action' to 'Content' or 'Resource'.
Note:Make sure to always change this to "Content" in order to reduce the size of your DLL, speeding up both app load and image load.Because when adding new images to your project by default the  "Build Action" is set to "Resource" (under the Properties window)
Content:
If you set the build action to "Content", the image(Test.png) is not included in the DLL. And you should access it like

Xaml
 <Image Name="img" Source="/Image/Test.png"/>
C#
Uri uri = new Uri("/Image/Test.png", UriKind.Relative);  
BitmapImage imgSource = new BitmapImage(uri);
this.img.Source = imgSource; 
Resource:
If you set the build action to "Content" the image is embedded in the DLL.And you should access it like

Xaml
<Image Name="img" Source="Image/Test.png"/>
C#
Uri uri = new Uri("Image/Test.png", UriKind.Relative);  
BitmapImage imgSource = new BitmapImage(uri);
this.img.Source = imgSource; 
Read more at:Working with Resource Files-Tips date:June 25,2014

13)WindowsPhone UriKind:What is difference between Relative and Absolute?

Absolute:
Absolute URL contains all the information necessary to locate a resource.
Ex:http://www.xyz.com/images/img1.png
Relative:
A relative URL locates a resource using an absolute URL as a starting point. In effect, the "complete URL" of the target is specified by concatenating the absolute and relative URLs.So relative path for above example is images/imag1.png

Read more at:Absolute and Relative URLs-Tips date:June 24,2014

12)Windows Phone:Compare two Image Source's C#

When you comapre two image sources ,first you need to covert those to corresponding bitmap
if(image1.source.tostring()==image2.source.tostring()){} 
The above code is won't work,you should try like this
BitmapImage image1= new BitmapImage(new Uri("First image relative path", UriKind.Relative)) 
BitmapImage image2= new BitmapImage(new Uri("Second image relative path", UriKind.Relative)) 
if(image1==image2) 
{ 
  MessageBox.show("Image matched."); 
} 
else 
{ 
  MessageBox.Show("Not matched.");
} 
Tips date:June 23,2014

11)Be care about BitmapImage in windowphone C#

Be care about while working with bitmapimage,because default behavior of the Image control is to cache the image for future reuse. This means that the memory is still used by the control. You need to explicitly release the references to the image to free the memory
BitmapImage bitmapImage = myimage.Source as BitmapImage;
bitmapImage.UriSource = null;
myimage.Source = null;
Read more at:Image Tips for Windows Phone -Tips date:June 22,2014

10)WindowsPhone BitmapImage:Load an Image from a URL C#

Uri uri = new Uri("http://www.v3.co.uk/IMG/542/225542/fibre-broadband-image-540x334.jpg", UriKind.Absolute);
myimagecontrol.Source = new BitmapImage(uri);
Note:Here you must set UriKind to Absolute,otherwise you will get 'UriFormatException' error.
Tips date:June 21,2014

9)WindowsPhone:How do take Screenshot in device

It is very easy to take screenshot on device,

1. Hold the Power button and the Windows Key at a time.
2. This will take a screenshot on the Windows Phone 8 device which will be stored in the Screenshots album.



Tips date:June 20,2014

8)How to determine screen resolution on Windows Phone 8 C#

string ScreenScaleFactor = App.Current.Host.Content.ScaleFactor.ToString();
if (App.Current.Host.Content.ScaleFactor == 100)
{
    ScreenScaleFactor = "WVGA";
}
else if (App.Current.Host.Content.ScaleFactor == 160)
{
    ScreenScaleFactor = "WXGA";
}
else if (App.Current.Host.Content.ScaleFactor == 150)
{
    ScreenScaleFactor = "720p"; 
}
MessageBox.Show(ScreenScaleFactor);
Tips date:June 19,2014

7)WindowsPhone 8:Get device battery level C#

Windows Phone 8 provides the Windows.Phone.Devices.Power.Battery class which can be used to retrieve the battery information of the windows phone.
string batterlvel= Windows.Phone.Devices.Power.Battery.GetDefault().RemainingChargePercent.ToString();
MessageBox.Show(batterlvel);
Note:Here every unit is measured in the from of 100 nanoseconds
Read more at:Battery Class -Tips date:June 18,2014

6)WindowsPhone:Get Unique DeviceId C#

WindowsPhone 8:
var UniqueID = Windows.Phone.System.Analytics.HostInformation.PublisherHostId;
MessageBox.Show("" + UniqueID.ToString());
WindowsPhone 7: 
string UniqueID = "";
byte[] myDeviceID = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
UniqueID = Convert.ToBase64String(myDeviceID);
MessageBox.Show("" + UniqueID );
Note:Here you must enable "ID_CAP_IDENTIY_DEVICE" capability from manifest file,otherwise you will get "System.UnauthorizedAccessException" error
Tips date:June 17,2014

5)WindowsPhone:Detect OS version c#

string OSVersion = Environment.OSVersion.Version.ToString();
MessageBox.Show(OSVersion);

Tips date:June 16,2014

4)WindowsPhone Application/Global variable

We can set a variable that can be accessed on all pages of a Windows Phone App
Step1:
App.xaml.cs

public partial class App : Application
   {
        public string sName { get; set; }
   }
Step2:
Now access application variable "sName" in entire application like this

(App.Current as App).sName = "Test value";//set value                                                               string myvalue=(App.Current as App).sName;//get value


Tips date:June 15,2014

3)WindowsPhone:How to detect which button was clicked in code behind c#

This is the sceneria where multiple buttons having same click event,and so we need to find which button is clicked on code behind when "Click" is fired.For example here i taken 3 buttons b1,b2,b3 with same click event is "GetName_Click".

Xaml:

<Button Name="b1" Click="GetName_Click"/>
<Button Name="b2" Click="GetName_Click"/>
<Button Name="b3" Click="GetName_Click"/>
C#:
private void GetName_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            if(btn.Name=="b1")
            {
                //selected button name is 'b1'
            }
            if (btn.Name == "b2")
            {
                //selected button name is 'b2'
            }
            if (btn.Name == "b3")
            {
                //selected button name is 'b3'
            }
        }

Tips date:June 14,2014

2)WindowsPhone Styles:Get and apply Explicit style with c#

See in below there is explicit style name is "MyCustomStyle" for TextBlock,so you can get this style with c# and apply like this.
App.xaml
<Application.Resources>
        <Style x:Key="MyCustomStyle" TargetType="TextBlock">
            <Setter Property="FontSize" Value="8" />
        </Style>
</Application.Resources>
C#
Txtblk.Style = (Style)App.Current.Resources["MyCustomstyle"];

Tips date:June 13,2014

1)WindowsPhone Styles Xaml

Styles makes life easier ,you can reuse them within the entire Application.And it is very best practices styles can included in App.xaml page to available for entire application.

Implicit Style:

Here created style need not to have key identifier and you don't need to specify key identifier when you use this kind of style.

<Application.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="8" />
        </Style>
</Application.Resources>
Here you don't have to specify the style for the TextBlock , it will automatically pick the above style when you created TextBlock in your application.

Explicit Style:

Here created style must have key identifier and you must specify that key identifier when you use this kind of style.

For example , the developers can create a style for the textblock with a key identifier in the app.xaml file and then reuse them in different screens of the application.


<Application.Resources>
        <Style x:Key="MyCustomStyle" TargetType="TextBlock">
            <Setter Property="FontSize" Value="8" />
        </Style>
</Application.Resources>
The above style is for the textblock is given a name with the key attribute "x:Key="MyCustomStyle" . To refer to this style for a textblock , use the sample code for the textblock as shown below.
 <TextBlock Name="Txtblk" Style="{StaticResource MyCustomstyle}"/>
Tips date:June 12,2014

Note: This post is not a static,and it will be updated by new tips in futher,so it may be helpful for you if you bookmark this post and check daily.And in between you must read this WindowsPhone Basics.
Follow me always at  
Have a nice day by  :)

25 comments:

  1. Great post! Thank you.
    Can you add some tips about working with files (local storage, sd card, cloud)?

    ReplyDelete
    Replies
    1. Hi alex! recently i post article about SQlite,check this from link let me know your feedback

      Delete
    2. Yes Sub-bu i had Confusion diff between "String" vs "string" but now am clear the difference thanks for your Today's Tips

      Delete
  2. Hi Subbu how cani retrieve Imei or Uniqueno from wp 8.1 in c#
    I cant access many namespace in wp 8.1 for ex Deviceextendedproperties i cant access in wp8.1 ...pl help me

    ReplyDelete
  3. how to use a Serial port in wp 8.1 for tablet. Give me some sample code

    ReplyDelete
  4. Hello Subu, tell many more websites for Windows phone Apps. Before few months, I saw SoftMozer really! its amazing sites for windows phone apps free download. If you want to explore @http://softmozer.com/windows-phone/

    ReplyDelete
  5. Hi .I am facing serious crashing issue in my app .Most of the data i have to show in webbrowser control,but the serious crash occurs at three places where web browser loads dynamically,So when i navigate from one page to other web browser memory will not be clear it consumes almost 50 mb, and it remains it will not be cleared ,So what can i do to clear web browser memory

    ReplyDelete
    Replies
    1. Clear Web browser control cookies before the new page load .
      WindowsPhone 8.0:
      ObjwebBrowser.ClearCookiesAsync();

      WindowsPhone 7:
      CookieCollection cookies = webBrowserInstance.GetCookies();

      Loop through it and try discarding it

      foreach (Cookie cookie in cookies)
      {
      cookie.Discard = true;
      cookie.Expired = true;
      }

      Delete
    2. WindowsPhone 8.0:
      ObjwebBrowser.ClearCookiesAsync();

      yes placed this code but unable make the memory consumption decrease,I even made the browser null in On Navigatedfrom event,When I open the page where web browser to be loaded the memory raises from 30 to 90 mb and when I navigate to other page from web browsers page the memory not decreases it grows up it moves to 100 mb and so on

      Delete
  6. I use GetNetworkNames(), always get 0 count or exception: "the pipe is being closed";

    how can i solve the problem? thank you.

    ReplyDelete
  7. Want to learn C# from basics & in most professional Code development style. I'll have you writing real working applications in no time flat-before you reach the end of course.
    Hire C# Teacher.

    ReplyDelete
  8. Hello, I went through your blog on using the drawerlayout in windows phone using the GitHub Libarary. However I am looking to create the same programmatically within my app. Could you explain how can I do the same?

    ReplyDelete
  9. Hi Everyone,

    I am facing some Problems during my app development.that is Actually I want to get Application List which are installed in device along with data usage per App same as Microsoft Data Sense App.Please any one have Idea about this?
    Please Give some Suggestions on this Guys.

    Thank you in Advance.

    ReplyDelete
  10. Great post.
    I have a question.
    Is it possible to retrieve browser (IE) cookies in windows phone 10 (or 8.1) application? If yes, how?

    Please respond. Thanks in advance.
    Really appreciate any inputs.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. hey nice source for us and thanks for sharing the blog and coding with us and i read the blog and you have done a amazing that i have needed and again thanks for sharing this blog with us and i bookmark this blog for the future use.

    Windows Application Development Services

    ReplyDelete
  13. I have visited your post and found some information which is very important for me. So, please keep posting.
    magento development company | mobile apps development companies melbourne

    ReplyDelete
  14. Thanks for the great information on windows app. its very useful for me. great article !

    Windows Tips And Tricks


    ReplyDelete
  15. Thanks for sharing this blog with us...
    Hvantage Technologies offer best Mobile app development and Web Development Services with affordable price. If anyone is required for these services visit as: www.hvantagetechnologies.com

    ReplyDelete
  16. Great blog you have got here.. It’s hard to find excellent writing like yours these days.

    best web development services | top web development company

    ReplyDelete

Search Engine Submission - AddMe