Archive for the 'Windows Phone 7' Category

04
Apr
12

wp7–JSON parsing

Peter Daukintis

I’m writing this mainly as a central place to store this code as I need to use it frequently – hopefully it will help others also.

Supposing I have a web service that I want to call that returns me some JSON data. I want to get that from the service and into a class which I will use as a domain model in my application. The first thing to do is to make sure that we understand the hierarchy that the JSON data represents. So for example,

{ IsSuccess: true }

is an object with a boolean property ‘IsSuccess’ which in this case is true. So we can read the {}’s as enclosing an object.

[{ IsSuccess: true },{ IsSuccess: false }]  

This represents an array of objects; read the []’s as enclosing an array.

Here’s a slightly more complicated example:

// start
{
   "FleetsCollection":[
      {
         "FleetId":2,
         "Nickname":"2007 Ninja ZX6R",
         "PictureFileName":"jvmlfdaq.rkr2.jpg",
         "AverageMpg":43.90925,
         "MaxMpg":47.945
      },
      {
         "FleetId":44,
         "Nickname":"Luminous Neptune",
         "PictureFileName":"ochufm0c.ohm2.png",
         "AverageMpg":29.4285,
         "MaxMpg":30.341
      }
   ]
}

(Note – useful JSON formatter here http://jsonformatter.curiousconcept.com/)

I can interpret this as an object with a property ‘FleetsCollection’ which is a list of objects which have further properties. In fact, if you take your JSON string data you can convert it to a c# class using this online tool http://json2csharp.com/

For our example, the online tool generates,

public class FleetsCollection
{
    public int FleetId { get; set; }
    public string Nickname { get; set; }
    public string PictureFileName { get; set; }
    public double AverageMpg { get; set; }
    public double MaxMpg { get; set; }
}

public class RootObject
{
    public List<FleetsCollection> FleetsCollection { get; set; }
}

Then, we can read the data in using the following code:

var dataContractJsonSerializer = new DataContractJsonSerializer(typeof(RootObject));
RootObject readObject = (RootObject)dataContractJsonSerializer.ReadObject(memoryStream);

02
Mar
12

skydrive photo upload wp7

Peter Daukintis

I just modified my file upload sample (http://babaandthepigman.wordpress.com/2012/01/18/wp7-skydrive-upload/) to use the PhotoChooserTask to enable photo upload.

 

upload

 

Here are the files:

https://skydrive.live.com/redir.aspx?cid=4f1b7368284539e5&resid=4F1B7368284539E5!439&parid=4F1B7368284539E5!123

01
Feb
12

wp7 Collectionviewsource filtering

Having read a recent question on the App Hub Forums I decided to update my previous post on CollectionViewSource http://babaandthepigman.wordpress.com/2011/07/03/wp7-collectionviewsource-sorting-a-listbox/ to enable filtering.

So, I added a text box to enter the filter string,

 

cvs2

 

And the following code to implement the filtering…

     private void FilterBoxTextChanged(object sender, TextChangedEventArgs e)
     {
           
Source.View.Filter = o =>
                                    
{
                                        
var item = o as Item;
                                        
if (item != null)
                                         {
                                            
return item.Text.Contains(filterBox.Text);
                                         }
                                        
return false;
                                     };
        }

and we get filtered results…

 

cvs2-2

Here’s the updated project https://skydrive.live.com/redir.aspx?cid=4f1b7368284539e5&resid=4F1B7368284539E5!436&parid=4F1B7368284539E5!123

18
Jan
12

wp7 skydrive upload

Technorati Tags:

Download the sdk, which at the time of writing is here http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=28195

Next, head over to https://manage.dev.live.com/Applications/Index and add an application. This will provide you with an application Id and a client secret token. You also need to configure a valid redirect url as required by the OAuth handshake.

 

liveappreg

 

Add a reference to Microsoft.Live and Microsoft.Live.Controls. (included with the SDK)

Add a SignInButton to your page.

 

<Controls:SignInButton x:Name="signInButton" Height="120"
                                   ClientId="XXXXXXXXXXXXXXXX"
                                   SessionChanged="SignInButtonSessionChanged"
                                   Scopes="wl.skydrive_update"
                                   RenderTransformOrigin="0.5,0.5" 
                                   d:IsHidden="True">

 

Now, you should be able to click on the sign in button, get redirected to the live login page.  After logging in you will be required to give consent for the requested authorisation. This will look like this:

 

authorise 

We then wire up a handler to the SignInButton SessionChanged event and if the sign in was successful we will get a LiveConnectSession object passed in the event.

            if (e.Status == LiveConnectSessionStatus.Connected)
            {
                VisualStateManager.GoToState(this, "SignedIn", true);
                _liveConnectSession = e.Session;
            }

 

A LiveConnectClient object can be constructed from the session object and used to carry out standard operations, i.e. upload, delete, copy, etc.

 

Find the project here:

https://skydrive.live.com/redir.aspx?cid=4f1b7368284539e5&resid=4F1B7368284539E5!435&parid=4F1B7368284539E5!123

06
Aug
11

wp7 – custom control project template

I couldn’t locate a Visual Studio project template for creating a windows phone 7 custom control library. So….I decided to make one. It is pretty straight-forward to create one by hand but the second time the process becomes a bit tedious..

Since it is practically the same as creating custom controls in wpf and silverlight it has been well documented. Here’s a clear and recent, phone-specific write-up http://www.windowsphonegeek.com/articles/7-Mistakes-Developer-make-when-implementing-Windows-Phone-Custom-Controls which points out some common errors.

Anyway, here’s the installation instructions:

  1. Find the folder used by visual studio for ‘user project templates location’ (Navigate to Tools > Options > Projects and Solutions and it will be in the right pane – see image below) and download and copy this zip file to that folder.
  2. Extract all files

 

blogcustomcontroltemplate

 

(This should result in a further zip file called ‘WP7 Custom Control’ being extracted to a subfolder called ‘Silverlight For Windows Phone’).

Next time you open the create new project dialog there should be an entry for a ‘Windows Phone Custom Control Library’  as shown below:

 

blogcustomcontroltemplate2

 

which, when selected will result in a project structure illustrated below..

 

blogcustomcontroltemplate3

 

By the way, to create a project template simply create or locate a project to base the template on and select File > Export Template in Visual Studio. See http://msdn.microsoft.com/en-us/magazine/cc188697.aspx for further details.

 

Technorati Tags: ,,,,,,,,,,

Windows Live Tags: windows phone,wp7dev,custom control,template,Visual Studio,library,Developer,Windows,templates,Projects,Control
WordPress Tags: windows phone,wp7dev,custom control,template,Visual Studio,library,Developer,Windows,templates,Projects,Control

03
Jul
11

wp7 CollectionViewSource – sorting a listbox

A nice and flexible way to introduce filtering and sorting on a view model data collection is to use a CollectionViewSource. Here’s a quick example:

 

collviewsrc

 

Starting with a bound collection property like this…

 

        public ObservableCollection<Item> Items { get; set; }

        // Constructor
       
public MainPage()
        {
            Items =
new ObservableCollection<Item>
                        {
                           
new Item { Date = DateTime.Now.AddDays(-4), Name = "Item 1"},
                           
new Item { Date = DateTime.Now.AddDays(-3), Name = "Item 2"},
                           
new Item { Date = DateTime.Now.AddDays(-5), Name = "Item 3"},
                           
new Item { Date = DateTime.Now.AddDays(-8), Name = "Item 4"},
                           
new Item { Date = DateTime.Now.AddDays(-1), Name = "Item 5"},
                        };

            InitializeComponent();
            DataContext = this;
        }

Which is bound to a ListBox like the following:

            <ListBox x:Name="ListBox"
                    
Margin="0,0,-12,0"
                    
ItemsSource="{Binding Items}">
                <
ListBox.ItemTemplate>
                    <
DataTemplate>
                        <
StackPanel Orientation="Vertical" >
                            <
TextBlock Text="{Binding Date}"
                                      
TextWrapping="Wrap"
                                      
Style="{StaticResource PhoneTextExtraLargeStyle}" />
                            <
TextBlock Text="{Binding Name}"
                                      
TextWrapping="Wrap"
                                      
Style="{StaticResource PhoneTextSubtleStyle}" />
                        </
StackPanel>
                    </
DataTemplate>
                </
ListBox.ItemTemplate>
            </
ListBox>

We simply need to insert a CollectionViewSource object into the data binding chain. To do this we can instantiate a CollectionViewSource, set the Items collection to it’s Source property and bind to the CollectionViewSource’s View property. See below:

public System.Windows.Data.CollectionViewSource Source { get; set; }

        // Constructor
       
public MainPage()
        {
            Items =
new ObservableCollection<Item>
                        {
                           
new Item { Date = DateTime.Now.AddDays(-4), Text = "Item 1"},
                           
new Item { Date = DateTime.Now.AddDays(-3), Text = "Item 2"},
                           
new Item { Date = DateTime.Now.AddDays(-5), Text = "Item 3"},
                           
new Item { Date = DateTime.Now.AddDays(-8), Text = "Item 4"},
                           
new Item { Date = DateTime.Now.AddDays(-1), Text = "Item 5"},
                        };

            Source = new System.Windows.Data.CollectionViewSource();
            Source.Source = Items;

(Note: I am using the code behind here just for illustrative purposes. I would usually expose the CollectionViewSource from a View Model).

and the xaml changes to:

<ListBox Grid.Row="1" x:Name="ListBox"
                    
Margin="0,0,-12,0"
                    
ItemsSource="{Binding Source.View}">

Now, as a simple example of what we can do I attach two buttons with click handlers to enable sorting of the ListBox. So,

           <StackPanel Grid.Row="0"Orientation="Horizontal">
                <
ButtonContent="Asc"Click="AscButtonClick"></Button>
                <
ButtonContent="Desc"
                      
Click="DescButtonClick"></Button>
            </
StackPanel>

with the click handlers defined like this…

        private void DescButtonClick(object sender, RoutedEventArgs e)
        {
            Source.SortDescriptions.Clear();
            Source.SortDescriptions.Add(
new SortDescription("Date", ListSortDirection.Descending));
        }

        private void AscButtonClick(object sender, RoutedEventArgs e)
        {
            Source.SortDescriptions.Clear();
            Source.SortDescriptions.Add(
new SortDescription("Date", ListSortDirection.Ascending));
        }

So, what has this achieved? A simple sort of the Listbox, but also since I don’t need to sort my original list a ui-agnostic way to maintain the original data.

The project source can be downloaded here https://skydrive.live.com/?cid=4f1b7368284539e5&sc=documents&id=4F1B7368284539E5%21352

Technorati Tags: ,,,,,,,,,,,,,,,,,,,,
Windows Live Tags: CollectionViewSource,ObservableCollection,DataContext,ListBox,ItemsSource,Source,View,Note,code,Model,Grid,Horizontal,Button,Content,Click,Desc,SortDescriptions,Clear,SortDescription,ListSortDirection,purposes
WordPress Tags: CollectionViewSource,ObservableCollection,DataContext,ListBox,ItemsSource,Source,View,Note,code,Model,Grid,Horizontal,Button,Content,Click,Desc,SortDescriptions,Clear,SortDescription,ListSortDirection,purposes

07
Jun
11

wp7 record your own accelerometer data for testing

In the recent Mango developer tools for Windows Phone the device emulator has been updated to include an accelerometer simulation screen.

 

acc1

 

This enables passing data in real time to your application via the Accelerometer. Also, you can play back some recorded data, of which there is some sample ‘Shake’ data. So pressing Play will play back the recorded data.

The shake data is stored as xml from this location ‘<PROGRAM FILES>\Microsoft XDE\1.0\sensordata\acc’ in a file called ‘Shake’.  The format is very simple as can be seen from the screenshot below;

 

acc2

 

Now, the next bit happened by accident as I was trying to think of something simple to implement with sockets just so I could become familiar with the socket support on Mango. Anyway, I started by writing the obligatory client / server socket code. The server being a console app which listens for client connections on a tcp port.

Once connected, the client sends  accelerometer reading data over the connection to the server which saves it to xml in the required format.

 

acc3

 

So to record a file, start the server console app, then run the mango app on the emulator. Start the accelerometer tools…

acc4

 

…manipulate the input data using the pink blob on the tools in the required motion. The data will be sent via the Accelerometer interface in the phone app, across the socket connection to the console app which will save it to an xml file when the recording ends.

The resulting file will subsequently end up in the drop-down on the Accelerometer Tools ui;

 

acc5

 

Probably not the best way to record the data but it allowed me to play around with the socket api’s

Smile

Source code is here http://cid-4f1b7368284539e5.office.live.com/self.aspx/.Public/AccelerometerRecorder/AccelerometerRecorderServer.zip

Technorati Tags: ,,,,,,,,,,,,,,,
Windows Live Tags: wp7dev,Mango,tools,simulation,Shake,location,Microsoft,socket,client,server,code,port,connection,AccelerometerRecorder,sockets,emulator
WordPress Tags: wp7dev,Mango,tools,simulation,Shake,location,Microsoft,socket,client,server,code,port,connection,AccelerometerRecorder,sockets,emulator

24
May
11

wp7 pathlistbox

Since the new Mango developer tools were just released I wanted to write a quick post on PathListBox since I have been looking for an excuse to give it a try. PathListBox allows layout of list box items along an arbitrary path (see PathListBox). So, after installing the Mango developer tools http://www.microsoft.com/downloads/en/details.aspx?FamilyID=77586864-ab15-40e1-bc38-713a95a56a05&displaylang=en, I created a standard Windows Phone 7 project (targeting 7.1). I opened it in Blend and using the pen tool drew a path and removed any fill or stroke colours…

 

pathlistbox1

 

I then added a PathListBox from the tool box and in it’s property pane, under the Layout Paths section clicked the target icon next to ‘Select an object to use as a Layout path’, and then choose the path. Now any items subsequently added to the PathListBox will be positioned on this path.

 

I created a ViewModel class and bound it to the DataContext of the MainPage…

 

        public MainPage()
        {
            DataContext = new ViewModel();            
            InitializeComponent();
        }

 

The ViewModel and Items started out like the following:

 

public class ViewModel
{
    private int _count;
    public ObservableCollection<Item> Items { get; set; }

    public ViewModel()
    {
        Items = new ObservableCollection<Item>();
        AddItem();
        AddItem();
        AddItem();
        AddItem();
        AddItem();
        AddItem();
    }

    public void AddItem(object parameter = null)
    {
        Items.Add(new Item { Name = "Item " + _count++ });
    }

    public void RemoveItem(object parameter)
    {
        Items.RemoveAt(Items.Count - 1);
    }
}

public class Item
{
    public string Name { get; set; }
}

 

which gave some data to bind the view to.

I then bound the ItemsSource of the PathListBox to our Items list in xaml and edited the Distribution property to give an even layout along the path, as follows:

 

           <mec:PathListBox HorizontalAlignment="Left"
                             Height="100"
                             VerticalAlignment="Top"
                             Width="100"
                             ItemsSource="{Binding Items}">
                <mec:PathListBox.LayoutPaths>
                    <mec:LayoutPath SourceElement="{Binding ElementName=path}" Distribution="Even"/>
                </mec:PathListBox.LayoutPaths>
            </mec:PathListBox>

 

At this stage, running in the Emulator gave,

 

pathlistbox3

So, we need to tell the ListBox how to display each data item. We can do this in Blend by editing the PayjListBox’s ItemTemplate. I just added a TextBlock bound to the Name property of the Item class.

 

        <DataTemplate x:Key="DataTemplate1">
            <Grid>
                <TextBlock Text="{Binding Name}" />
            </Grid>
        </DataTemplate>

 

This gave,

pathlistbox4

 

Which is a fairly interesting list box, but what really brings it to life is adding a FluidMoveBehavior to the Layout Panel and then triggering some layout updates. I did this as follows:

Edit the PathListBox’s ItemPanel template in Blend and drag n drop a FluidMoveBehavior (from the Assets Pane) onto the PathPanel.

 

pathlistbox5

 

You can select the FluidMoveBehavior and edit some of it’s properties to control the nature of the transitions it will produce.

 

pathlistbox6

 

You must set the ‘Applies To’ property to ‘Children’ so that the transitions are applied to the children of the layout panel. In order to see the animations I added some buttons for sorting the list and adding and removing items from the list. I made use of the new Commanding support and added ICommand implementing properties on my ViewModel which I bound to the buttons.

 

            <StackPanel Orientation="Horizontal"
                        Grid.Row="1"
                        d:IsHidden="True">
                <Button Content="Sort"
                        Command="{Binding SortCommand}" />
                <Button Content="+"
                        Command="{Binding AddCommand}" />
                <Button Content="-"
                        Command="{Binding RemoveCommand}" />
            </StackPanel>
 
            SortCommand = new ProxyCmd(Sort);
            RemoveCommand = new ProxyCmd(RemoveItem);
            AddCommand = new ProxyCmd(AddItem);

 

Where ProxyCmd is just a class which implements ICommand by calling a delegate that you pass it. Also, the sorting was implemented using CollectionViewSource.

 

pathlistbox7

 

The result is a a pleasing, dynamic, fully functioning ListBox.

The source code is available here http://cid-4f1b7368284539e5.office.live.com/self.aspx/.Public/MangoPathListBox/MangoPathListBox.zip

 

 

Technorati Tags: ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

WordPress Tags: Mango,tools,PathListBox,items,path,FamilyID,Blend,tool,pane,Layout,icon,Select,ViewModel,DataContext,MainPage,InitializeComponent,_count,ObservableCollection,Item,AddItem,parameter,Name,RemoveItem,RemoveAt,Count,data,ItemsSource,Distribution,HorizontalAlignment,Left,VerticalAlignment,Width,LayoutPaths,LayoutPath,SourceElement,ElementName,Emulator,ListBox,PayjListBox,ItemTemplate,TextBlock,DataTemplate,Grid,Text,life,FluidMoveBehavior,Panel,Edit,ItemPanel,template,Assets,PathPanel,nature,Children,ICommand,StackPanel,Orientation,Horizontal,IsHidden,True,Button,Content,Sort,Command,SortCommand,AddCommand,RemoveCommand,ProxyCmd,Where,implements,Also,CollectionViewSource,result,Paths,transitions,animations,developer

15
Dec
10

WP7 UserControls

by Peter Daukintis

Since silverlight 2 we have had the concept of the UserControl which provides a simple way to compose a re-usable part of our user interface. This allows multiple uses of the same ui across an application which can be edited in one location. Expression Blend helps us out with the creation of UserControls…

I created a new Windows Phone Application project and found some of the standard application bar icons on my disk (here on my PC C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Icons\dark). I added a reference to Microsoft.Phone.Controls.Toolkit and added a WrapPanel to the Content grid on my page. I dragged all of the icons in, tidies up the layout to give this.

 

iconsmain

 

Now in Blend I right-click my WrapPanel and select ‘Make into UserControl…’ and Blend will create the files for me and reference the new UserControl on the page I created it from.

Now, if I make any edits to anything on my user control and flip back to a page that references it Blend will provide a visual cue that something has changed and I need to recompile to have the change propagated. It looks like this with an exclamation!

 

editedusercontrol

 

Just to prove to myself that this all works as expected I added a new Windows Phone Page to my app, dragged a ‘NavigateToPageAction’ behavior onto my main page header and configured it to navigate to my new page. Once you have compiled a user control Blend will make it available in the Assets panel under controls

 

usercontrolinblend

 

So, from there I dragged my usercontrol out onto my second page.

This is all very simple but you can go much further and add properties, events, event handlers, and code, etc in your code behind. Example solution can be seen here http://cid-4f1b7368284539e5.office.live.com/self.aspx/.Public/UserControl%20WP7/WP7UserControl.zip or here with the user control in a class library

http://cid-4f1b7368284539e5.office.live.com/self.aspx/.Public/UserControlInClassLibrary/WP7UserControlInClassLibrary.zip

Technorati Tags: ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
Windows Live Tags: UserControls,concept,UserControl,user,interface,location,Expression,Blend,creation,Application,disk,Program,Files,Microsoft,SDKs,reference,Controls,Toolkit,WrapPanel,Content,grid,Make,exclamation,Just,Page,NavigateToPageAction,header,Once,Assets,panel,events,event,code,icons,references,handlers
WordPress Tags: UserControls,concept,UserControl,user,interface,location,Expression,Blend,creation,Application,disk,Program,Files,Microsoft,SDKs,reference,Controls,Toolkit,WrapPanel,Content,grid,Make,exclamation,Just,Page,NavigateToPageAction,header,Once,Assets,panel,events,event,code,icons,references,handlers

21
Oct
10

Simple textbox validation wp7

Since wp7 is based on Silverlight 3 then input validation can be done (love or loathe it) via exceptions. Here’s a simple example…

        <Grid x:Name="ContentPanel" Grid.Row="1">
            <Border x:Name="errorBorder" Background="Red" Opacity="0"></Border>
            <TextBox Margin="8" 
                     Text="{Binding MyText, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 
                     BindingValidationError="ContentPanel_BindingValidationError">
                <TextBox.InputScope>
                    <InputScope>
                        <InputScope.Names>
                            <InputScopeName>Default</InputScopeName>
                        </InputScope.Names>
                    </InputScope>
                </TextBox.InputScope>
            </TextBox>
        </Grid>

 

Note that the Textbox is bound to a text property and NotifyOnValidationError and ValidatesOnExceptions properties have been set to true. Also, the binding will be triggered when the TextBox loses focus. Setting NotifyOnValdationError means that my event handler for BindingValidationError event will be called when a validation error is detected. Following from that, a validation error will be detected when my bound property setter (for ‘MyText’) throws an exception. Here’s the code for that….

 

   public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private string _myText;

        public string MyText
        {
            get { return _myText; }
            set
            {
                if (_myText != value)
                {
                    if (value.Contains("."))
                    {
                        throw new Exception("Cannot contain '.'");
                    }

                    _myText = value;
                    OnPropertyChanged("MyText");
                }
            }
        }

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            DataContext = this;
        }

        private void ContentPanel_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            errorBorder.Opacity = e.Action == ValidationErrorEventAction.Removed ? 0 : 100;
        }
    }

 

 

I haven’t been very creative with the visuals here…

Note that I have placed all of this code in the code-behind purely for convenience – I would usually implement this with a view model.




Follow

Get every new post delivered to your Inbox.