Developer's Academy: September 2014

Saturday, 6 September 2014

Basic Calculator WP 8.1 App

Developing Basic Calculator Using XAML & C#

This article is a basic WP 8.1 App development tutorial for beginners who do not have any prior experience with developing WP 8.1 applications. In this article, i will develop a basic Calculator application that performs addition, subtraction, multiplication and division of two numbers passed in text boxes and then displays the result in the same text box. 

Following are the steps to develop the application:

Step 1: Open Visual Studio 2013

Step 2: Click File --> New --> Project

Step 3: Under C# --> Store Apps --> Windows Phone Apps --> Blank App (Windows Phone)

Step 4: Rename the application to Simple_Calculator and click OK

Step 5: From the right pane, click on MainPage.xaml

At the moment, the contents of the MainPage.xaml file are as follows:



Step 6: From the right pane, click on MainPage.xaml.cs

At the moment, the contents of the MainPage.xaml.cs file are as follows:



Step 7: Changes in MainPage.xaml

1) First we will add a Grid and then define Row Definitions and Column Definitions. Code is given below:

<Grid>

  <Grid.RowDefinitions>
    <RowDefinition Height="130"></RowDefinition>
    <RowDefinition Height="100"></RowDefinition>
    <RowDefinition Height="100"></RowDefinition>
    <RowDefinition Height="100"></RowDefinition>
    <RowDefinition Height="100"></RowDefinition>
    <RowDefinition Height="100"></RowDefinition>
    </Grid.RowDefinitions>

  <Grid.ColumnDefinitions>
    <ColumnDefinition></ColumnDefinition>
    <ColumnDefinition></ColumnDefinition>
    <ColumnDefinition></ColumnDefinition>
    <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>

</Grid>

2) Then we will add a textbox:

<TextBox x:Name="TextBox1" 
                 Grid.Row="0"
                 Grid.ColumnSpan="4"
                 FontFamily="Lucida Sans Unicode" 
                 FontSize="60" 
                 FontWeight="Bold"
                 VerticalAlignment="Center" 
                 HorizontalAlignment="Right"
                 TextAlignment="Right"
                 Width="400" 
                 Height="110" />

3) After adding a textbox, we will add the buttons:

<Button Grid.Row="3"
                Grid.Column="0"
                Click="one_click" 
                Style="{StaticResource ButtonStyle1}">

            <TextBlock Text="1" />
</Button>

<Button Grid.Row="3"
                Grid.Column="1"
                Click="two_click" 
                Style="{StaticResource ButtonStyle1}">

            <TextBlock Text="2" />
</Button>

<Button Grid.Row="3"
                Grid.Column="2"
                Click="three_click" 
                Style="{StaticResource ButtonStyle1}">

            <TextBlock Text="3" />
</Button>

...... similarly we will all the buttons.

4) After adding buttons, we will apply styles to them by using the Setter Property:

<UserControl.Resources>
        <Style TargetType="Button">
            <Setter Property="Height" Value="110" />
            <Setter Property="Background" Value="#FF3A5AC9" />
            <Setter Property="VerticalAlignment" Value="Center" />
        </Style>
        
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="60" />
            <Setter Property="TextAlignment" Value="Center" />
            <Setter Property="FontWeight" Value="Bold" />
            <Setter Property="VerticalAlignment" Value="Bottom" />
        </Style>
</UserControl.Resources>

Step 8: Changes in MainPage.xaml.cs

Since we have created all the buttons, and their click events; now we will write C# code in those events.

First we will initialize some string, char and double objects:

string input = string.Empty;    // store user input
string op1 = string.Empty;      // store 1st operand
string op2 = string.Empty;      // store 2nd operand   
char operation;                 // character for operation
double result = 0.0;            // calculated result   

Now we will write code for the Add, Sub, Multiply and divide events:

private void Add_Click(object sender, RoutedEventArgs e)
        {
            op1 = input;
            operation = '+';
            input = string.Empty;
        }

