Sunday, March 25, 2012

Windows Phone - Logger

Hello

Logging is very important for development and for production.

Logger

The logger i have found is NLog .

It can be downloaded here.

Adding to project

Next you need to add configuration file by Add->New Item and choosing "Empty NLog Configuration File" :


This will add a configuration file name NLog.config and a reference to NLog.dll.

Next  change  NLog.config properties "Copy to Output Directory" to "Copy always"



Logging API


Most important classes are Logger and LogManager.
Logger class represent the name of the logger and has methods for writing to the log.
LogManager create and manage the Logger instances.

You create log in the following way :
 Logger logger = LogManager.GetLogger("someLogName");

The following log level are supported :

  • Trace - relevant in general for development
  • Debug - not enabled for production
  • Info - information
  • Warn - Warning
  • Error - Errors
  • Fatal - Fatal Error

Writing to Log file :
logger.Log(LogLevel.Error, "Some Error - {0}",i);
LogLevel has all log level described above.

Supported Targets

  • Console
  • Memory - store trace in memory
  • MethodCall - call a user defined method
  • Network,NLogViewer,Chainsaw - Network using HTTP , HTTPS
  • WebService - using SOAP,POST
  • LogReciverService - use a WebService using WCF



Configuration file :
The are two important sections :

targets

  • Can have one of more target tag
  • possible target attributes :
  • name
  • xsi:type 


rules

  • Can have one of more logger tags
  • possible rule attributes :
  • name
  • minlevel
  • writeTo

for example


Here all loggers starting level Trace are written to Console.

Remark :

  • Set  EnableConsole=1  under  [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\XDE]  in case you want to use Console target (32 bit PC)


Sample source
NLog_NK.zip

This sample illustrate a usage of the logger with console target.
Add NLog.config as described before.
Click the button to produce log events


MainPage.xaml.cs
NLog.config


Run the application and click the button to produce




Sample source 

NLog_OutputWindow_NK.zip

This sample illustrate a usage of the logger with MethodCall target to write to the Output window.

Add NLog.config as described before.
Click the button to produce log events



MainPage.xaml.cs 



NLog.config


MyClass.cs
Run the application via the debugger, open the Output windows and click the button to produce :



Nathan

Tuesday, March 6, 2012

Windows Phone - Pivot and Panorama (15)

Hello

Hierarchy


Object

  • DependencyObject
  • UIElement
  • FrameworkElement
  • Control
  • ItemsControl 
  • TemplatedItemsControl
  • Panorama
  • Pivot



Pivot and Panorama :

  • Controls
  • Used in case you have to display info which is larger then the screen. 
  • Have a virtual space that is arranged horizontally and can be accessed by sweeping your fingers right or left across the screen
  • Have Title property and TitleTemplate
  • Defines SelectionChanged event and properties SelectedIndex , SelectedItem which relates to the item shown.
Pivot

  •  A collection of PivotItem objects.
  • Tapping on the next header navigate to it


Panorama



PivotItem and PanoramaItem

  • Have a content which is object , in particular other control.
  • Have a Header property and HeaderTemplate


PivotItem

  • Derived from ContentControl.


PanoramaItem 

  • Derived from ContentControl 




Source sample
PivitandPanorama_NK.zip


Add a new page and choose "Windows Phone Panorama Page"








Basically what you get is the following




I have changed it to make it more interesting - all PanoramaItems are images

PanoramaPage.xaml


Note that all three XAML representation of Image element are equivalence.
Remember that PanoramaIten derives from ContentControl so you can dismiss the Content tag

Run the application and click "Panorama Control" button to produce :


Now drag the image to the right to produce








Source sample

PivitandPanorama_NK.zip


Add a new page and choose "Windows Phone Pivot Page"




Basically what you get is the following






I will  change it as i did in the previous so you will notice the difference
PivotPage.xaml



Run the application and click "Pivot Control" button to produce :



Now drag the image to the right to produce


The feeling is very similar to the Panorama control. Panorama seems more smooth

Nathan

Monday, March 5, 2012

Windows Phone - Items Control (14)

Hello

ItemsControl is used to represent collection of objects.

ItemControl has the following hierarchy

