Pages

Saturday 24 December 2011

Merry Christmas and Happy New Year

Monday 19 December 2011

Multi-Translator ver. 2.0

Multi-Translator 2.0 [Mango] has been released.


Wednesday 30 November 2011

How to scroll ListBox (ScrollViewer) to show an element without using BringIntoView method

This is a problem you can encounter in WPF and Silverlight. The usual solution presented in the Internet is to use BringIntoView() method. This approach works but does not guarantee that the whole element will be showed. The solution I want to show you is similar in both technologies and is more precise than BringIntoView() method. 

Let's assume that our UI contains a ListBox with a content

   1:  <ListBox x:Name="SomeItems">
   2:  <!--...-->
   3:  </ListBox>
   4:   


If we want to show a particular item contained in SomeItems ListBox we have to discover ScrollViewer which is a part of a ListBox visual tree and run ScrollToVerticalOffset method pointing to an index of an item we want to show. The following class can be used to find any DepenendecyObject in a visual tree.

   1:      public static class VisualHelper
   2:      {
   3:          public static T FindDependencyObject<T>(DependencyObject dependencyObject)
   4:      where T : DependencyObject
   5:          {
   6:              DependencyObject d = dependencyObject;
   7:              while (!(d is T) && VisualTreeHelper.GetChildrenCount(d) > 0)
   8:                  d = VisualTreeHelper.GetChild(d, 0);
   9:              return d as T;
  10:          }
  11:      }
  12:   

This is how you can use the code presented above

   1:  var scrollViewer = VisualHelper.FindDependencyObject<ScrollViewer>(SomeItems);
   2:  scrollViewer.ScrollToVerticalOffset([index of an item]);

Friday 4 November 2011

Multi-Translator

My first application has been released and is available on Windows Phone Marketplace

Wednesday 14 September 2011

Windows 8

Microsoft finally unveiled some additional details regarding new Windows 8. If you would like to watch the keynote session please have a look at http://www.buildwindows.com/.

Some key conclusions (for developers) from the keynote:
  • JavaScript is becoming a first-class language (you can find few proofs below)
  • Developers will receive VS2011 and Expression Blend 5 with arrival of Windows 8




I really like new Microsoft 'no compromises' approach which means that developers will be able to use new Windows 8 tablets for everything - the most important for coding.

Wednesday 7 September 2011

Key concepts in Silverlight in comparison with WPF

In this article I would like to show you how to use some of the key Silverlight features:
  • Dependency Properties,
  • Data Bindings,
  • Commands,
  • Implicit styles,
  • Explicit styles,
  • Visual State Manager,
  • Animations,
  • Value Converters,
  • CollectionViewSource,
  • Custom Controls.


1. Dependency Properties
If you want to understand the reason and the way how DP works please visit this link. I would like to mention differences between WPF and SL DPs. When you create DP in SL you can specify PropertyMetadata but as a result you will lack coercion and validation support which can be handled in FrameworkPropertyMetadata (WPF). These two can be useful especially if you want to create advanced controls. If you cannot imagine how coercion can be useful for you I can give an example - range IP address control.

   1:  public static readonly DependencyProperty RadiusProperty = DependencyProperty.Register("Radius", typeof(double), typeof(CelestialBodyControl), new PropertyMetadata(double.NaN));
   2:   
   3:          public double Radius
   4:          {
   5:              get { return (double)GetValue(RadiusProperty); }
   6:              set { SetValue(RadiusProperty, value); }
   7:          }

2. Data Bindings 
I describe data bindings as maximum functionality and minimum code, very useful for displaying and interacting with data. Bindings are even more useful when you use Model-View-ViewModel (MVVM) pattern because in case like that data bindings create these pipelines/streams of data between presentation layer (V) and logic behind it (VM) and no additional code is needed.

Example below shows how to use data bindings directly in your view (V)
   1:  <local:CelestialBodyControl BodyName="{Binding Name}" Radius="{Binding Radius}" AverageDistanceFromSun="{Binding AverageDistanceFromSun}" 
   2:                                                  RotationPeriod="{Binding RotationPeriod}" OrbitalPeriod="{Binding OrbitalPeriod}"/>

This example shows how to use a data binding inside a style
   1:  <TextBlock Text="{Binding Radius, RelativeSource={RelativeSource TemplatedParent}}" Foreground="White"/>

Tuesday 6 September 2011

How to list and activate services from command-line console

My colleague had this unusual problem with his computer (actually it was a virus) and he had no access to the Services console in Administrative Tools but at the same time he had to run a service. As a solution we decided to use a command-line console. Please have a look below to find out how you can do it.

