by Nico
As I was working on a Windows Phone 8 project I needed a pivot that could hide its title, giving back some screen real-estate when needed. The basic pivot that is included in the Windows Phone SDK doesn’t have this kind of behavior so it was a great opportunity to try out custom controls in Windows Phone. I’ve build custom controls in XAML before but never based on an existing one, so fun times ahead. Let me start by showing a side-by-side comparison between both views of my pivot.  don’t mind the overlapping textblock and button, point is that when the button is clicked, the title of the pivot disappears. Building a XAML custom control It’s quite easy to build a custom control in XAML as long as you follow the guidelines. It requires you to add a folder called Themes and in the folder a file called generic.xaml. The generic.xaml file is a resource dictionary, no code behind file is needed. Do follow the naming conventions exactly or your control won’t work. Next step is adding a class that inherits from ContentControl (or a control that already inherits from ContentControl). The project for my ExtendedPivot looks like this  The project type is a WP8 class library containing two custom controls, one for the pivot and one for the pivot items. Extending the pivot Since I only want to add a functionality to an existing control, the Pivot, my ExtendedPivot class inherits from Pivot instead of CustomControl. Code Snippet - public class ExtendedPivot : Pivot
- {
- public static readonly DependencyProperty HeaderVisibilityProperty =
- DependencyProperty.Register("HeaderVisibilityProperty", typeof (Visibility), typeof (ExtendedPivot), new PropertyMetadata(null));
-
- public Visibility HeaderVisibility
- {
- get { return (Visibility)GetValue(HeaderVisibilityProperty); }
- set { SetValue(HeaderVisibilityProperty, value); }
- }
-
- public ExtendedPivot()
- {
- DefaultStyleKey = typeof(ExtendedPivot);
- }
- }
We’ll start with the constructor, Line 14 is necessary when developing a custom control, it sets the style of the control to the style defined in generic.xaml (we’ll get to that style in a minute). Lines 6 – 10 are a property that will be used by the DependencyProperty. The DependencyProperty (lines 3-4) is a property that we can bind a value to when using the control in a project, it might seem a bit overwhelming at first but there’s a great snippet in VS2012 to easily write them. Basically, the parameters for the Register function are a name, the type of the property, the owner type (type of the control where you’re declaring the DP) and some metadata. The get and set method of the normal property use the DP to get and set values through databinding. generic.xaml This is the style for the ExtendedPivot as declared in generic.xaml Code Snippet - <Style TargetType="local:ExtendedPivot">
- <Setter Property="Margin" Value="0" />
- <Setter Property="Padding" Value="0" />
- <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}" />
- <Setter Property="Background" Value="Transparent" />
- <Setter Property="ItemsPanel">
- <Setter.Value>
- <ItemsPanelTemplate>
- <Grid />
- </ItemsPanelTemplate>
- </Setter.Value>
- </Setter>
- <Setter Property="Template">
- <Setter.Value>
- <ControlTemplate TargetType="local:ExtendedPivot">
- <Grid HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto" />
- <RowDefinition Height="Auto" />
- <RowDefinition Height="*" />
- </Grid.RowDefinitions>
- <Grid Grid.RowSpan="3" Background="{TemplateBinding Background}" />
- <ContentControl Grid.Row="0"
- Margin="24,17,0,-7"
- HorizontalAlignment="Left"
- Content="{TemplateBinding Title}"
- ContentTemplate="{TemplateBinding TitleTemplate}"
- Visibility="{TemplateBinding HeaderVisibility}" />
- <primitives:PivotHeadersControl x:Name="HeadersListElement" Grid.Row="1" />
- <ItemsPresenter x:Name="PivotItemPresenter"
- Grid.Row="2"
- Margin="{TemplateBinding Padding}" />
- </Grid>
- </ControlTemplate>
- </Setter.Value>
- </Setter>
- </Style>
Basically, I’ve created a xaml page in some very basic Windows Phone project, right-clicked it, selected Edit Template > Edit a copy. This gives you a copy of the template for the Pivot. I copied that template in the generic.xaml style. The ContentControl at Lines 23-28 show the title in the pivot. I added the Visiblity property here and bound it to the HeaderVisibility property in the ExtendedPivot class. To bind a property in a style you need to use the TemplateBinding keyword instead of the normal Binding one. Don’t forget to set TargetType to the type of your custom control. Using the custom control in an app The control is ready, now it’s time to use it. Create a new Windows Phone app and reference the project or DLL of the custom control. This is the MainPage of the sample app. Code Snippet - <phone:PhoneApplicationPage x:Class="ExtendedPivot.MainPage"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:control="clr-namespace:ExtendedPivot.Control;assembly=ExtendedPivot.Control"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
- xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
- FontFamily="{StaticResource PhoneFontFamilyNormal}"
- FontSize="{StaticResource PhoneFontSizeNormal}"
- Foreground="{StaticResource PhoneForegroundBrush}"
- Orientation="Portrait"
- SupportedOrientations="Portrait"
- shell:SystemTray.IsVisible="True"
- mc:Ignorable="d">
-
- <!-- LayoutRoot is the root grid where all page content is placed -->
- <Grid x:Name="LayoutRoot" Background="Transparent">
- <!-- Pivot Control -->
- <control:ExtendedPivot HeaderVisibility="{Binding Visibility}" Title="MY APPLICATION">
- <control:ExtendedPivotItem Header="item 1">
- <Grid>
- <TextBlock Text="item1" />
- <Button Click="ButtonBase_OnClick" Content="button" />
- </Grid>
- </control:ExtendedPivotItem>
-
- <control:ExtendedPivotItem Header="item 2">
- <TextBlock Text="item2" />
- </control:ExtendedPivotItem>
- </control:ExtendedPivot>
- </Grid>
- </phone:PhoneApplicationPage>
Line 4 defines the namespace that holds the ExtendedPivot. Line 20 puts the control on the actual page. Notice that we bind the HeaderVisibility property of our control. I defined the datacontext of this page in code behind to be of type MainViewModel. MainViewModel implements INotifyPropertyChanged and only holds one property of type Visibility, that property is bound to the ExtendedPivot’s HeaderVisibility. The Button in the pivot will switch the HeaderVisibility between Collapsed and Visible, this happens in the code behind of this page. Code Snippet - public partial class MainPage : PhoneApplicationPage
- {
- private MainViewModel _mainViewModel;
-
- // Constructor
- public MainPage()
- {
- InitializeComponent();
-
- _mainViewModel = new MainViewModel();
-
- DataContext = _mainViewModel;
- }
-
- private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
- {
- if (_mainViewModel.Visibility == Visibility.Collapsed)
- {
- _mainViewModel.Visibility = Visibility.Visible;
- }
- else
- {
- _mainViewModel.Visibility = Visibility.Collapsed;
- }
- }
- }
Not really the best way of writing a Windows Phone app but it’s just for making the point  Conclusion Extending a Windows Phone control isn’t hard as long as you follow the naming conventions, adding some extra functionality is as easy as copying the xaml template and adding some dependency properties. The sample code can be found on my SkyDrive
by Nico
Ever since I started playing with XAML based technologies (which actually isn’t that long ago) I’ve been looking into the MVVM (Model – View – ViewModel) pattern. I stumbled across MVVM Light pretty soon and liked the way it worked. Turns out I’m not the only one that likes it, there’s a whole set of developers, both hobby and professional, that really love this set of libraries. MVVM Light is, according to the author, not a framework but a set of libraries that take care of the plumbing to set up an MVVM structure and provide some extra helper classes to make life easier.
MVVM Light has changed a lot in its history, some elements were dragged out, others dragged in. Fact remains that it’s a fast, easy to use and lightweight framework. The author, Laurent Bugnion, does a great job of listening to the people that use MVVM Light, incorporating requested features and helping developers out. While talking to some of my fellow developers I’ve noticed a few times that there are certain elements of MVVM Light that others hadn’t heard of, and the same goes in the other direction. I’ve learned a lot of new things about MVVM Light just from talking with other users. Thinking about that gave me the idea of this blogpost and since those “10 things about…” posts seem to be popular, this was my chance. So here are my top 10 hidden gems of MVVM Light that you might have missed.
1. The MVVM Light installer
This one might seem a bit obvious, but in this NuGet driven world we would forget the added benefit of an installer. MVVM Light has an MSI installer that not only installs the binaries on your drive but it also provides project and itemtemplates in Visual Studio, along with a list of snippets. In case the Visual Studio 2012 update 2 removed your templates, reinstall the VSIX from C:\Program Files (x86)\Laurent Bugnion (GalaSoft)\Mvvm Light Toolkit\Vsix that should put the project templates back in place.