Object

  • DependencyObject
  • UIElement
  • FrameworkElement
  • Control
  • ItemesControl
  • Selector
  • ListBox
  • ComboBox

  • TemplatedItemsControl
  • Panorama
  •  Pivot


Important properties of ItemControl



Source sample
ItemsControl_NK.zip


This sample uses two controls

Both control represent a list of sorted font files names which are entered via the code.

StaticItemsControl.xaml


StaticItemsControl.xaml.cs




Run the application and click the button "Static ItemsControl" to produce




Note that you can scroll the ListBox by pointing on it, click the mouse and drag it up or down, but not the ItemsControl, you need ScrollViewer for this.


Customize item display


We saw before  that DataTemplate can be used to render object which have no visual representation. Here i will show how each item in  a list of SolidColorBrush will be given a visual represntation of  :

  • TextBlock with Text as the ARGB of the brush color
  • Rectangle filled with the brush color

Source sample
ItemsControl_NK.zip


CustomizeItemDisplay.xaml



Run the application and click the button "Customize Item Display" to produce





ListBox Selection
ListBox derives from Selector which allows to select an object from a collection.

Selector has a property name SelectedIndex which is the index of the selected item or -1 if no item is selected. Item[SelectedIndex] is equal to the SelectedItem in case item was selected.
SelectedItem is backed by a dependency property so it can function as binding target.

SelectionChanged occurs when selection is changed.


Source sample
ItemsControl_NK.zip


This sample is built over the previous with one change - a TextBox was added . The TextBox Forground is binded to the ListBox.SelectedItem. The SelectedIndex is 0 to start with

Selection.xaml





Run the application and click the button "Selection" , select a color to produce :





Notice that change in the selected color cause a change in the text forground 

Binding to ItemSource

ItemSource :
  • A property of ItemControl
  • It is used to set the content of the ItemsControl
  • Type is IEnumerable

In case the collection is changing dynamically then the collection should implement INotifyCollectionChanged e.g. ObserveableCollection




Sample source
ItemsControl_NK.zip

The sample show a collection of person and allow adding person to the collection. The person added is updated on the GUI.

The implementation includes :

  • Resource name oPersons - ObservableCollection of CPerson
  • Resource  name textBoxStyle - style for TextBlock
  • Resource name textBlockDataTemplateName - DataTemplate for the person name
  • Resource name textBlockDataTemplateFamily - DataTemplate for the person family
  • oListBoxName - ListBox of person name
  • oListBoxFamily -   ListBox of family name
  • Add button - Add person name and family


Two binding here :

  • oPersons - source is binded to oListBox - target. Note that oPersons can not be target because it is not dependency object
  • ListBox item - source is binded to the TextBox - target 

ItemSource.xaml

Resources :
remark - due to some bug in VS2010 i had to use x:Key and not x:Name when i defined oPersons

ContentPanel :


Person.cs
Persons.cs

Remember the collection must be ObservableCollection to notify changes like adding item


Run the application and click the button "Selection" , select a color to produce :







Enter a name - Diego family Forlan and click Add to produce





Nathan



Wednesday, February 29, 2012

Windows Phone - Template (13)

Hello

Two types of templates :

  • DataTemplate - Render objects that have no visual representation
  • ControlTemplate - Customize visual appearance of controls


ContentControl , ContentTemplate and  DataTemplate
DataTemplate - Render objects that have no visual representation
ContentTemplate is the way to display Content.

Sample source
Templates_NK.zip

We have seen before (blog) how to set content for a button (ContentControl). Now i will use ContenetTemplate which is a property of ContentControl type DataTemplate.
Content is set to an object type CUser and it is the button DataContext i.e. Binding source. Given a source there is no need to define it for the two TextBlocks and only Path is left to be defined. for Binding.
The Button content is displayed by two TextBlocks as defined in ContentTemplate


Note that Path may be omitted from the Binding i.e


Run the application and click the "Data Template" button to produce :



ControlTemplate
ControlTemplate - customize visual appearance of controls

Every Control has a property name Template which is type ControlTemplate.
Template is common as part of Style.
Note that ControlTemplate changes the appearance of the control but not it's functionality.

Source sample
Templates_NK.zip