To list all up and running services type: net start
To list all inactive services type: sc query type= service state= inactive
With the second command you can check the name of your inactive service and to make it running type: sc start [service name]

Thursday 18 August 2011

AddressAccessDeniedException HTTP could not register URL http://+:...

System.ServiceModel.AddressAccessDeniedException was unhandled
  Message=HTTP could not register URL http://+:xxxx/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).

This is a typical problem which you can encounter when you migrate/create a service on Vista or Windows 7 machine. The reason why you can see it is because your user/group does not have rights to create a service that listen on the portion of the namespace. To perform reservation on Windows Vista or Windows 7 you have to use netsh.exe application which is available directly from your command line:

netsh http add urlacl http://+:[port]/ user=[Domain\Username or Everyone]

Before you even start, remember to run your command line application as an administrator otherwise you will not be able to accomplish the procedure. If your case scenario is more specific/unusual go to Microsoft webpage where you can find more detailed information. If you want to list existing reservations use the following expression: netsh http show urlacl

Saturday 6 August 2011

Battlefield 3

Excellent, detailed presentation of BF3.

Tuesday 26 July 2011

Filtering in MVVM architecture - Silverlight & WPF

Before you start implementing functionality for filtering data in MVVM architecture you have to find out which technologies you are going to use. There are two different ways how you can implement filtering in WPF but only one solution can be ported to Silverlight. The reason behind it is that Silverlight version of CollectionViewSource class does not support GetDefaultView method. The following example shows how you can filter data in MVVM architecture by changing the content of FilteringMethod predicate.


   1:  class MainWindowPresentationModel : INotifyPropertyChanged
   2:      {
   3:          ObservableCollection<string> _observableCollection = new ObservableCollection<string>() { "a", "bb", "ccc", "dddd", "eeeee", "ffffff", "eeeeeeee", "fffffffffffffff", "gggggggggggggggggg" };
   4:          private int _threshold = 100;
   5:          private ICollectionView _Items;
   6:          private CollectionViewSource _CollectionViewSourceItems;
   7:          public event PropertyChangedEventHandler PropertyChanged;
   8:   
   9:          public MainWindowPresentationModel(Window window)
  10:          {
  11:              FilterCommand = new RoutedCommand();
  12:              CommandBinding customCommandBinding = new CommandBinding(FilterCommand, HandleFilterCommand);
  13:              window.CommandBindings.Add(customCommandBinding);
  14:   
  15:              window.DataContext = this;
  16:              window.Show();
  17:   
  18:              Items = CollectionViewSource.GetDefaultView(_observableCollection);
  19:              Items.Filter = FilteringMethod;
  20:              Items.Refresh();
  21:   
  22:              CollectionViewSourceItems = new CollectionViewSource();
  23:              CollectionViewSourceItems.Source = _observableCollection;
  24:              CollectionViewSourceItems.View.Filter = FilteringMethod;
  25:              CollectionViewSourceItems.View.Refresh();
  26:          }
  27:   
  28:          public ICommand FilterCommand
  29:          {
  30:              get;
  31:              set;
  32:          }
  33:   

Thursday 23 June 2011

How to make dynamically generated tiles in Windows Mobile 7?

This project was inspired by the way how menu in Portal 2 game works. Portal 2 is a first-person puzzle-platform video game developed by Valve Corporation. Really interesting and very well executed. Going back to the subject when I saw Portal 2 menu in action I decided to do something similar in WM7. The whole idea is quite simple:
  1. define your area of interest e.g. a whole screen or a part
  2. make a screenshot
  3. populate WrapPanel with rectangles which contain appropriate parts of the previously created screenshot.
  4. hide your area of interest (yourUIElement)
  5. start animations
  6. perform a transition if needed 

Points 1 and 2

   1:              WriteableBitmap bmp = new WriteableBitmap((int)LayoutRoot.ActualWidth, (int)LayoutRoot.ActualHeight);
   2:              bmp.Render(yourUIElement, null);
   3:              bmp.Invalidate();
   4:              image.Source = bmp;

Tuesday 22 February 2011

Kinect for Windows will be available this Spring - version for enthusiasts and academic researchers

I am really glad that Microsoft is going to release Windows version of Kinect this Spring. I cannot wait to put my hands on this amazing piece of hardware.

Another pretty amazing Kinect hack

Sunday 13 February 2011

How to make a fully animated ListBox in Windows Mobile 7

If you want to animate all ListBox items in a way similar to the WM7 embedded functionality please have a look at the following article.

Requirements: 
  • only items visible on the screen take part in an animation,
  • an animation kicks off when one of the the ListBox items is selected,
  • all items are animated apart from the one which is selected,
  • items are animated one by one from the bottom to the top of the screen,
  • when the animation is finished the application navigates to the another page. 

Solutions:
  1. If we want to detect visible ListBox items you need to get access to the ScrollViewer which is a part of a ListBox visual tree. To iterate through the visual tree we will be using the following method:
  2.    1:          private T FindDependencyObject<T>(DependencyObject dependencyObject)
       2:              where T : DependencyObject
       3:          {
       4:              DependencyObject d = dependencyObject;
       5:              while (!(d is T) && VisualTreeHelper.GetChildrenCount(d) > 0)
       6:                  d = VisualTreeHelper.GetChild(d, 0);
       7:              return d as T;
       8:          }
    ScrollViewer VerticalOffset and ViewportHeight properties tell us the index of the first visible item and how many items are visible altogether.
  3. Animations will be started when a ListBox triggers SelectionChanged event.
  4. All functionality responsible for running animations on per ListBox item basis will be nested in SelectionChanged event handler.
  5. Items will be animated one by one using Storyboards nested in DataTemplate resources. An animation of each item will be delayed with Storyboard BeginTime property which has to be populated in code based on an item position.
  6. The last animated item Completed event handler will be used to trigger NavigationService.Navigate(...) method.
Found problems:
When you run animations/storyboards in code you have to be aware of few pitfalls. It is not allowed to start an animations which has been started it means that you have to be aware of the animation state and stop it if necessary. In this particular case a user is able to change a selected item in the middle of the running animation  and this is the moment when we have to clean it up and start the whole process again.

Results:

Useful links:
  • https://www.silverlight.net/learn/quickstarts/animations/#advanced_animations
Source code: ListBoxAnimation.zip

Sunday 30 January 2011

Dependency Property

Definition:
Dependency property is a new type of property which can be used with dependency objects, to enable styling, data binding or animation. To define your own dependency property you have to register your new property using DependencyProperty.Register(...) method and optionally you can create FrameworkPropertyMetadata object where you can specify property characteristics.

Example:

   1:   public partial class MinMaxControl : Control
   2:      {
   3:          public static readonly DependencyProperty MinProperty = 
   4:              DependencyProperty.Register("Min", typeof(int), typeof(MinMaxControl),
   5:              new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 
   6:                  HandleMinValueChanged, CoerceMinValue), ValidateMinValue);
   7:          public static readonly DependencyProperty MaxProperty = 
   8:              DependencyProperty.Register("Max", typeof(int), typeof(MinMaxControl),
   9:              new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
  10:                  HandleMaxValueChanged, CoerceMaxValue), ValidateMaxValue);
  11:   
  12:          static MinMaxControl()
  13:          {
  14:              DefaultStyleKeyProperty.OverrideMetadata(typeof(MinMaxControl), new FrameworkPropertyMetadata(typeof(MinMaxControl)));
  15:          }
  16:   
  17:          public int Min
  18:          {
  19:              get { return (int)GetValue(MinMaxControl.MinProperty); }
  20:              set { SetValue(MinMaxControl.MinProperty, value); }
  21:          }
  22:   
  23:          public int Max
  24:          {
  25:              get { return (int)GetValue(MinMaxControl.MaxProperty); }
  26:              set { SetValue(MinMaxControl.MaxProperty, value); }
  27:          }
  28:   

How to calculate coordinates of a control in WPF

If you have a control nested in another control and you have to calculate their coordinates, you can achieve it using TranslatePoint(..,..) method e.g. [your control].TranslatePoint(new Point(0, 0), [parent control]); If you need to retrieve a control coordinates to make it visible on the screen you can consider BringIntoView() method. The only problem with previously mentioned method is lack of consistency but on the other hand you do not have to perform any additional calculations.

Please have a look at the following example if you want to see TranslatePoint and BringIntoView methods in action: Coordinates.zip

Saturday 8 January 2011

How to restyle WPF controls

If you have to restyle some controls and you do not have a designer on-board there are some tools you can use or places you can check to find/gather some answers and inspirations. If you have Expression Blend you do not have to search for additional tools or help. Whatever you need to do it can be achieved with this tool. There are still some other solutions. You can use Microsoft's style examples which you can grab from Styling & Templating webpage or directly from this link ControlTemplateExamples.zip. If you are not satisfied with this approach you can go for Kaxaml which contains style snippets and can be used as a start point of your restyling process.

Expression Blend

Microsoft's examples 


Kaxaml