2. Constructor injection
This one is just awesome, and is actually a feature that can be found in most DI frameworks. MVVM Light uses SimpleIoc to register viewmodels and service classes at application launch (or during the app lifetime). Constructor injection means that you can specify a parameter in a class his constructor. When that class gets instantiated SimpleIoc will try to find a registered class of the same type as the parameter, when it finds one, that instance will get injected as the parameter of the constructor. Here’s an example, let’s say that in the ViewModelLocator, we register a navigation service.
Code Snippet
- SimpleIoc.Default.Register<INavigationService, NavigationService>();
We state here that we want to register an INavigationService in the IOC container, when it creates the instance we want it to be of type NavigationService. This “record” in the IOC container doesn’t have an instance yet, it gets instantiated when we fetch it from the container the first time. There are some occasions where you would want to create an instance of a class immediately when it gets registered. the Register<T> function of SimpleIoc has an overload to do just that.
Code Snippet
- SimpleIoc.Default.Register<INavigationService, NavigationService>(true);
Just pass in true as a parameter and it will create an instance right there and then.
Now we want to use the NavigationService in the MainViewModel.
Code Snippet
- ///<summary>
- /// Initializes a new instance of the MainViewModel class.
- ///</summary>
- public MainViewModel(INavigationService navigationService)
- {
-
- }
SimpleIoc will search for a registered class of type INavigationService and will inject it in this constructor. This saves us the hassle of manually contacting the IOC container and requesting the correct instance.
WARNING: do be careful with this, the order in which you register your classes with the IOC container can be important, especially when using the overload to create instances. If I would create the MainViewModel before the NavigationService is registered I would get a nullreference exception. So be aware of that.
3. SimpleIoc to simple? replace it!
The SimpleIoc library works great and is a cool, lightweight addition to MVVM Light, but it is actually really lightweight. It is a very realistic scenario that for larger apps the SimpleIoc just won’t do (or you’re like me and want to try out how hard it is to replace it with another one). In this example I’m going to replace SimpleIoc with AutoFac, another well known and very powerful IOC service.
First of all, we’re going to need the AutoFac libraries and the extra library that allows us to use the ServiceLocator, just like SimpleIoc does. So either from the package manager console or from the UI, add the CommonServiceLocator extra for AutoFac, the AutoFac libraries are a dependency so they’ll get installed as well. I’m using a brand new Windows Phone 8 project for this, started from the MVVM Light project template.
Code Snippet
- Install-Package Autofac.Extras.CommonServiceLocator
The only place we’ll need to change some code is in the ViewModelLocator.
This is the new ViewModelLocator constructor, I’ve put the old SimpleIoc code in comments so it’s easy to compare
Code Snippet
- static ViewModelLocator()
- {
- var container = newContainerBuilder();
-
- //ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
- ServiceLocator.SetLocatorProvider(() => newAutofacServiceLocator(container.Build()));
-
- if (ViewModelBase.IsInDesignModeStatic)
- {
- //SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
- container.RegisterType<Design.DesignDataService>().As<IDataService>();
- }
- else
- {
- //SimpleIoc.Default.Register<IDataService, DataService>();
- container.RegisterType<DataService>().As<IDataService>();
- }
-
- //SimpleIoc.Default.Register<MainViewModel>();
- container.RegisterType<MainViewModel>();
- }
And that’s it, we declare a ContainerBuilder, set it as the LocatorProvider. The container is then used to register everything we need. The SimpleIoc overload that creates an instance upon registering would look something like this in AutoFac.
Code Snippet
- container.RegisterInstance(newDataService()).As<IDataService>();
That’s it, constructor injection should still work exactly like before with SimpleIoc.
4. Built-in messages
MVVM Light has something called the messenger, it registers classes as listeners and can send messages to them. This is commonly used to do communication between viewmodels. Generally I would create a message class for each type of message that I want to send, but MVVM Light has some build in messages that we can use.
GenericMessage<T>(T content) A message that can contain whatever of type T.
Code Snippet
- Messenger.Default.Send(newGenericMessage<string>("my message"));
NotificationMessage(string notification)a message that contains a notification. this might be used to send a notification to a notification factory that will show the message in the preferred way.
Code Snippet
- try
- {
- //try something
- }
- catch (Exception ex)
- {
- Messenger.Default.Send(newNotificationMessage(ex.Message));
- }
There’s also a NotificationMessage<T>(T notification) should you need it.
The next one is NotificationMessageAction(string notification, Action callback) basically the same as the NotificationMessage but you can add a callback action that will fire once the message is received. This one also has the generic implementation just like NotificationMessage.
DialogMessage(string content, Action<MessageBoxResult> callback) This message is meant to ask the user to input something and it will return the result of that input in the MessageBoxResult. MessageBoxResult is an enum that lives in System.Windows
Code Snippet
- publicenumMessageBoxResult
- {
- None = 0,
- OK = 1,
- Cancel = 2,
- Yes = 6,
- No = 7,
- }
Code Snippet
- Messenger.Default.Send(newDialogMessage("Are you sure?", result =>
- {
- if (result == MessageBoxResult.Yes)
- {
- //do something
- }
- }));
The DialogMessage class inherits from GenericMessage<string>
PropertyChangedMessage(T oldValue, T newValue, string propertyName)
The PropertyChangedMessage is meant to use like the RaisePropertyChanged implementation. This is great when multiple viewmodels need to respond to a changed property.
Code Snippet
- publicstring WelcomeTitle
- {
- get
- {
- return _welcomeTitle;
- }
-
- set
- {
- if (_welcomeTitle == value)
- {
- return;
- }
-
- Messenger.Default.Send(newPropertyChangedMessage<string>(_welcomeTitle, value, "WelcomeTitle"));
-
- _welcomeTitle = value;
- RaisePropertyChanged(WelcomeTitlePropertyName);
- }
- }
Be careful when registering listeners, try to use as many different types of messages as makes sense. You don’t want a wrong listener to receive a message because it happens to listen to the same type of message. To register a listener do this:
Code Snippet
- Messenger.Default.Register<PropertyChangedMessage<string>>(this, message =>
- {
- var a = message.NewValue;
- //do something
- } );
5. Portable libraries
MVVM Light is available on every XAML based platform. And it comes with a portable version now. The portable version is a separate library on NuGet.
Code Snippet
- Install-Package Portable.MvvmLightLibs
If you decide to use the portable version, make sure that every project in your solution that needs the MVVM Light libraries references the portable version. It does not work together with the “normal” MVVM Light libraries. When you use the PCL version, you can put your viewmodels in a separate, portable library and share them over, for example, a Windows Store and a Windows Phone app.
6. Event to Command behavior
MVVM Light has an ICommand implementation called RelayCommand that can be used to bind commands to actions. Like for example a button in XAML has a Command property that can be bound to an ICommand on its datacontext, so that when the button is clicked the ICommand will fire. Unfortunately not every XAML UI element has a bindable command property for every event that they can trigger and that’s where EventToCommand comes into play. With EventToCommand you can bind any event from a XAML UI element to an ICommand in the viewmodel.
First we’ll need two namespaces in our XAML page
Code Snippet
- xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
- xmlns:command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP8"
Let’s say that we want to use the Tap event on a stackpanel.
Code Snippet
- <StackPanel Grid.Row="0" Orientation="Horizontal">
- <i:Interaction.Triggers>
- <i:EventTrigger EventName="Tap">
- <command:EventToCommand Command="{Binding GoToCommand}" CommandParameter="Edit" />
- </i:EventTrigger>
- </i:Interaction.Triggers>
Line 3 specifies the event that we want to handle, note that this is a string so be aware of typos. Line 4 binds the actual command and can even pass a parameter to the ICommand implementation.
Code Snippet
- privateRelayCommand<string> _goToCommand;
- publicRelayCommand<string> GoToCommand
- {
- get { return _goToCommand jQuery15206875578026641675_1366095632942 (_goToCommand = newRelayCommand<string>(NavigateAway)); }
- }
The NavigateAway method has this signature
Code Snippet
- privatevoid NavigateAway(string parameter)
The parameter will be the word “Edit” in this case as that’s what we’ve specified in the XAML. We can even pass the eventargs from the event to the Command by changing line 4 from the XAML snippet to this
Code Snippet
- <command:EventToCommand PassEventArgsToCommand="True" Command="{Binding GoToCommand}" />
Windows Store applications don’t have these behaviors out of the box so you won’t be able to use EventToCommand there unless you install the Win8nl toolkit from NuGet. Joost Van Schaik has build his own implementation of behaviors in WinRT and thanks to his efforts (and of some other people that have helped in the project) we can now use EventToCommand in WinRT.
7. DispatcherHelper
Since .net 4.5 we have the await/async keywords and being the good little citizens that we are we do a lot of stuff async now. That means if we want to update something that lives on the UI thread we’ll need the Dispatcher class to marshall our action to that thread. Normally we don’t have access to the Dispatcher from our viewmodel classes. MVVM Light contains a DispatcherHelper that will execute an action on the UI thread when needed.
Code Snippet
- DispatcherHelper.CheckBeginInvokeOnUI(() =>
- {
- //do something
- });
The DispatcherHelper gets initialized in the App.xaml.cs in the InitializePhoneApplication method (in a WP8 project that is).
DispatcherHelper also has a RunAsync method. The difference with the CheckBeginInvokeOnUI is that the CheckBeginInvokeOnUI will first check if it’s already on the UI thread, if it is it will just execute the action, if it isn’t it will call the RunAsync method.
8. Blendable
MVVM Light has complete Blend support, meaning you can drag and drop properties from the viewmodel onto the view to generate a binding, or you can generate design time data based on the datacontext and so on. I’m really not that good in Blend so I’m not going into detail about this one, just remember that MVVM Light was build with Blend in mind.
9. Open Source
This one you probably knew but MVVM Light is completely open source. http://mvvmlight.codeplex.com/ is the place to be if you want to dive into the source code.
10. Laurent is on Twitter and he’s a nice guy 
Laurent Bugnion, the founder of MVVM Light, is on Twitter! https://twitter.com/LBugnion he’s a great guy to chat with and very eager to help out anyone who needs help.
Conclusion
MVVM Light is a great library with a few hidden gems. In this article I’ve discussed 8 very interesting ones that can make your life as a developer easier. I’ve included two more extra items because 10 is a prettier number than 8 
by Nico
While SQLce is still a viable solution in Windows Phone 8 to have some form of local database we also have an official SQLite implementation available. So why use SQLite when we can just keep using SQLce? Because Windows 8 only support SQLite and if you ever want to port over your app it would be nice not to have two versions of local databases to maintain. In this post I’ll explain how to implement a SQLite database into an MVVM Light Windows Phone 8 project (there is an unofficial Windows Phone 7 SQLite version as well but I have no idea how stable / buggy that is). I’ll be using Tim Heuer’s SQLite .net wrapper so we can use LINQ to SQLite instead of writing SQL queries manually (hooray for intellisense ). Let’s kick things off by creating an empty Windows Phone 8 app. SQLite Before we can use SQLite, we’ll need to install the SDK. Click here (official SQLite download page) to download the VSIX file and install it into Visual Studio. NuGet fun Before we can write any code we’ll need some NuGet packages. Use these commands in the Package Manager Console. Install-Package MvvmLight Install-Package sqlite-net Install-Package WPtoolkit Install-Package Cimbalino.Phone.Toolkit Changing target platform SQLite is a C++ library, meaning that it should be compiled against the architecture that the app will be running on. On Windows 8 that means creating separate packages for ARM and x86. On Windows Phone 8 that means switching from Any CPU to ARM when running on a device or when creating your XAP. When you’re running your app on the emulator the target platform needs to be set to x86.  Moving files around When you install the MVVM Light package it will add some folder structure and some files. I like to adjust this a bit more by adding a View folder and moving the MainPage into that view. That means that the startup page has to change as well. Open up the WMAppManifest.xml and change it like on the screenshot.  At this stage I couldn’t build the project because of a whole bunch of compile errors in the sqlite-net files. If you get the same problem (by the time you read this, it might be fixed), download the sqlite-net source from GitHub and from your project, add a reference to your local sqlite-net repo/lib/wp7/Community.CsharpSqlite.WinPhone.dll and that should fix it right up. Also, add a folder “Model” to the project so that our MVVM folder structure is complete. The demo app The app that we’ll be creating today is an app to keep track of tasks, which seems to be the new “Hello, World!”. We’ll start with the model, and work our way up to the view from there. Our class is called “Task” that means we’ll have to be careful that we use Model.Task instead of System.Threading.Task but we’ll manage. Code Snippet - [Table("Tasks")]
- public class Task : INotifyPropertyChanged
- {
- private int _id;
- private string _title;
- private DateTime _date;
-
- [PrimaryKey, AutoIncrement]
- public int Id
- {
- get { return _id; }
- set
- {
- if (value == _id) return;
- _id = value;
- OnPropertyChanged("Id");
- }
- }
-
- public string Title
- {
- get { return _title; }
- set
- {
- if (value == _title) return;
- _title = value;
- OnPropertyChanged("Title");
- }
- }
-
- public DateTime Date
- {
- get { return _date; }
- set
- {
- if (value.Equals(_date)) return;
- _date = value;
- OnPropertyChanged("Date");
- }
- }
-
- public event PropertyChangedEventHandler PropertyChanged;
- protected virtual void OnPropertyChanged(string propertyName = null)
- {
- PropertyChangedEventHandler handler = PropertyChanged;
- if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
- }
- }
The “Task” class implements INotifyPropertyChanged so that controls that are bound to its properties get updated like good citizens. Now for the annotations, those come from sqlite-net and mark this class as a table in the database. The same goes for the annotations on the Id property, that property is marked as being the primarykey and being an autoincremented value. If you have a property that you don’t want in the database, add the [Ignore] attribute and there won’t be any column generated for it. Now that we have a model we can start working on the service, the class that will do all the SQLite communication. (Yes we could do all this in the viewmodel but it’s called seperation of concerns ). And to do this the right way we’ll start by creating an interface for the service. Code Snippet - public interface IDataService
- {
- Task SaveTask(Model.Task newTask);
- Task<IList<Model.Task>> LoadTasks();
- Task UpdateTask(Model.Task selectedTask);
- Task DeleteTask(Model.Task selectedTask);
- }
Those are all the basic CRUD (Create, Read, Update, Delete) that we can (should be able to) perform on any datacontainer. Here’s the implementation Code Snippet - public class DataService : IDataService
- {
- public async Task SaveTask(Model.Task newTask)
- {
- await App.Connection.InsertAsync(newTask);
- }
-
- public async Task<IList<Model.Task>> LoadTasks()
- {
- return await App.Connection.Table<Model.Task>().ToListAsync();
- }
-
- public async Task UpdateTask(Model.Task selectedTask)
- {
- await App.Connection.UpdateAsync(selectedTask);
- }
-
- public async Task DeleteTask(Model.Task selectedTask)
- {
- await App.Connection.DeleteAsync(selectedTask);
- }
-
- public async Task<IList<SubTask>> LoadSubTasks()
- {
- return await App.Connection.Table<SubTask>().ToListAsync();
- }
- }
Hmm looks like I forgot to mention something, go to App.xaml.cs and add this property Code Snippet - public static SQLiteAsyncConnection Connection { get; set; }
Keep App.xaml.cs open, we’ll need it in a minute. In the DataService class we’re calling all the CRUD methods provided to us by sqlite-net. We can get a list of all records in a table by calling .Table<T>().ToListAsync() or do any of the other CRUD operations by just calling the function and passing in the modified POCO. Really easy and quite powerful. Let’s jump back to App.xaml.cs, there should be an empty function called Application_Launching. In this function we’ll need to check if the database exists, open a connection to it if it exists or create it first and then open the connection. Code Snippet - private async void Application_Launching(object sender, LaunchingEventArgs e)
- {
- try
- {
- await ApplicationData.Current.LocalFolder.GetFileAsync("taskDB.db");
- Connection = new SQLiteAsyncConnection("taskDB.db");
- }
- catch (FileNotFoundException)
- {
- CreateDB();
- }
- }
Unfortunately, there is no DataBaseExists() function like in SQLce so I choose to do it the quick and dirty way. I try to get the database, which is basically a file in the ApplicationData, if the file doesn’t exist it will throw a FileNotFoundException and that’s where I call the CreateDB() method. Code Snippet - private async void CreateDB()
- {
- Connection = new SQLiteAsyncConnection("taskDB.db");
-
- await Connection.CreateTableAsync<Task>();
- }
Line 3 creates the database while line 5 creates the Task table in the database. When all that’s in place, we’re ready to move to the viewmodels. ViewModel Not much to say here, we all know what a viewmodel is, so here is the MainViewModel. The IDataService field is what we’ve defined just a minute ago, it gets instantiated through the constructor. INavigationService comes from the Cimbalino toolkit, it allows us to do page to page navigation from within the viewmodels. There’s a property of IList<Task> that one will hold all the available tasks, they are loaded at startup, also newly added tasks will be put in that list. There’s a property of type Task, his properties will be bound to the input fields on the new task form, when the user clicks save the property will be pushed to the dataservice to save it in the database. Talking about the save button, there are two RelayCommands (MVVM Light’s implementation of ICommand). One is for saving a new property and the second one is for navigating to the detail page when a task is selected. In the constructor both fields are set and the Task property is initialized, setting the date to today. Since our datepicker will be bound to this property it will automatically be set to today’s date. Loading all the tasks needs to be done asynchronous, since the constructor can’t be marked as async we’ll put the service call in a synchronous method and call that one from the constructor, that way we can use the async / await keywords. Saving a task is as easy as calling the SaveTask function on IDataService and adding the new task to the list, and reinitializing it afterwards to clear all the fields. You might want to think about adding some check here in case something goes wrong while saving to the DB (have it return a boolean for example), I’ll just be living on the edge here and assume this never fails . For navigating to the detail page we’ll add a command to the SelectionChanged event of our LongListSelector. We use the MVVM Light messenger, some sort of implementation of the Observer pattern, to send over the selected item to anyone registered to listen to a message of type TaskSelectedMessage. The TaskSelectedMessage class is pretty basic. Code Snippet - public class TaskSelectedMessage : MessageBase
- {
- public Model.Task Task { get; set; }
-
- public TaskSelectedMessage(Model.Task task)
- {
- Task = task;
- }
- }
The class inherits from MessageBase, which is a class in the MVVM Light library, it has one property that is set in the constructor (that’s just to make life a bit easier). In the MainViewModel, when the SelectionChanged event fires we send a message of this type containing the selected item, once the message is on its way we use the INavigationService to navigate to the detail page. Here’s the viewmodel for the editpage. Code Snippet - public class EditViewModel : ViewModelBase
- {
- private readonly IDataService _dataService;
- private readonly INavigationService _navigationService;
-
- /// <summary>
- /// The <see cref="SelectedTask" /> property's name.
- /// </summary>
- public const string SelectedTaskPropertyName = "SelectedTask";
-
- private Task _selectedTask;
-
- /// <summary>
- /// Sets and gets the SelectedTask property.
- /// Changes to that property's value raise the PropertyChanged event.
- /// </summary>
- public Task SelectedTask
- {
- get
- {
- return _selectedTask;
- }
-
- set
- {
- if (_selectedTask == value)
- {
- return;
- }
-
- RaisePropertyChanging(SelectedTaskPropertyName);
- _selectedTask = value;
- RaisePropertyChanged(SelectedTaskPropertyName);
- }
- }
-
- public RelayCommand UpdateTaskCommand
- {
- get { return new RelayCommand(UpdateTask); }
- }
-
- public RelayCommand DeleteTaskCommand
- {
- get { return new RelayCommand(DeleteTask); }
- }
-
- public EditViewModel(IDataService dataService, INavigationService navigationService)
- {
- _dataService = dataService;
- _navigationService = navigationService;
-
- Messenger.Default.Register<TaskSelectedMessage>(this, msg => SelectedTask = msg.Task);
- }
-
- private void UpdateTask()
- {
- _dataService.UpdateTask(SelectedTask);
- }
-
- private void DeleteTask()
- {
- _dataService.DeleteTask(SelectedTask);
- }
- }
The same fields can be found here (I could put them in a base class, would be cleaner but who cares about clean code anyway? – well you should all care!). One property in this viewmodel, to hold the selected task and bind its properties to the view. A few commands for update and delete, they just call their respective functions on the DataService passing in the selected Task. The interesting part here is in the constructor. The fields get set and we register the viewmodel to listen if the messenger has a message of type TaskSelectedMessage, if it does set the task in the message to the property. However, the viewmodel by default gets instantiated when we navigate to the view meaning that the message has left the building before the receiver has registered as a receiver so it won’t arrive. Let’s fix that shall we? When you’ve added the MVVM Light libraries through NuGet (or you used the MVVM Light project templates) there should be a ViewModelLocator class in your ViewModel folder. This class registers your viewmodels in the TinyIoc container. Registering those viewmodels has an overload that, when set to True, creates an instance of each viewmodel at application launch, meaning that the viewmodels register themselves on the messenger before any message can be send. Here are my viewmodel registrations (from the ViewModelLocator constructor). Code Snippet - SimpleIoc.Default.Register<MainViewModel>();
- SimpleIoc.Default.Register<EditViewModel>(true);
MainViewModel won’t get instantiated at registration but EditViewModel will. So that’s a problem solved. Next piece of the puzzle are those constructor parameters in the viewmodels. They get resolved by dependency injection, we register the correct types here in the ViewModelLocator and when the viewmodel constructor is called, the correct instances will get injected automagically. Code Snippet - if (ViewModelBase.IsInDesignModeStatic)
- {
- // Create design time view services and models
- SimpleIoc.Default.Register<IDataService, DesignService>();
- }
- else
- {
- // Create run time view services and models
- SimpleIoc.Default.Register<IDataService, DataService>();
- SimpleIoc.Default.Register<INavigationService, NavigationService>();
- }
Take this for example, when we are in design mode (Blend for example) we can load an IDataService implementation that returns dummy data so that we can style our views very easily (code gets executed when running at designtime so even when you’re not using dummy data it’s a good idea to register these types in an if-block to prevent design time errors). What everything in place, let’s have a look at the xaml and hook everything up. We’ll start with the MainPage.xaml and since XAML has a tendency of growing quite large, I’ll chop it in pieces. First thing a page needs in an MVVM scenario is a DataContext, meaning our ViewModel. This can be set from code behind (DataContext = new MainViewModel()) but that would just null out every use of the ViewModelLocator. We’ll set the datacontext from XAML. Code Snippet - <phone:PhoneApplicationPage x:Class="SqLitePoc.View.MainPage"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP8"
- xmlns:behaviors="clr-namespace:Cimbalino.Phone.Toolkit.Behaviors;assembly=Cimbalino.Phone.Toolkit"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
- xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
- xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
- DataContext="{Binding Main,
- Source={StaticResource Locator}}"
- FontFamily="{StaticResource PhoneFontFamilyNormal}"
- FontSize="{StaticResource PhoneFontSizeNormal}"
- Foreground="{StaticResource PhoneForegroundBrush}"
- Orientation="Portrait"
- SupportedOrientations="Portrait"
- shell:SystemTray.IsVisible="True"
- mc:Ignorable="d">
The key here is DataContext="{Binding Main, Source={StaticResource Locator}}" this says to the view that its datacontext is bound to a property called Main and that property lives in a resource called Locator (that resource is defined in App.xaml). Now for the page itself, the page consists of a pivot control with two pivot pages, one for entering new tasks and one for viewing a list of all the tasks that have been created so far. Code Snippet - <!-- LayoutRoot is the root grid where all page content is placed -->
- <Grid x:Name="LayoutRoot" Background="Transparent">
- <!-- Bindable Appbar buttons -->
- <i:Interaction.Behaviors>
- <behaviors:ApplicationBarBehavior>
- <behaviors:ApplicationBarIconButton Command="{Binding SaveNewTaskCommand, Mode=OneTime}" IconUri="/Assets/AppBar/save.png" Text="Save Task" />
- </behaviors:ApplicationBarBehavior>
- </i:Interaction.Behaviors>
-
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto" />
- <RowDefinition Height="*" />
- </Grid.RowDefinitions>
- <phone:Pivot Title="SQLite POC" Grid.Row="1">
- <phone:PivotItem x:Name="NewTask" CacheMode="{x:Null}" Header="new task">
- <StackPanel>
- <TextBlock Text="Title" TextWrapping="Wrap" />
- <TextBox x:Name="TextBoxTitle"
- Height="72"
- Text="{Binding NewTask.Title, Mode=TwoWay}"
- TextWrapping="Wrap" />
- <TextBlock Text="Complete by" TextWrapping="Wrap" />
- <toolkit:DatePicker Value="{Binding NewTask.Date, Mode=TwoWay}" />
- </StackPanel>
- </phone:PivotItem>
- <phone:PivotItem x:Name="AllTasks" CacheMode="{x:Null}" Header="all tasks">
- <phone:LongListSelector ItemTemplate="{StaticResource TaskListItemTemplate}" ItemsSource="{Binding Tasks}">
- <i:Interaction.Triggers>
- <i:EventTrigger EventName="SelectionChanged">
- <command:EventToCommand Command="{Binding SelectionChangedCommand}" PassEventArgsToCommand="True" />
- </i:EventTrigger>
- </i:Interaction.Triggers>
- </phone:LongListSelector>
- </phone:PivotItem>
- </phone:Pivot>
- </Grid>
First thing in this snippet is a behavior for a bindable appbar button. The default appbar is not bindable, meaning that you can’t bind the buttons Command property to an ICommand on your viewmodel. This wasn’t the case in WP7 and it still isn’t in WP8, bit of a pain. Luckily, Cimbalino toolkit gives us an ApplicationBarBehavior, allowing us to bind our ICommands to the appbar, the only trade off we need to make is that the appbar buttons won’t be visible at design time but that’s a small trade-off in my opinion. We’ll add one button in the appbar, bind it to the SaveNewTaskCommand RelayCommand in MainViewModel and appoint it the save icon. Then there’s the pivot control, first pivotitem contains a stackpanel with a textbox for entering a task title and a datepicker (courtesy of the Windows Phone Toolkit) both are bound to properties of the NewTask property on the MainViewModel. Don’t forget to set the bind mode to TwoWay so that we can update the properties from our view. The second pivot item contains a list of all the tasks. Now, in WP8 they advice us to use the LongListSelector instead of the listbox that’s all great but at least make it behave more like a listbox and not some crippled dependency property missing piece of ****. The problem lies in the SelectedItem property, myself and many other XAML devs usually create a SelectedTask property and bind it to the SelectedItem property of the ListBox, the setter of that SelectedTask property would then be used to navigate to the detailspage. That was a clean, fast solution but the LongListSelector’s SelectedItem property is not a dependency property, meaning it cannot be bound so that’s not a viable solution anymore. Second option would be to bind an ICommand to the SelectionChanged event, again a no-go. There are some implementations of the LongListSelector floating around on the internet that has a bindable SelectedItem property so that would be a solution, another one is to add an EventToCommand behavior and binding the SelectionChanged event to the MainViewModel in the behavior (that’s right Windows 8 devs, we Windows Phone devs still get behaviors out of the box). I’m going with the EventToCommand solution, only thing I haven’t solved here is that when we navigate to the detail page, navigate back to the mainpage and click the same task again it won’t do anything anymore since that item still is the selected item so the selection doesn’t change and the event doesn’t fire. A solution here would be to use the messenger to send a message to the code behind of the view to set the SelectedItem property of the LongListSelector to null. tl;dr version: LongListSelector kind off sucks but it can be solved. The LongListSelector is bound to the Tasks collection, the ItemTemplate is defined in the resources part of the page Code Snippet - <phone:PhoneApplicationPage.Resources>
- <DataTemplate x:Key="TaskListItemTemplate">
- <StackPanel>
- <TextBlock x:Name="Title"
- Style="{StaticResource JumpListAlphabetStyle}"
- Text="{Binding Title}"
- TextWrapping="Wrap" />
- <TextBlock x:Name="Date"
- Margin="12,0,0,0"
- Text="{Binding Date}"
- TextWrapping="Wrap">
- <Run />
- <LineBreak />
- <Run />
- </TextBlock>
- </StackPanel>
- </DataTemplate>
- </phone:PhoneApplicationPage.Resources>
That gives the list a nice look (as far as I can tell that is, I really really suck at designing apps…) Last part on this page is the appbar itself, the button are defined using the Cimbalino toolkit but we need to actually put an appbar on the page, this sits between the resources and the LayoutRoot grid. Code Snippet - <!-- Buttons are defined using the behaviors in the Cimbalino toolkit to allow a bindable appbar -->
- <phone:PhoneApplicationPage.ApplicationBar>
- <shell:ApplicationBar IsMenuEnabled="True" IsVisible="True" />
- </phone:PhoneApplicationPage.ApplicationBar>
And that’s it for the MainPage, on to the final part of this post, the EditPage.xaml First, the datacontext Code Snippet - DataContext="{Binding Edit, Source={StaticResource Locator}}"
Then the appbar buttons, again using Cimbalino (these need to sit in the LayoutRoot grid) Code Snippet - <!-- Bindable Appbar buttons -->
- <i:Interaction.Behaviors>
- <behaviors:ApplicationBarBehavior>
- <behaviors:ApplicationBarIconButton Command="{Binding UpdateTaskCommand, Mode=OneTime}" IconUri="/Assets/AppBar/save.png" Text="Save Task" />
- <behaviors:ApplicationBarIconButton Command="{Binding DeleteTaskCommand, Mode=OneTime}" IconUri="/Toolkit.Content/ApplicationBar.Delete.png" Text="Save Task" />
- </behaviors:ApplicationBarBehavior>
- </i:Interaction.Behaviors>
And then there’s the controls Code Snippet - <!-- TitlePanel contains the name of the application and page title -->
- <StackPanel Grid.Row="0" Margin="12,17,0,28">
- <TextBlock Style="{StaticResource PhoneTextNormalStyle}" Text="SQLite POC" />
- <TextBlock Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" Text="Edit Task" />
- </StackPanel>
-
- <!-- ContentPanel - place additional content here -->
- <Grid x:Name="ContentPanel"
- Grid.Row="1"
- Margin="12,0,12,0">
- <StackPanel Margin="0,0,0,76">
- <TextBlock Text="Title" TextWrapping="Wrap" />
- <TextBox x:Name="TextBoxTitle" Height="72" Text="{Binding SelectedTask.Title, Mode=TwoWay}" TextWrapping="Wrap" />
- <TextBlock Text="Complete by" TextWrapping="Wrap" />
- <toolkit:DatePicker Value="{Binding SelectedTask.Date, Mode=TwoWay}" />
- </StackPanel>
- </Grid>
That’s all pretty much the same as in the MainPage. And with that our small SQLite POC is finished. Conclusion In this post I’ve discussed SQLite in a Windows Phone 8 app. What you should take away from this is that as of Windows Phone 8 SQLite is a first class citizen, even more so when using the excellent sqlite-net library. Don’t forget to switch the platform when running on emulator or on a device, this is necessary because SQLite is a C++ library. I’ve also talked a bit about MVVM Light and the way I use it, I don’t claim that this is the best / only way to use the excellent MVVM implementation by Laurent Bugnion but it is one I feel comfortable with and that gives me great results. If you have any questions / remarks, feel free to drop a comment! UPDATE: for the LongListSelector, you can also use an extension of the control instead of defining a trigger, see http://stackoverflow.com/questions/14586521/bind-viewmodel-to-item-from-longlistselector-in-datatemplate/14600157#14600157 for more detail. thanks for the tip Glenn (link to Glenn’s Twitter)!
by Nico
Fiddler and the WP8 emulator Fiddler is a great tool for capturing network traffic. I find it especially useful when I’m working with services. It sniffs out your network traffic and allows you to dig into every incoming or outgoing request. You can even create requests from inside the tool. The tool itself is free to use and can be downloaded from https://fiddler2.com/fiddler2/  So how does it work? Fiddler installs a proxy on your machine (default on port 8888). That proxy intercepts all network traffic going from and to the machine it’s installed on. That traffic gets displayed in the Fiddler UI. The proxy captures the traffic, sends it to the application and let the traffic itself pass to the original destination. This image shows the normal client – internet situation (top half) and the situation with Fiddler installed (bottom half).  Makes sense? Nothing to difficult about this. What I just explained here is the basic functionality of Fiddler. Only monitoring your local traffic. The Windows Phone 8 emulator runs as a Hyper-V virtual machine, meaning it identifies itself as a separate device on the network. But that’s not really a problem, Fiddler in al its greatness can monitor remote devices as well. Here’s how to enable it. First, start Fiddler and go to Tools > Fiddler options. Go to tab “Connections” and check the “Allow remote computers to connect” option.  Click OK, back on the Fiddler main screen, you’ll notice a textbox underneath the list of captured requests (a black one). That’s called the QuickExec box, it can be used to set preferences. In our case we need to add a hostname to our proxy. The hostname we need to add is the one from the Hyper-V host that is running the Windows Phone emulator, your developer machine in other words. Since all traffic from the Windows Phone emulator goes through our developer machines we need to attach Fiddler to our pc. The default localhost connection won’t work so we need to attach the Fiddler proxy to the network name. In the QuickExec box enter this command prefs set fiddler.network.proxy.registrationhostname <your computername>  With that done, restart Fiddler and the Windows Phone emulator and behold the emulator’s traffic getting sniffed. As you can see on the screenshot below, if I use the mobile browser in the emulator to go to my blog Fiddler captures all the images, pages, scriptfiles etc. that are getting loaded. If I select one, the user agent clearly points to the Windows Phone 8 browser.  Note that it doesn’t just captures the emulator’s traffic, all the localhost traffic is still captured as well. Keep in mind that if you close Fiddler now there’s a chance that the Windows Phone emulator won’t have network access anymore, that’s because at startup it configured the Fiddler proxy as gateway, closing Fiddler means disabling the proxy. Simply restart the emulator and it should work fine again. This is all great stuff, but eventually we’ll run into a situation where we need to sniff network traffic but for some reason we can’t use the emulator. With Fiddler we can also sniff the network traffic from an actual Windows Phone device, provided the machine running Fiddler and the Windows Phone are connected to the same network. Fiddler and WP8 devices To do this, setup Fiddler the same way as we did for the emulator. When that’s done, on you Windows Phone device go to Settings > WiFi. Select the wireless network that your phone is connected to and enable the Proxy. Set the proxy url to the IP address or the hostname of the computer running Fiddler and the port to 8888.  Fire up Fiddler, fire up the mobile browser on your phone and be amazed! If you’re decrypting HTTPS traffic you might need to install the Fiddler certificate on your phone, the browser will prompt you to install it. Before testing your app with HTTPS, try the browser first so the certificate gets installed. Do be aware that every Fiddler installation generates its own certificate (they are self-signed so you might get a security warning, in this case its perfectly safe to ignore that warning) so you might need to install a new one when you use Fiddler on another machine.  Conclusion In this post we’ve talked about using Fiddler, a great tool for sniffing and decrypting network requests, with both the Windows Phone 8 emulator and Windows Phone 8 devices. It’s really easy to setup and a great asset when working or developing services. A few remarks to end this post: If you ever change your computer’s hostname Fiddler will stop capturing Windows Phone network. Use the prefs set fiddler.network.proxy.registrationhostname <your computername> command again in the QuickExec box with the new hostname and Fiddler will happily continue its work. If you computer is joined to a domain that has IPSEC security setup you will need to ask the administrator to add a IPSEC Boundary Computer exception for your computer. Happy sniffing!
by Nico
That Microsoft loves his communities is no secret. The past months we literally drowned in hackathons, trainings, competitions and many more Windows 8 related. And it doesn’t look like it’s stopping any time soon! On November 23th Microsoft Belgium organizes the Windows App Day, a day stuffed to the top with sessions divided into two tracks, one for developers and one for designers. And the best part? It’s not only for Windows 8! Windows Azure and my all time favorite platform, Windows Phone 8 will be represented as well. So if you’re in or around Belgium on November 23th and feel like spending the day with our great community feel free to drop by. There might even be some very cool announcement concerning people that are into Windows 8 development… drop by to get the full story (and start thinking about that one killer app)! Details: When: Friday 23 November 2012, 9AM to 6PM Where: ALM Meeting Point Filip Williotstraat 9 2600 Antwerp (Berchem) All details: http://www.microsoft.com/belux/msdn/windows-app-day/default.aspx 
by Nico
My first week back on the job is finished, that means I’ve had about 5 hours of time to work on my lunch game. Progress started of pretty small because of some enemy placement issues that showed up after I changed the complete control scheme. After loosing about an hour of time trying to fix it, I’ve decided to revert back to the virtual thumbsticks. About half an hour and some Mercurial commands later I was back to the original controls, the enemy movement behavior also reverted back to normal. Day 2 I decided it was about time to make the enemy move, the character itself was moving up and down but without any animation, he was just sliding up and down. My animations are done using a spritesheet, the eight walking directions each have a line in the spritesheet. In the code itself I have a rectangle that has the width and height of one texture on the sheet, using the Update method I move the rectangle after x amount of time. This is the piece of code that creates the animation protected Rectangle SourceRectRunning;
protected readonly TimeSpan RunRate = TimeSpan.FromSeconds(0.1);
protected TimeSpan RunTimer;
public override void Update(GameTime gameTime)
{
RunTimer -= gameTime.ElapsedGameTime;
if (RunTimer <= TimeSpan.Zero)
{
if (CharState == State.Running)
{
if (SourceRectRunning.X >= TextureWidth * 7)
{
SourceRectRunning.X = 0;
return;
}
SourceRectRunning.X = SourceRectRunning.X + (int)TextureWidth;
}
RunTimer = RunRate;
}
}
The CharState is just en enum that I’ve build. The enum looks like this
public enum State
{
Running,
Standing,
Spotted,
Walking
}
This makes it very easy for me to call the right code when the player starts moving or when he’s spotted by the enemy.
I was very happy of how the animation looked like, so I figured it was about time to do something about the collision detection. This is something I’ve implemented quite some time ago but it never really worked how it should. The way collision detection is working in my app is a pretty nifty one. I found it in the demo code of the tile engine that I’m using.
A map build with Tiled consist of several layers, I have a layer that contains only the floor textures and a second layer that contains stuff like trees, walls and other non-interactable objects. The demo project contained with the WP7 Tiled engine has a method that can get the color of a certain tile on a certain layer. I take the player’s position, add a few pixels to it and determine the color on that location of the Objects layer, if the color is NULL then there’s no object in the way. Let me show you the code
Color? collColor = _level.Map.GetColorAt("Objects", _player.WorldPosition +
(VirtualThumbsticks.LeftThumbstick * 5));
if (collColor == null)
{
//player can move
}
The GetColorAt method looks like this
public Color? GetColorAt(string layerName, Vector2 position)
{
var l = GetLayer(layerName);
TileLayer tileLayer = l as TileLayer;
position.X = (int)position.X;
position.Y = (int)position.Y;
Vector2 tilePosition = new Vector2((int)(position.X / TileWidth), (int)(position.Y/TileHeight));
Tile collisionTile = tileLayer.Tiles[(int)tilePosition.X, (int)tilePosition.Y];
if (collisionTile == null)
return null;
if (collisionTile.CollisionData != null)
{
int positionOnTileX = ((int)position.X - (((int)position.X / TileWidth) * TileWidth));
int positionOnTileY = ((int)position.Y - (((int)position.Y / TileHeight) * TileHeight));
positionOnTileX = (int)MathHelper.Clamp(positionOnTileX, 0, TileWidth);
positionOnTileY = (int)MathHelper.Clamp(positionOnTileY, 0, TileHeight);
int pixelCheckX = (collisionTile.Source.X) + positionOnTileX;
int pixelCheckY = (collisionTile.Source.Y) + positionOnTileY;
return collisionTile.CollisionData[(pixelCheckY * collisionTile.Texture.Width) + pixelCheckX];
}
else
{
return null;
}
}
As I’ve said, this piece of code comes from the Tiled engine I’ve found on this site.
The problem I was having before was that I was passing the player’s coordinate on the screen to the method instead of the player’s position on the map. It does work much better now but currently I’m passing the coordinate of the upper left corner of the texture (XNA default) so it does need some fine-tuning.
I’m thinking next week to do some more work on the level editor or maybe start working on interactable objects. I’ll write another post next week, so stay tuned or follow me on Twitter to get daily updates.
by Nico
So I’ve already missed my first blog appointment about the Windows Phone game that I’m developing during my lunch brakes. Not a good start, but I’m taking two weeks off work so I do have a valid excuse  Last week I worked 3 hours on the game in total, my vacation started on Thursday with the app-a-thon. In those three hours I reworked the control scheme. Previously the character was moved using a virtual, on-screen thumbstick. That worked great but on a device with such small screen estate and my huge thumbs there wasn’t much left to see. So I reworked that into a point and click system, tap on the screen and the character will move to the position of the tap. A side effect of this new system is that some enemy movement bug got fixed automagically, that was a rather nice surprise. Next to the control scheme I made some progress on the collision detection system, since my level engine is a tile based layered engine it was quite easy to do. I’ll probably dedicate a separate post on the collision detection system. All in all good progress with little time. The project will now be shelved until the end of June, the day my vacation ends is the day I’ll pick the game back up. So that’ll be two weeks without updates. Keep an eye on Twitter for upcoming updates and see you in two weeks! 
by Nico
For the last couple of weeks I’ve been developing a game during my lunch break at work. Why? Mainly because I had this project in my mind for a while and I wanted something fun to do while eating lunch. Since I’ve started working on it I made a habit of tweeting my progress after the break, around 1PM GMT+1. Since I’ve started doing so a lot of people have shown interest in the project, providing tips and some even wanted to see the source code or wanted to help on the project. I never expected to get this much feedback from something like this so I’ve decided to try and write weekly blog posts about the project, I will still tweet daily about the progress and then make a weekly summary post with findings, problems and fixes. Now, about the game. The game is a stealth, sneak around the level, isometric 2D XNA game build for Windows Phone 7.5. If I finish it and I’m happy enough with the result to submit it to the marketplace then I’ll port it to Monogame and release it on some other platforms (no, not you iOS). What I have so far: I have a map, created with a free, open source program called Tiled. I use Tiled because it’s pretty easy to use and it provides libraries for Windows Phone to read the maps in an XNA project. Next to the map I have a player that can run around on the map, the player always stays in the center of the screen so I basically move the map around. I have an enemy, with a triangular field of view, who moves up and down between two points. The player gets spotted when he enters the field of view of the enemy. What I’m working on now: I’m currently building a level editor with winforms. This will make it easier for me to create lots of levels with enemies and objects in them. I currently have the form, I can open a map and read out the size date from the .tmx file (.tmx get’s created with Tiled). I want to finish the editor now so I can complete a first level. Once I have a complete level I can finetune the gameplay. Will I open source this? Currently not, there are a few people that I know personally who have access to the source code but the repository will remain private for now. Why? because I’m thinking about making this my first paid app (with a free, ad containing version) on the WP7 marketplace. If I get completely stuck I might get some other developers involved, but for the time being I will remain the only developer. Can I give more information about the story or setting? I probably could but I won’t for now, I’m going to build up the hype meter for this project so that everyone will want to get it and I will get rich. Once I’m rich I can start up my own game developer studio, create Version 2 of this, get even richer, buy EA and finally get them to make decent games again. Then I’ll probably wake up and realize this was all a dream. Should you be interested in following my project, please follow me on Twitter (@NicoVermeir) for daily updates or stay tuned for weekly updates on my blog. PS: I’m going on holiday from June 12th until August 1st so there will probably be little to no updates in that timeframe.
by Nico
Yesterday I did a talk in the Belgian Windows Phone User Group about beginning XNA development. It was the first time I did a talk in my own user group and I had a great time.
I also learned a very valuable lesson: don't name your Autohotkey snippets the same as your classes. It was quite the hilarious moment when I entered the class name in the "Add File" dialog and hit the Enter key.
Besides that small setback everything went great. The slidedeck and demo (shooting iphones down with a pink magenta Lumia) are zipped up and can be found here.
by Nico
Yesterday was Community Day, the biggest community driven event in Belgium.
I did a talk there about porting over a Windows Phone 7 app to Windows 8. It was very exciting, I never spoke to such a crowd before, let alone hooked up my portable to a cinema beamer.
The talk itself went pretty well but I did suffer from demo failure, what was really odd since the demo worked perfectly an hour earlier. I researched the error after the talk and it seems that in a Windows 8 Metro app the path to the manifest file is an absolute path for some reason. I suddenly remembered that I moved the solution to another folder right before the talk, so it was my own fault. Reminder to self: never move a folder before doing a talk.
Anyway, it was a great day, I've met some nice people, had fun discussions and attended an App clinic on UI (thanks Lesley for the useful information!). See you next year community day!
Download my slides and demos here.
|