ControlTemplate.xaml

A button with ControlTemplate which includes Border andTextBlock



A button with ControlTemplate which includes Border andTextBlock using TemplateBinding
which means a binding between the ControlTemplate property and the templated control property. i.e. the boder BorderBrush property is binded to the Control BorderBrush, same goes for BorderThickness
Note that i used once TemplateBinding and once Binding with RelativeSource. However, they are equivalence.




Same as the first button but using style





Based on previous button but two changes :

  • Add corner to the Border
  • Add ContentPresenter and bind it to the Control Content so "Click Me" will appear. This solve the problem that the Content "Click Me" was not shown


Now i want to show the use of ControlTemplate and Style as resources so we can reuse them.

Three resources are defined :

  • templateButtonComplete - ControlTemplate for button with Border which defines BorderBrush,BorderThickness and CornerRadius and ContenetPresenter which is binded to it's control content
  • templateButtonBinded - similar to  templateButtonComplete but bind  BorderBrush and  BorderThickness to it's parent button. Is it possible to bind also CornerRadius ?
  • styleButton - style add property such as HorizontalAlignment,Margin and use templatedButtonBinded. Note that the style set BorderBrush and BorderThickness which will be used by the template binding properties


And the buttons use is really easy after the resources are defined :



Run the application and click the "Control Template" button to produce :



Visual State Manager
The VisualStateManager manages states and logic for transitioning between states of controls.
We can use the visual state manager to handle state transitions as part of the ControlTemplate

VisualStateManger has VisualStateGroups which is a collection of VisualStateGroup objects.
VisualStateGroup has two important properties :


VisualState :

  • Represent visual state of a control e.g. MouseOver
  • Has important property name storyboard which defines the apperance of the control in this state. storyboard is actually the control animation in this state

VisualTransition - represent the visual behavior when transition happens


Source sample
Templates_NK.zip



The sample has a button with ControlTemplate name templateButtonComplete. The template has Border and ContenentPresenter as before. However the template has VisualStateManger which define the behavior of pressing on the button.


VisualStateManager.xaml


Run the application and click the "Visual State Manager" to produce :





Click the button and hold it down, the color of it will change and after you release it will turn back to green.

Sharing Templates and Styles
We already know how to share Style and Template inside the same application. Now it's time to share them cross application.


MergedDictionaries
Basic idea is to put the resources e.g. Styles, Templates in a single xaml file and share this file between projects.

Source sample
Templates_NK.zip


The common resources are defined inside a xaml file called SharedResources.xaml


This file is referenced in App.xaml using MergedDictionaries property


The resources are consumed in TemplateStyleSharing.xaml


Run the application and click the "Template and Style Sharing" to produce :





Nathan

Sunday, February 26, 2012

Windows Phone Data Binding (12)

Hello

Suppose you have a Slider and you want a TextBlock to show it's value. You can implement a handler for ValueChanged event , get the value , convert to string, and set the TextBlock Text to this string.

The above is common in Silverlight, so common that it is given a special mechanism called data binding.

Data binding is actually a link between two properties, so when one property is changing also the other changes. It can also be bidirectional binding.

The binding mechanism use events internally for handling change of properties and it can be defined entirely in XAML.

Data binding is possible between two UIelements or between a UIElement an arbitrary data.



One Way Binding


Source sample
DataBinding_NK.zip


The sample implement a binding between a Slider and a TextBlock.
OneWayBinding.xaml



The central class here is Binding class.
Two important properties :

  • ElementName - name of binding source element
  • Path - path to the binding source


Note that you can write the TextBlock element in the following short cut


Actually Binding can be done also in the code behind instead of in the XAML. To show this i have added another TextBlock Name oTextBlock into the xaml


OneWayBinding.xaml


And added to Slider.xaml.cs a binding object





Run the Application and click "OneWay Binding" button , then move the slider to the right to produce





Source and target
The binding is between the properties Slider Value and TextBlock Text
The source property is oSlider.Value so ElementName is oSlider and Path is Value.
The target property is TextBlock.Text , so the Binding element is under TextBlock.Text. Binding is done on the target element




Target and mode
Target property must be backed up by dependency property (see blog) and it must also be a property of UIElement.