private void Sub_Click(object sender, RoutedEventArgs e)
        {
            op1 = input;
            operation = '-';
            input = string.Empty;
        }

.... and so on.

For every numeric button event:

private void zero_click(object sender, RoutedEventArgs e)
        {
            this.TextBox1.Text = "";
            input += "0";
            this.TextBox1.Text += input;
        }

private void one_click(object sender, RoutedEventArgs e)
        {
            this.TextBox1.Text = "";
            input += "1";
            this.TextBox1.Text += input;
        }

.... and so on.

Code for equal_click button:

private void equal_click(object sender, RoutedEventArgs e)
        {
            op2 = input;
            double num1, num2;
            double.TryParse(op1, out num1);
            double.TryParse(op2, out num2);

            if (operation == '+')
            {
                result = num1 + num2;
                TextBox1.Text = result.ToString();
            }
            else if (operation == '-')
            {
                result = num1 - num2;
                TextBox1.Text = result.ToString();
            }
            else if (operation == '*')
            {
                result = num1 * num2;
                TextBox1.Text = result.ToString();
            }
            else if (operation == '/')
            {
                if (num2 != 0)
                {
                    result = num1 / num2;
                    TextBox1.Text = result.ToString();
                }
                else
                {
                    TextBox1.Text = "DIV/Zero!";
                }

            }
        }

Step 9: Run the program on WP 8.1 Emulator:




To download the complete project, click here !!

Tuesday, 2 September 2014

Understanding of Grids in XAML

Introduction

The grid is a layout panel that arranges its child controls in a tabular structure of rows and columns. Its functionality is similar to the HTML table but more flexible. A cell can contain multiple controls, they can span over multiple cells and even overlap themselves.

The resize behaviour of the controls is defined by the HorizontalAlignment and VerticalAlignment properties who define the anchors. The distance between the anchor and the grid line is specified by the margin of the control

Define Rows & Columns

The grid has one row and column by default. To create additional rows and columns, you have to add RowDefinition items to the RowDefinitions collection and ColumnDefinition items to the ColumnDefinitions collection. The following example shows a grid with three rows and two columns.

The size can be specified as an absolute amount of logical units, as a percentage value or automatically.

Fixed
         Fixed size of logical units (1/96 inch)
Auto
        Takes as much space as needed by the contained control
Star (*)
       Takes as much space as available (after filling all auto and fixed sized columns), proportionally divided over all star-sized columns. So 3*/5* means the same as 30*/50*.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="28" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="200" />
    </Grid.ColumnDefinitions>
</Grid>

Example: 3 * 3 Grid

<Grid>
  <Grid.Background>
  <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
    <GradientStop Color="Black" Offset="0"/>
    <GradientStop Color="#FFE42B2B" Offset="1"/>
  </LinearGradientBrush>
  </Grid.Background>
  
  <Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>

  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>

  <TextBlock>1</TextBlock>
  <TextBlock Grid.Column="1">2</TextBlock>
  <TextBlock Grid.Column="2">3</TextBlock>
  <TextBlock Grid.Row="1">4</TextBlock>
  <TextBlock Grid.Row="1" Grid.Column="1">5</TextBlock>
  <TextBlock Grid.Row="1" Grid.Column="2">6</TextBlock>
  <TextBlock Grid.Row="2">7</TextBlock>
  <TextBlock Grid.Row="2" Grid.Column="1">8</TextBlock>
  <TextBlock Grid.Row="2" Grid.Column="2">9</TextBlock>
</Grid>

... and the result is a simple grid with a number in each "cell":



The other thing I want you to notice about this example is that when you don't specify a Grid.Row or Grid.Column, it is assumed to mean the first row (row 0) or first column (column 0). Relying on the defaults keeps your code more concise.

Grid Cell Alignments & Margins

Another example app called AlignmentAndMargins. This XAML:

<Grid>
  <Rectangle Fill="Red"
             Height="100"
             Width="100"
             HorizontalAlignment="Left"
             VerticalAlignment="Top" />

  <Rectangle Fill="Blue"
             Height="100"
             Width="100"
             HorizontalAlignment="Right"
             VerticalAlignment="Bottom" />

  <Rectangle Fill="Green"
             Height="100"
             Width="100"
             HorizontalAlignment="Center"
             VerticalAlignment="Center" />

  <Rectangle Fill="Yellow"
             Height="100"
             Width="100"
             HorizontalAlignment="Left"
             VerticalAlignment="Top"
             Margin="100,100" />

  <Rectangle Fill="White"
             Height="100"
             Width="100"
             HorizontalAlignment="Left"
             VerticalAlignment="Bottom"
             Margin="50,0,0,50" />
</Grid>

Produces this result:


Understanding Default Properties in XAML

Since XAML is essentially an XML document, we can embed elements inside of other elements.

For Example:

<Page>
   <Grid ...>
      <Button ... />
      <TextBlock … />
   </Grid>
</Page>

Here Page "contains" a Grid and the Grid "contains" a Button and a TextBlock. Or, perhaps more correctly in XAML parlance, that Page’s Content property is set to Grid, and Grid's Children collection includes the Button and TextBlock. Depending on the type of control you're working with, the default property can be populated using this embedded style syntax. 

So, you could do this:

<TextBlock Content="Click Me" ... />

... or this ...

<Button HorizontalAlignment="Left"
        Margin="246,102,0,0"
        VerticalAlignment="Top"> Hi
</Button>


In simple words the default property of a XAML element is the property that we can simply put "between the tags" without any specific references.

Relationship Between .XAML and .XAML.CS Files

In Visual Studio’s Solution Designer, you can see that the XAML files have an arrow which means that we can expand them to reveal a C# file by the same name, the only difference is that it has a .cs file name extension appended to the end. If you look at the .cs version of the file, you’ll see that it defines a MainPage class, and furthermore, it defines it as a PARTIAL class.

       public sealed partial class MainPage : Page

The other half of the equation is defined in lines 1 & 2 of the MainPage.xaml:

<Page
        x:Class="HelloWorld.MainPage"
        ...

While it doesn't use the term Partial like its procedural counterpart, it does indicated the relationship between the two.

Why is this Important? 

This relationship means that the compiler will combine the output of the MainPage.xaml and the MainPage.xaml.cs files into a SINGLE CLASS. This means that they are two parts of a whole. That’s an important concept … that the XAML gets compiled into Intermediate Language just like the C# gets compiled into Intermediate Language and they are both partial implementations of a single class. This allows you to create an instance of a class in one file then use it in the other file. This is what allows me to create an instance of the Button class called clickMeButton in XAML and then call its methods or set its properties in C#.

Introduction to XAML

XAML - Basics

XAML is a little bit similar to the very popular markup language HTML. XAML is nothing but the EXtensible Markup Language XML. XML is also similar to HTML since both markup languages share some base common properties and tags. 



XAML is really just XML, the eXtensible Markup Language. At a higher level, XML looks like HTML insomuch that they share a common ancestry.

Whereas HTML is specific to structuring a web page document, XML is more generic. By "generic" I mean that you can use it for any purpose you devise and you can define the names of the elements and attributes to suit your needs.

In the past, developers have used XML for things like storing application settings, or using it as a means of transferring data between two systems that were never meant to work together. To use XML, you define a schema, which declares the proper names of elements and their attributes.

A schema is like a contract. Everyone agrees — both the producer of the XML and the consumer of the XML to write and read XML to conform to those rules, they’ll abide by that contract. Now, they can communicate with each other. So, a schema is an important part of XML. 

Example

This example presents how XAML looks and works.

<Button Name=”PlayAudioButton”
                          Width=”100”
                          Height=”70”
                          HorizontalAlignment =”Left”
                          VerticalAlignment =”Top”
                          Background = ”Green” 
                          Click =”PlayAudioButton_Click”> Play
</Button>


Monday, 1 September 2014

Famous Hello World App !!