Binding has property name Mode which determines the direction of data flow in the binding. by default it's OneWay i.e. a change in source will be reflected in the target , but not vice verse.

Source sample
DataBinding_NK.zip
TwoWayBinding.xaml


Notice that Binding use TwoWay Mode i.e. change in source is reflected in target and vice verse.



Run the Application and click "TwoWay Binding" button , then move the slider to the right  or change the value in the TextBox to produce


Binding Converter
Binding has a property name Converter which is used to convert the data passed between source and target. For example we can use converter to make sure that the text block will be formatted e.g. no more then two digit after the floating point.

Converter is type IvalueConverter which has two methods :

  • Convert  - Convert data passed from source to target
  • ConverBack - Convert data passed from target to source

Source sample
DataBinding_NK.zip.
To illustrate this i will add a TextBox with converter.

Convertor.cs


Converter.xaml

A resource is defined type CConverter

The resource - oCConverter is used as converter

Run the Application and click "Converter" button , then move the slider to the right to produce :


Note that the last TextBox text reflect the converter action.

Remark - Binding has a property ConverterParameter which may used as parameter for the Converter. This parameter is the third argument of the methods of  IvalueConverter.

Source Definitions


The source can be defined in four ways

  • Binding.ElementName - Source is UIElement which is created on XAML
  • Binding. Source - Source is an object. Object is typcally created on ResourceDirectory and given a key
  • Binding. RelativeSource - Source is defined according to it's position relative to the target
  • DataContext - Source is defined using the DataContext property 


Binding.Source
Source is defined by using Source property of Binding.
Source is an object. Object is typically created on ResourceDirectory and given a key

Source sample
DataBinding_NK.zip
Binding is done between a source - object type CUser and target - TextBlock. To be more precise :

  • Source property Name of CUser is bind to the target Text property of a TextBlock which represent name
  • Source property Family of CUser is bind to the target Text property of a TextBlock which represent family

User.cs




BindingSource.xaml
A resource called oUser is defined with Name Nathan and Family Krasney.
Binding is performed on two TextBlocks using Source property of Binding.
A style name styleTextBlock is defined for TextBlock and used later by all TextBlocks



Run the Application and click "Binding.Source" button to produce :




Notification
Given the sample of Binding.xaml, what will happen if i will add a button which change the properties of oUser ? actually we would like the target TextBlocks to reflect the change but this will not happen. Note that oUser is type CUser which has no dependency properties so it has no notification mechanism regarding changes of it's properties values.


To overcome this that source object must implement the interface INotifyPropertyChanged

Source sample
DataBinding_NK.zip

UserNotify.cs
Notice the set - it updates the value  only in case it has changed and only in this situation it fires the PropertyChanged event. This event is handled by the binding client which update the TextBlocks Text property.


BindingSourceNotification.xaml
The file is very similar to BindingSource.xaml beside using CUserNotify instead of CUser and using the Toggle button


BindingSourceNotification.xaml.cs
Only interesting issue here is the Button handler

Run the Application and click "Binding.Source Notification" button and click the Toggle button to produce :

Click on the Toggle button cause a change in Name and Family via binding and notification,


DataContext
FrameworkElement has property name DataContext.
Binding source is defined using DataContext.
DataContext type is object
DataContext simplify individual binding in case of one common source by eliminating repetition .
DataContext is a concept which allows objects to inherits binding specification from their parents.


Source sample
DataBinding_NK.zip

The sample is actually the same as for Binding.Source beside the use of DataContext.

DataContext.xaml
Note that ContentPanel has DataContext  set to Binding object with oUser as Source. Now all children can inherit this source and Binding of the TextBlocks need only Path.


Run the Application and click "DataContext" button to produce :





RelativeSource
Source is defined according to it's position relative to the target. This is important for templates

Source sample
DataBinding_NK.zip

Source is the TexBlock.FontFamily
Target is the same TextBlock but property is Text.

RelativeSource.xaml
Self means the same element.

Run the Application and click "Binding.RelativeSource" button to produce :



Note that the FontFamily - "Portable User Interface" which is the TextBlock FontFamily appears as the TextBlock Text.






Nathan.