Step: 1 Create a new Project

1. Launch Visual Studio 2013

2. Select File > New Project

3. In the left pane, expand Installed > Templates, then expand Visual C# and pick the Windows Store template type. The dialog's centre pane displays a list of project templates for Windows Store apps.




4. In the centre pane, select the Blank App (Windows Phone Silverlight) template.

5. In the Name text box, enter "HelloWorld".

6. Click OK to create the project.

Visual Studio creates your project and displays it in the Solution Explorer.



Step: 2 Start the App

Run the Application using "Emulator 8.1 WVGA 4 inch 512MB"


At this point, you created a very simple app. If you want to see what it looks like, press F5 to build, deploy, and launch your app in debugging mode. A default splash screen appears first. The splash screen is defined by an image and a background color.



Step: 3 Modify start page

1. Double Click on App.Xaml from the right pane.

2. Remove the existing code and add the following lines of code:

<StackPanel Grid.Row="1">
  <TextBlock Text="What's your name?" FontSize="40"/>
    <StackPanel Orientation="Horizontal">
      <TextBox x:Name="nameInput" Width="300"/>
      <Button Content="Say &quot;Hello&quot;"/>
    </StackPanel>
  <TextBlock x:Name="greetingOutput"/>
</StackPanel>



Step: 4 Create an event handler

XAML elements can send messages when certain events occur. These event messages give you the opportunity to take some action in response to the event. You put your code to respond to the event in an event handler method. One of the most common events in many apps is a user clicking a Button.

Let's create an event handler for your button's Click event. The event handler will get the user's name from the nameInput TextBox control and use it to output a greeting to the greetingOutput TextBlock.

Add an Event Handler

1. In XAML or design view, select the "Say Hello" Button that you added to MainPage.xaml.

2. In the Properties Window, click the Events button.

3. Find the Click event at the top of the event list. In the text box for the event, type the name of the function that handles the Click event. For this example, type "Button_Click".


4. Press Enter. The event handler method is created and opened in the code editor so you can add code that's executed when the event occurs.

5. Add code to the event handler that you created in the code behind page. In the event handler, retrieve the user's name from the nameInput TextBox control and use it to create a greeting. Use the greetingOutput.

private void Button_Click(object sender, RoutedEventArgs e)
{
greetingOutput.Text = "Hello, " + nameInput.Text + "!";
}

6. Run the App on emulator.



Understanding Windows Phone 8.1 Application Lifecycle

Windows Phone apps moves between different application states:

  • Apps are launched from Start Screen icon, apps menu or from deep link.
  • User may close apps.
  • The OS will suspend your app if it loses focus.
  • Apps may be reactivated from a suspended state.



As you see in the above diagram, four events happens:
  • Launching Event
  • Deactivated Event
  • Activated Event
  • Closing Event


App Launching Event

The user taps a tile and starts the application. The application goes from the not running state to the launched state since it was started for the first time and the event handler Application_Launching is fired.

Code for this event is:


// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated

private void Application_Launching(object sender, LaunchingEventArgs e)
{
}

App Deactivated Event

At this point either you continue working with your app or move away from your app by pressing the Start button or by launching another application, the event handler Application_Deactivated is fired, here one more situation could exist when Application_Deactivated is fired, let's say a call comes when using an application. In these types of situations the application goes into a dormant state and the good thing about this state is your application will automatically resume at the page where it is deactivated.

Code for this event is:


// Code to execute when the application is deactivated 
// This code will not execute when the application is closing

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}

App Activated Event

When you return to your app and resume it from a Dormant state, the event handler Application_Activated is fired.

Code for this event is:


// Code to execute when the application is activated 
// This code will not execute when the application is first launched

private void Application_Activated(object sender, ActivatedEventArgs e)
{
}

App Closing Event

When the user navigates backwards past the first page of an app and when the application is ended the Application_Closing event handler method is called.

Code for this event is:


// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated

private void Application_Closing(object sender, ClosingEventArgs e)
{
}