J2i.Net

Nothing at all and Everything in general.

New Hardware: Samsung Galaxy Tab

If you follow me on Twitter you'll know I've been looking for a new tablet device. I've made my decision. I was originally going to get a Windows tablet. But when I looked at the available tablets I found that the emphasis seems to be on making them smaller and lighter and as a consequence they are lower powered than what I have with longer battery life. I get pretty good battery life already, so there wasn't a big incentive for me to get a new Windows tablet just yet. Mine is good enough.

For a breif moment I considered the iPad 2 but the new unit looks to be an incremental upgrade from the original. So I'm leaving it alone.

Next on the list was an Android tablet. That's what I got, a Samsung Galaxy Tab. It's a nifty little device in it's own right. It's small enough to fit in one hand or the back pocket of some jeans (not that I recommend carrying that way, to many pick pockets around) but large enough to make for a good eBook reader. I was also pleased with how consistent it is with other Samsung devices. I'll be talking more about it (and another mobile operating system!) in the coming weeks.

Tracking High Scores on Windows Phone

Another frequent question I come across in the user forums is related to how some one implements local high scores. The question has come up frequently enough for me to conclude that its to the benifit of the community to have an implementation available that can be used in Silverlight or XNA that is ready to be used with very little setup.

So I've made a solution for others to use. By default the component will keep track of up to 10 high scores and will take care of loading and saving itself. If you add a score the component will take care of ensuring the score is in it's proper place and removing scores that are nolonger one of the top. For persisting the score information I've made use of the DataSaver<T> code from a previous blog post. I hope others will find the solution easy to use.

To get started with using the component add a reference to my component to your project. You'll want to instantiate HighScoreList passing an optional file name that it will use to save score information. It's possible to keep track of more than one high score list as long as your instances have different file names. One might want to do this if they keep track of scores in different modes separately from each other (Ex: a score list for Difficult mode, a score list for Easy mode, and so on).

HighScoreList _highScoreList = new HighScoreList("MyScores"); 

Upon instantiation the component will take care of loading any previous high scores without you doing anything more.

To add a score create a new instance of ScoreInfo and populate its PlayerName and Score fields. (There is also a ScoreDate field that automatically gets populated with the current date and time). Then use the AddScore(ScoreInfo) method on the HighScoreList instance to add it to the score list.

ScoreInfo scoreInfo = new ScoreInfo(){PlayerName = "Jack", Score = 1048576};
_highScoreList.AddScore(scoreInfo);

And that's it, there's nothing more for you to do. When you make that call the score gets added to the high score list, scores that are no longer in the top 10 (or what ever you set the limit to be) will fall off the list, and the list will automatically be persisted back to IsolatedStorage so that it is available the next time your game runs. Easy, right?

As a test project I've created a Silverlight application that allows you to enter new scores and see the behaviour of the component.

Score Keeper Screenshot

The main bits of the source code are below. First the ScoreInfo class which is nothing more than a serializable collection of three properties

/// <summary>
/// ScoreInfo contains information on a single score
/// </summary>
[DataContract]
public class ScoreInfo : INotifyPropertyChanged 
{

                
    // PlayerName - generated from ObservableField snippet - Joel Ivory Johnson
        private string _playerName = String.Empty;

    /// <summary>
    /// The name of the player that made this score
    /// </summary>
        [DataMember]
        public string PlayerName
        {
        get { return _playerName; }
            set
            {
                if (_playerName != value)
                {
                    _playerName = value;
                    OnPropertyChanged("PlayerName");
                }
            }
        }
        //-----

                
    // Score - generated from ObservableField snippet - Joel Ivory Johnson
        private int _score = 0;

    /// <summary>
    /// The score that the player made
    /// </summary>
        [DataMember]
        public int Score
        {
        get { return _score; }
            set
            {
                if (_score != value)
                {
                    _score = value;
                    OnPropertyChanged("Score");
                }
            }
        }
        //-----

                
    // ScoreDate - generated from ObservableField snippet - Joel Ivory Johnson
        private DateTime _scoreDate = DateTime.Now;

    /// <summary>
    /// The date and time that the player made the score. If this field is not 
    /// assigned a value it will automatically be assigned with the date and time
    /// that the score isntance was created
    /// </summary>
        [DataMember]
        public DateTime ScoreDate
        {
        get { return _scoreDate; }
            set
            {
                if (_scoreDate != value)
                {
                    _scoreDate = value;
                    OnPropertyChanged("ScoreDate");
                }
            }
        }
        //-----
    protected void OnPropertyChanged(String propertyName)
    {
        if(PropertyChanged!=null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #region INotifyPropertyChanged Members

    public  event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

And then the HighScoreList class, which is a collection class that contains the .

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.Serialization;


namespace J2i.Net.ScoreKeeper
{
    public class HighScoreList : ObservableCollection<ScoreInfo>, INotifyPropertyChanged    
    {
        static DataSaver<HighScoreList> MyDataSaver = new DataSaver<HighScoreList>();

        public HighScoreList()
        {
            
        }

        public HighScoreList(string fileName):this()
        {
            this.ScoreFileName = fileName;
            HighScoreList temp = MyDataSaver.LoadMyData(fileName);
            if(temp!=null)
            {
                foreach(var item in temp)
                {
                    Add(item);
                }
            }
        }
                
        // MaxScoreCount - generated from ObservableField snippet - Joel Ivory Johnson
        private int _maxScoreCount = 10;
        [DataMember]
        public int MaxScoreCount
        {
        get { return _maxScoreCount; }
            set
            {
                if (_maxScoreCount != value)
                {
                    _maxScoreCount = value;
                    OnPropertyChanged("MaxScoreCount");
                }
            }
        }
        //-----


                
        // ScoreFileName - generated from ObservableField snippet - Joel Ivory Johnson
        private string _scoreFileName = "DefaultScores";
        [DataMember]
        public string ScoreFileName
        {
        get { return _scoreFileName; }
            set
            {
                if (_scoreFileName != value)
                {
                    _scoreFileName = value;
                    OnPropertyChanged("ScoreFileName");
                }
            }
        }
        //-----

                
        // AutoSave - generated from ObservableField snippet - Joel Ivory Johnson
        private bool _autoSave = true;
        [DataMember]
        public bool AutoSave
        {
        get { return _autoSave; }
            set
            {
                if (_autoSave != value)
                {
                    _autoSave = value;
                    OnPropertyChanged("AutoSave");
                }
            }
        }
        //-----

        static int ScoreComparer(ScoreInfo a, ScoreInfo b)
        {
            return b.Score - a.Score;
        }

        public void SortAndDrop()
        {
            List<ScoreInfo> temp = new List<ScoreInfo>(this.Count);
            foreach(var item in this)
            {
                temp.Add(item);
            }

            if (temp.Count > MaxScoreCount)
            {
                temp.RemoveRange(MaxScoreCount - 1, (temp.Count) - (MaxScoreCount));
            }

            temp.Sort(ScoreComparer);
            this.Clear();

            temp.ForEach((o)=>Add(o));


        }

        public void Save()
        {
            if(String.IsNullOrEmpty(ScoreFileName))
                throw new ArgumentException("A file name wasn't provided");
            MyDataSaver.SaveMyData(this, ScoreFileName);
        }

        public void AddScore(ScoreInfo score)
        {
            this.Add(score);
            SortAndDrop();
            if(AutoSave)
                Save();
        }
        
        
        
        protected void OnPropertyChanged(String propertyName)
        {
            if(PropertyChanged!=null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}

Remember to set the Input Scope!

I was testing some code out for some one that was still in development. The code wasn't yet in complete form yet but even with that being said there was one thing that was annoying me about it. It wasn't taking advantage of InputScopes. To describe it breifly an input scope is a hint for the type of data that is to be entered into a text field. When the user gives focus to a text field the system will set the keyboard to the mode most appropriate for the type of data being entered. For numeric input scopes it will set the keyboard to numeric mode. For an e-mail input scope it will default to text and a key for the @ sign, and so on. For a full list of the input scopes you can see this page on MSDN.

Using InputScopes is easy. Within your XAML on the text boxes set the InputScope property to the name of the InputScope that specifies the type of data to be entered.

<TextBox InputScope="Number" />

<TextBox InputScope="EmailNameOrAddress" />

In addition to setting the input mode of the keyboard setting the InputScope also will let the system know whether or not to use its autocomplete dictionary. If you don't set the InputScope then it's up to the user to manually change the keyboard to the mode that is appropriate for what they are entering, and that can be down right annoying when there is a lot of text to enter!

Serializing the Unserializable

I came across a post in the Windows Phone developer forums that got me thinking for a moment. The poster had asked how to serialize a class that was not serializable. The class of interest was the StrokeCollection class. The solution for this problem has actually been around for a while but under different terms. If you pick up a design patterns book and look up Data Transfer Object (DTO) you'll see what I'm talking about. For the sake of those that don't have a design patterns book handy I'll describe the concept.

A DTO exists for the sake of storing data in an object that is suitable for crossing boundaries. More times than not when I see some one talking about a DTO it is for an object that is going from an application to a database. But it's not restricted to that scenario. For the sake of answering the question for the poster I can assume that he or she wanted to transfer the data to a file. The representation of the data in a file is also a form that is suitable for transfer over a wire.

To accomplish the task I made a few classes that have some (but not all) of the same properties as the classes I needed to serialize. I didn't need to replicate all of the properties because I'm not interested in saving all of the data that the class provides. As far as functionality goes the only thing that I've put on these classes is functions for converting from the DTO to the original class and vice versa. The StrokeCollection class uses a number of other classes to represent it's data. StrokeCollection caontains instances of Stroke, which contains instances of StylusPointCollection, and that contains instances of StylusPoint. I created a similar hierarchy with the members of that hierarchy marked as serializable (with the [DataContract] attribute). For saving and loading the data I've made use of the serialization code from a previous post.

    [DataContract]
    public class StrokeDto
    {

        public StrokeDto()
        {
        }

        public StrokeDto(Stroke source)
        {
            this.StylusPointDtos = new StylusPointDtoCollection(source.StylusPoints);
        }

        public Stroke ToStroke()
        {
            Stroke retVal = new Stroke();
            if(this.StylusPointDtos!=null)
                StylusPointDtos.ForEach((o)=>retVal.StylusPoints.Add(o.ToStylusPoint()));
            return retVal;
        }

        [DataMember]
        public StylusPointDtoCollection StylusPointDtos { get; set; }
    }

    public class StrokeDtoCollection: List
    {
        public StrokeDtoCollection()
        {
        }

        public StrokeDtoCollection(StrokeCollection source):this()
        {
            foreach(Stroke s in source)
            {
                this.Add(new StrokeDto(s));
            }
        }

        public StrokeCollection ToStrokeCollection()
        {
            StrokeCollection retVal = new StrokeCollection();
            this.ForEach((o)=>retVal.Add(o.ToStroke()));
            return retVal;
        }
    }

    [DataContract]
    public class StylusPointDto
    {

        [DataMember]
        public double X { get; set;  }

        [DataMember]
        public double Y { get; set;  }

        [DataMember]
        public float PressureFactor { get; set;  }

        public StylusPointDto()
        {}

        public StylusPointDto(StylusPoint source)
        {
            this.X = source.X;
            this.Y = source.Y;
            this.PressureFactor = source.PressureFactor;
        }

        public StylusPoint ToStylusPoint()
        {
            return new StylusPoint(this.X, this.Y) {PressureFactor = this.PressureFactor};
        }
    }
    public class StylusPointDtoCollection : List
    {

        public StylusPointDtoCollection(): base()
        {}

        public StylusPointDtoCollection(StylusPointCollection source): this()
        {
            var sourceList = (from point in source select new StylusPointDto(point)).ToArray();
            this.AddRange(sourceList);
        }

        public StylusPointCollection ToStylusPointCollection()
        {
            var retVal = new StylusPointCollection();
            this.ForEach((o) => retVal.Add(o.ToStylusPoint()));
            return retVal;
        }
    }

With my class hierarchy and the serialization code I was able to load and save the stokes in a few lines of code. 

 

//Save the Strokes
var valuesaveDto = new StrokeDtoCollection(myInkPresenter.Strokes);
_myInkSaver.SaveMyData(valuesaveDto,"MyInk.ink");


//Load the Strokes
var valueDto = _myInkSaver.LoadMyData("MyInk.ink");
myInkPresenter.Strokes = valueDto.ToStrokeCollection();


Screen Shot of Drawing Program

I've put together an example program (see link at top of article) that uses the code. Word of warning, I've not implemented any tombstoning code in it. But draw what eer you like and then click on the Save button. After you exit from the program when you go back into it you'll see your picture reload.

 

Simple Data Serialization on WP7

You've got a class that contains data that you want to be able to save and load in IsolatedStorage on Windows Phone 7.  How would you go about doing that? There is more than one way, but I wanted to share a generic solution for didactic purposes; I'm finding that many begininers like to start off with a single satisficing solution and brance off into specialized solutions later.  Let's say that you are starting off with a stereotypical Employee class. 

 

class Employee 
     public int EmployeeNumber { getset; } 
     public string Name { getset; } 
     public string Department { getset; } 

 

There are a couple of problems with this employee class that make it unsuitable for the type of serialization that will be used. First the class isn't marked as public. This is a requirement for the DataContract serializaer. Secondly the class needs to be marked as serializable and the properties to be serialized must be marked. We mark the class as serializable by giving it the [DataContract] attribute. Each property that needs to be serialized must be marked with the [DataMember] attribute.  When we apply these changes the class looks like the following. 

 

[DataContract] 
public class Employee  
{  
     [DataMember] 
     public int EmployeeNumber { getset; }  
     [DataMember] 
     public string Name { getset; }  
     [DataMember] 
     public string Department { getset; }  
}  

 

There's another requirement that the class already met that I didn't mention. The class needs to have a default constructor. Sicne we've not given this class a default constructor the runtime will provide one. Now that we have a serializable class we need a way to serialize it. The DataContractSerializer would be used to handle both serialization and deserialization of the class. In it's simplest form you only need to provide the type that the serializer will handle. So a serializaer could be created with the following code. 

 

DataContractSerializer mySerializer = new DataContractSerializer(typeof(Employee)); 

 

That serializer can be used to read or write your object to a stream such as a file stream, network stream, or memory stream. I've set forth to only save and read contents from a file stream. So I've made a generic class that contains most of the logic to do that. 

 

using System; 
using System.IO; 
using System.IO.IsolatedStorage; 
using System.Runtime.Serialization; 
 
 
public class DataSaver<MyDataType> 
    private const string TargetFolderName = "MyFolderName"
    private DataContractSerializer _mySerializer; 
    private IsolatedStorageFile _isoFile; 
    IsolatedStorageFile IsoFile 
    { 
        get 
        { 
            if (_isoFile == null
                _isoFile = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); 
            return _isoFile; 
        } 
    } 
 
    public DataSaver() 
    { 
        _mySerializer = new DataContractSerializer(typeof(MyDataType)); 
    } 
 
    public void SaveMyData(MyDataType sourceData, String targetFileName) 
    { 
        string TargetFileName = String.Format("{0}/{1}.dat", TargetFolderName, targetFileName); 
        if (!IsoFile.DirectoryExists(TargetFolderName)) 
            IsoFile.CreateDirectory(TargetFolderName); 
        try 
        { 
            using (var targetFile = IsoFile.CreateFile(TargetFileName)) 
            { 
                _mySerializer.WriteObject(targetFile, sourceData); 
            } 
        } 
        catch (Exception e) 
        { 
            IsoFile.DeleteFile(TargetFileName); 
        } 
 
 
    } 
 
    public MyDataType LoadMyData(string sourceName) 
    { 
        MyDataType retVal = default(MyDataType); 
        string TargetFileName = String.Format("{0}/{1}.dat", TargetFolderName, sourceName); 
        if (IsoFile.FileExists(TargetFileName)) 
            using (var sourceStream = IsoFile.OpenFile(TargetFileName, FileMode.Open)) 
            { 
                retVal = (MyDataType)_mySerializer.ReadObject(sourceStream); 
            } 
        return retVal; 
    } 
 

 

I've hard coded the folder name in which the data will be saved (feel free to save that). When using the class you only need to pass it the object to be saved and the name of the file that it will use. 

 

//declare instance 
DataSaver<Employee> myEmployeeDataSaver = new DataSaver<Employee>(); 
 
//read Usage 
var EmployeeData = myEmployeeDataSaver.LoadMyData("MyEmployeeDataFileName"); 
 
//save Usage 
myEmployeeDataSaver.SaveMyData(myEmployee,"MyEmployeeDataFileName"); 

 

That should be enough to get you started. I'm working on a much more complete explanation to be shared later. 

Double Precision Vector3

Download the code (2.90 KB)

 

I was working on an educational project using Windows Phone and XNA on the desktop (the phone will be controlling the desktop). The project involves demonstrating the laws of celestial mechanics. So the modeled entities have attributes with large values (ex: the mass of a planet in kilograms, the distance the planet is from its sun in meters, so on). In the Xna portion of the program the Vector3 class appeared to be a good fit for modeling a planet's position, velocity, acceleration, and so on. My only concern with Vector3 is the precision of the numeric type that it uses. It uses a single precision number. When I started my initial test I was seeing how small objects reacted on the earth's surface just to make sure that my gravity calculations were correct. Everything worked fine; the object would fall toward the earth with the expected acceleration. So I went straight from modeling a small object on the earth's surface to modeling the Earth's moon. That's when things broke down. The numbers coming back from the gravity calculations were all wrong. 

It turns out I was running into a precision problem. Floating point types have enough precision to hold the final results of my calculations, but not enough prevision to hold the large intermediate values during the calculations. There are three ways to solve this:

  1. Use a Vector class with a higher precision numeric type
  2. Copy values from Vector3 to doubles, perform calculations, copy results back to Vector3
  3. Perform my calculations using Astronomical Units (AU) instead of meters. 
I started with trying to copy values to double types before doing calculations first. That works, but I had concerns with the code getting messy and the overhead in coding that way. I thought about using astronomical units. But that would add an extra mental layer of complication. I think of calculations for gravity in terms of meters and trying to work in some other unit would likely lead to problems. There was no higher precision Vector3 class available. So last night I converted the Vector3 class to a double-precision version of itself that I named Vector3D.  A majority of the methods available on Vector3 are available on the Vector3D class. 
I replaced the Vector3 with the Vector3D class and everything worked as expected. 

I figure at some point some one else will run into this problem so I've posted a copy of this class (link at the top of this entry). If I need to add more functionality to this class I'll be updating the version at the above link to. 

WP7 Team Member Interviews

There were a couple of interviews with members of the Windows Phone 7 team that I thought were worth looking at. They were both short interviews. While they don't tell you definitively what is yet to come they do show that Microsoft is aware of many of the needs expressed by the community and it also explains why Microsoft has been so quiet

From the WMPoserUser interview with Brandon Watson.

WMPowerUser.com asked Brandon Watson some consumer oriented questions in a recent interview. I don't want to repost the entire interview here (you can head to their site to see that. But there were a few replies that I wanted to mention. When asked about Enterprise Scenarios Brandon mentions some of the needs of Enterprise LOB applications such as side loading or a private Marketplace and mentioned that Microsoft is working with Enterprise customers to ensure that they have what they need. He also mentions some popular request such as sockets and databases. While nothing commiting was stated it is good to see the Microosft is aware of features that developers want and need. From reading the interview it doesn't look like we will be seeing native code any time soon (and to that I am not complaining)

Interview with Loke Uei Tan and Tim Huckaby

In Loke Uei's interview he said something that explains why Microsoft has been so quiet about forthcoming information.

It's very frustrating when people talk to you and ask you when, why, how, and you can't really share it with them. Because there are so many people working in that division. Working really hard to ship a product. We just don't want to prerelease information. Some one might take it wrongly and cause a stir. We needed to have a proper cascde of information. And that's the reason we are keeping a lot of information internal for now.

Copy and Paste rolling out for Windows Phone

Microsoft promised Copy and Paste for first quarter 2011, and today they've started to make good on that promise. The update is rolling out to developer's first so that they can test their software and then it will roll out to consumers later. For developers interested in applying the update grab the Windows Phone Developer Tools January 2011 Update.

In the tools you will find updated reference assemblies and a new version of the Emulator that has copy and paste. Your existing applications do not need to be recompiled or changed to take advantage of this update. However, since this update will affect how a tectbox behaves you will want to ensure it doesn't interfere with any textbox interactions that you have designed. For example, if your textbox is inside of another control that accepts text input then the user could encounter difficulty when trying to select text in your application. If this occurs then you'll want to make an update to your application.

The copy and paste update is currently limited to being an update just to the text box. There isn't yet programmatic access to the clip board. But don't worry, that's coming later.

Begining WCF for Windows Phone Developers

I'm back in the USA from the Bahamas, a place where Internet Access cost me 0.50USD/minute (thus I hardly used it).

A few questions have come up in the Windows Phone developer forum centered around serialization and WCF. I've been working on an introduction to WCF for WP7 developers (though do to recent travel and holidays I'm not done with it yet) and am releasing it in parts. In this first part I touch on Serialization and create a simple WCF service. I'm starting off with desktop WCF projects and then will transition to Windows Phone 7 specifics. Because WP7 supports a subset of WCF I won't venture far into WCF functionality that isn't available on WP7.

Prerequisites

I'm writing this targetting the developer that is just getting started with Windows Phone development. The developer will have already have learned the C# development language and have become comfortable with the Windows Phone application model of their choice (Silverlight or XNA). A developer in my target audience doesn't necessarily have a strong web services background.  If you still need to get an understanding for Windows Phone 7 programming you might won't to check out this free learning material by Rob Miles.

Required Software

The software required for this article is Visual Studio 2010. The Express edition of Visual Studio that comes with the Windows Phone tools won't be sufficient; I'll be using som desktop programming examples in this article.

Why WCF

With the ubiquity of Internet access it's common for programs to rely on services hosted on other machines. Some times this is becaus edata consumed by the program is kept in some centralized location. Othertimes it is to distribute computational load. Having a machine on which to host a service also facilitates communication between different client instances such as Instant Messenger type interactions. What ever your reason there are a lot of scenarios for which programs may need to communicate with other machines.

Communication among different clients can be implemented in a number of different ways. Clients may communicate with a service over raw socket connections in which they send messages to the server and receive data in a format completly authored by developers. Or a client may communicate using HTTP web request, much like your browser does. It is even possible for clients to use e-mail protocols for sending messages to other services. The number of ways in which communication could be implemented is countless. What ever the method you choose it will be necessary for both the client you are developing and the service that is providing some functionality agree on the formats used for the data.

WCF, or Windows Communication Foundation provides the functionality that a developer can use to quickly implement communication between services and clients. Instead of being burdened by implementing communication at the socket level WCF allows you to specify how communication will occur in higher level terms and will take care of managing communication channels that conform to what you've specified. You can specify that you want communication to occur over certain protocols (many of which are standards complient) along with marking which elements of data or functionality will be exposed to the end user. WCF will take care of converting your data elements into a format that can be transfered ofer the connection and will take care of reassembling the new objects on the other side of the connection.

Serialization

Whether you are sending data over a network connection or saving it to storage your data needs to be serialized. Serialization is simply converting data to a format that is appropriate for these purposes. At first one may wonder why the data needs to be converter. After all the data is nothing more than bits in memory, and bits can be transmited. But without conversion thos bits may not have much meaning if transmited in an unconverted format. The bits could contain the name of a file that doesn't exists on the remote system. Those bits could contain a pointer that may not point to the same item of data on another machine (or they may not point to any relevant data on the same machine during a different session!). Also some data may not need to be transmited or saved. If I made a class representing a rectangle I may decide that I only need to serialize the Width and Height members but not the Area member (since I can always recalculate it from the other two members).

Classes that serializer our data are called serializers. The two serializers that I will discuss here are the DataContractSerializer and the XmlSerializer. A number of data types are already serializable. These include the various numeric types (double, int, byte, float and so on), string, and arrays composed of these data types. We don't need to do any extra work to be able to serialize these. It's the complex data types for which we need to do some more work. Let's start with a stereotypical employee class.

class Employee
{
   public int     Number { get; set; }
   public string  Name { get; set; }
   public string Position { get; set; }
}

Without a serializer if you wanted to write entities of this type to a file you would need to decide on some way of delimiting your data and write code to place each value in your file. To read from the file you would also need to write code that would load the values from the files in the same order. If there were a change to your data type you would also need to make changes to your code for reading and writing. That amounts to a lot of busy work for a result that is in no way intelectually rewarding nor is it productive. When using a serializer things are much simpler. One only needs to instantiate a serializer telling it what type of data it will be serializing and then use the serializer to read or write the stream. The following code demonstrates what must be done. Note that this code is written to run on a desktop so that we can more easily get to the resulting file.

var e = new Employee()
            {
                Number = 515148, 
                Name = "Joel Ivory Johnson", 
                Position = "Owner"
            };

XmlSerializer employeeSerializer = new XmlSerializer(typeof(Employee));
using(StreamWriter sw = new StreamWriter("employeeData.xml"))
{
    employeeSerializer.Serialize(sw,e);
    sw.Close();
}
            

Running this code will result in an error though. The error will say that Employee is inaccessible due to its protection level. To correct this Employee must be declared as public and then the code will work. The program's resulting file will be found in it's directory and it's content looks like the following

<?xml version="1.0" encoding="utf-8"?>
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Number>515148</Number>
  <Name>Joel Ivory Johnson</Name>
  <Position>Owner</Position>
</Employee>

What if I have a property on the class that cannot be serialized? To invoke this senario I'm adding a new property of type IntPtr which is undoubtedly not serializable.

public class Employee
{
    public int Number { get; set; }
    public string Name { get; set; }
    public string Position { get; set; }
    public IntPtr X {get; set; } //This will not serializae
}

Making the change will result in an error message stating "There was an error reflecting type 'Employee'."" I don't want the pointer element serilized. By placing the [XmlIgnore] on the property and all will be well again.

There are a number of other attributes that can be placed on a class being serialized with the XmlSerializer. I won't discuss those within this article but mention it so that those that wish to have control over the resulting Xml know that there are additional options.

DataContractSerializer

The DataContractSerializer appears to work like the XmlSerializer at first glance. Let's take a look at the source for the same program if it used the DataContractSerializer instead of the XmlSerializer along with its output.

<Employee xmlns="http://schemas.datacontract.org/2004/07/J2i.Net.Example01.DataContractSerialization" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Name>Joel Ivory Johnson</Name>
  <Number>515148</Number>
  <Position>Owner</Position>
  <X xmlns:a="http://schemas.datacontract.org/2004/07/System"><value i:type="b:long" xmlns="" xmlns:b="http://www.w3.org/2001/XMLSchema">0</value></X>
</Employee>

The data contract serializer was able to serialize the X member, but I don't want that element serialized. To solve this problem I can add the [IgnoreDataMember] attribute to the code. There's something missing though. Typically if you are designing a class to be used by the DataContracySerializer it will be decorated with the [DataContract] member. If you add the [DataContract] attribute to the class and run it again we'll end up with an empty XML files. While the XmlSerializer is an opt-out serializer (it will try to serialize everything unless told to do otherwise) the DataContractSerializer is an opt-in serializer (It won't serialize anything unless a field is marked otherwise). So to correct this we need to add [DataMember] to each one of the fields that we want serialized. In general you'll want to have some control over how your class is serialized, so serialization with the [DataContract] attribute is preferred.

The Service Contract

While the Data Contract allows you to declare constructs used for passing data arount the Service Contract let's you make declarations on functionality that will be provided. Like the data contract you will decorate a class with attributes. But instead of specifying what data is available to external entities the attributes will specify what functionality is available to external entities. For the sake of cleanly separating the specification for functionality provided from the implementation of that functionality I'll be using interfaces to declare functionality. Of course the implementation for that functionality will be in a class that inherits from that functionality.

To get started let's make a simple service that has a few pieces of simple functionality. I'll call this our Mathimatics service. This service can take two numbers and either multiply them or return the difference between the two numbers. Since the data types being passed around are simple  won't need to concern ourselves with data contracts. To get started I'm creating a Windows class library that will contain the interface that defines the service contract and a class that implements the service. The interface is decorated with the [ServiceContract] attribute and the methods on the interface are decorated with the [OperationContract] attribute.

[ServiceContract]
public interface IMathimaticsService
{
    [OperationContract]
    double Multiply(double arg1, double arg2);

    [OperationContract]
    double Difference(double arg1, double arg2);
}

class MathimaticsService: IMathimaticsService
{
    public double Multiply(double arg1, double arg2)
    {
        return arg1*arg2;
    }

    public double Difference(double arg1, double arg2)
    {
        return Math.Abs(arg1 - arg2);
    }
}

The code will compile just fine but in its present state you can't run it. You could create another project and add the assembly produced by the above as a reference, but that would be going against the point of a service. With a service you want your functionality on one machine or process and the client using the functionality is generally in another machine or another process. To make use of this code we'll actually need two more projects. We need a project that will host the functionality and another project that will make use of the functionality. The service can be hosted in just about any Windows application; web application, Windows Form application, console application, and so on. Though generally one will dichotomize the hosting options to web or desktop.

I'll use a console application to host the service for now. There's still some more decisions to be made. A WCF service must always have three things defined when it is hosted; it must have an address, a binding, and a contract. Some call this the "ABCs of WCF" to make it easier to remember. The address will be the machine name or IP address along with the port over which the service will communicate. In most of the examples that follow the address will be localhost:8123. Though when running a client from an actual Windows Phone you'll want to have your computer name in that place. The binding defines how communication will occur. Presently Windows Phone only supports HTTP based communication. So I'll onl be using basic HTTP binding (HTTPS is also supported, but I won't cover setting up your machine to do secure communication). We've already covered what a contract is.

What's an endpoint?

The console application will instantiate a new ServiceHost with the our address and set the binding for it. We want other potential clients to be able to inquire about our services contracts. So we'll need to add a metadata exchange endpoint. With the metadata endpoint added other development tools will be able to look at our service definition and generate code to make the service easier to use for the developer. Without it the developer has no way to know what functionality is available short of it being communicated through some other means. With all of the above defined the only thing left to do is open the communications channel by calling ServiceHost.Open(). The process will need to stay alive so that the service can continue to be available and then we should free up the service's resources by calling ServiceHost.Close().

static void Main(string[] args)
{

    ServiceHost myServiceHost = new ServiceHost(typeof(MathimaticsService),
        new Uri("http://localhost:8123/MathimaticsService"));

    ServiceMetadataBehavior myBehavior = new ServiceMetadataBehavior(){HttpGetEnabled = true};
    myServiceHost.Description.Behaviors.Add(myBehavior);
    myServiceHost.AddServiceEndpoint(typeof (IMathimaticsService), new BasicHttpBinding(), String.Empty);
    myServiceHost.AddServiceEndpoint(typeof (IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(),
                                     "mex");
  myServiceHost.Open();


    //Keep the service from immediatly terminating by waiting on the user to press the Enter key
    Console.WriteLine("Press [Enter] to close");
    Console.ReadLine();

    myServiceHost.Close();

}      

While it would work, there's something I don't like about the above code. What would I need to do to move the code to a different machine or if I needed to host the service on a different port? I would need to change the code, recompile it, and redeploy it. That's no good. I could move the information on the port and address to an external file and read it at run time so that the program is nolonger bound to compile time settings. Microsoft has already included support to do this with the App.config file.  Covering how App.config works is beyond the scope of this writing so what I discuss here in a minimum. I've added a new item to my services host project named App.config. When the project is compiled this file will be copied to a file that has the same name as the executable with .config appended to the end.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="J2i.Net.MathimaticsService" >
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8123/MathimaticsService"/>
          </baseAddresses>
        </host>
        <endpoint address="" binding="basicHttpBinding"
                  contract="J2i.Net.Example02.ServiceContractExample.IMathimaticsService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

WCF is already capable of pulling this information from the App.config and using it. The code for our service is greatly simplified.

static void Main(string[] args)
{
    ServiceHost myServiceHost = new ServiceHost(typeof(MathimaticsService));
    myServiceHost.Open();

    Console.WriteLine("Press [Enter] to close.");
    Console.ReadLine();

    myServiceHost.Close();
}

Physics 101 Part 1 of N : Acceleration

Physic 101: Acceleration

When I was in college since I was going after a B.S. of Computer Science I was required to take the calculus based physics classes (those going after a B.A. of Computer Science could take the Algebra based versions instead). Because of some conversion complications with the school changing from the quarter system to the semester system I had to take a full year of physics classes to ensure I didn't loose credits. Since then I've used the math I've learned there for reasons of personal curiousity (though I must admit I've not had the frequent desire to do any calculations around accelerating electrons or mass/energy conversion).

It didn't occur to me until a few weeks ago that I should share this knowledge. I'll stick with talking about mechanics and leave the thermodynamics and quantum physics out of the discussion for now, and all of my code examples will run on WP7 (though they may also work on the Xbox 360 and PC). Let's start with talking about Acceleration.

A word about measurement units. I live in the USA and here we use English units such as inch, foot, mile, pound, and ton. These units don't seem to have much to do with each other and tend to complicate the math that involves these units. The SI units work out much nicer. For those that live in much of the rest of the world this may conform to the way you already do things. For those living in the USA I hope you don't mind conforming to this different way of doing things. But I just plan to avoid using the English system of metrics all together (imagine if the engineers at Lockheed Martin had done the same thing!).

Acceleration

Let's say I told you to create a Windows Phone project that will accelerate a red dot on the screen. Using your rendering technology of choice you position the red dot on the screen and start moving it at a constant rate in some direction. While that works, it doesn't look natural. Acceleration in the real world is usually gradual. An object that accelerated from 0 km/h to 60 km/h also traveled at intermidiate speeds between 0km and 60km. Let's take a look at how acceleration works and then use that to implement a more natural looking program.

Exactly what is acceleration? Accceleration is a change in velocity. Velocity is a combination speed and direction. If you are travelling on a straight road at 60 km/h that information alone doesn't describe your velocity. It only describes your speed. If you are said to be travelling at 60 km/h on a straight road heading north then your velocity has been described (at least within a 2 dimensional sense. I'm ignoring changes in elevation). If you change either your speed or your direction your velocity is changing. Speeding up, slowing down, or turning the steering wheel will cause your vehicle to experience acceleration.

If you increase your speed from 60 km/h to 80 km/h in 5 seconds without changing direction you've changed your speed by 20 km/h. Assuming your changed your speed at a constant rate during that 5 seconds you accelerated by 4 km/h per second.

An astute observer may have noticed that there are two units of time expressed above: the hour and the second. For the sake of consistency we can convert the change in speed from km/h to m/s. Our change in 20 km/h is equal to a change of 55.4 m/s (feel free to check my math here and or anywhere else in this article and inform me if I make any mistakes). So we can now say the rate of accelerate was 11.1 m/s per second (also expressable as 11.1 m/s^2). Technically there's a direction component to the acceleration. When one doesn't state the direction component then it is assumed to be in the same direction in which the object is already travelling. If the acceleration is negative then it is assumed to be in a direction opposing to that in which the object is travelling.

With the above I've discussed enough for some one to model acceleration. In making use of the existing XNA classes I could use a Vector3 to represent the position of an object in three dimensional space. To represent its velocity I can also use a Vector3. The X, Y, and Z values on the Vector3 will indicate how many units the body moves along the X, Y, and Z axis in a second. The rate of acceleration along the X, Y, and Z are once again representable with a Vector3.

public class Body
{
    public Vector3 Position;
    public Vector3 Velocity;
    public Vector3 Acceleration;

    public void ApplyVelocity(float seconds)
    {
        Position += seconds*Velocity;
    }

    public void ApplyAcceleration(float seconds)
    {
        Velocity += seconds*Acceleration;
    }
}

If you've ever taken any courses in calculus then you may recognize velocity as being a first order derivitive of position with respect to time. Acceleration is a first order derivitive of velocity with respect to time, or a second order derivitive of position. It's possible to have a third order element to describe changes in acceleration (I can think of some scenarios involving propulsion engines to which this would apply) but I won't go that far in any of these example.

It is clear in the above code that I am using seconds as my units of time. You can interpret the units of distance to be what ever you want (meters, feet, pixels, yards, whatever). However one decides to map the numbers to the physical world is of no impact to the meaning of the examples. With the above code if I give an object a position, a velocity, and acceleration we can then simulate it's movement by letting the velocity get adjusted by the acceleration (ApplyAcceleration) and then applying the velocity to the position (ApplyVelocity). Rather than manipulate my bodies independently I'll create a world in which to put them and will manipulate them all at once through this world. Since my world will be a collection of bodies I find it appropriate to derrive my world class from a List base.

public class World: List<Body>
{
    public float Width { get; set;  }
    public float Height { get; set;  }

    public World()
    {   
    }

    public void Step(float seconds)
    {
        foreach (var b in this)
        {
            b.ApplyAcceleration(seconds);
        }
        foreach (var ball in this)
        {
            ball.ApplyVelocity(seconds);
        }
    }
}

The Width and Height members on my world have no impact on the logic but are only there for scaling the world on a display (elements that move outside of the world's height or width are not gauranteed to be displayable on the screen, but those within the area of the world will always be rendered).

With this simple implementation it's possible to simulate acceleration. Let's take a look at the XNA source in which I host my two classes.  In addition to the declarations that one get's in an XNA project I've added a few more to the Game1 class.

private World _myWorld;         //For manipulating the elements of my world
private float _worldScale;      //for scaling the world up/down to fit on the screen
private Vector2 _worldOffset;   //for centering the world on the screen
private Texture2D _ballTexture; //an image of a ball to represent the body

In the constructor for the game I need to instantiate my world and add some bodies to it. I'm adding bodies with three types of movement. The first body will have a velocity but zero acceleration. So it will move at a constant speed. The second body will accelerate in the same direction as its initial velocity. So it will speed up. The third object will have a velocity causing it to move up and to the right but it will accelerate in a downward direction. The path that this body follows will conform to what many know as projectile motion.

_myWorld = new World(){Width = 320, Height = 240};
//Constant Motion Body
_myWorld.Add(new Body(){
        Position = new Vector3(10, 70, 0),
        Velocity = new Vector3(0,0,0),
        Acceleration=new Vector3(3.0f,0f,0)
    });

//Body accelerating in same direction as movement
_myWorld.Add(new Body() { 
        Position = new Vector3(10, 140, 0), 
        Velocity = new Vector3(20.0f, 0f, 0), 
        Acceleration = new Vector3(0,0,0)
    });

//Body accelerating in direction not parallel to initial velocity.
// will follow a projectile path.
_myWorld.Add(new Body() { 
        Position = new Vector3(0, 0, 0), 
        Velocity = new Vector3(45.0f, 60f, 0), 
        Acceleration = new Vector3(-1, -9, 0) 
    });

While loading the texture I also calculate a scale factor and offset so that the world will be centered on the screen. With the code written this way it is less dependent on the physical resolution of the device on which it is run. I could achieve more resolution independence if I used a vector image of a ball instead of the bitmap. But for this example the effort to do that isn't outweight by the benefit for my immediate purposes.

protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);

    float width = GraphicsDevice.Viewport.Width;
    float height = GraphicsDevice.Viewport.Height;

    var widthScale = width/_myWorld.Width;
    var heightScale = height/_myWorld.Height;
    if(heightScale<widthScale)
    {
        _worldScale = heightScale;
        _worldOffset = new Vector2((width-((int)(_myWorld.Width*heightScale)))/2 ,0);
    }
    else
    {
        _worldScale = widthScale;
        _worldOffset = new Vector2(0, (height- ((int)(_myWorld.Height * widthScale))) / 2);
    }


    
    _ballTexture = Content.Load<Texture2D>("canonBall");

}

In the Update method only contains a single new line beyond what is already present in a new project. The line that I have added makes a call so that the World instance will update the bodies' velocities and positions.

protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        this.Exit();

    _myWorld.Step((float)gameTime.ElapsedGameTime.TotalSeconds);

    base.Update(gameTime);
}

Lastly I need to render the world to the screen. I've made a function to map the coordinates within my world to the coordinates to the screen coordinates based on the scale factor and offset calculated earlier. It is used within the Draw method when rendering the bodies.

Vector2 MapPosition(Vector3 source)
{
    Vector2 retVal = new Vector2();
    retVal.X =  source.X*_worldScale + _worldOffset.X;
    retVal.Y = (_myWorld.Height - source.Y*_worldScale) + _worldOffset.Y;
    return retVal;
}

protected override void Draw(GameTime gameTime)
{
    
    GraphicsDevice.Clear(Color.Black);
    spriteBatch.Begin();
    foreach (var body in _myWorld)
    {
        var newCoord = MapPosition(body.Position);
        spriteBatch.Draw(_ballTexture,newCoord, Color.White);
    }
    spriteBatch.End();
    base.Draw(gameTime);
}

It is easier to see the program running then it is to infer how it operates from static images. So I've recorded the program in action and have uploaded it to YouTube. And motivated by the "because I can!" justification I've also created the solutions so that the example program will run on the PC and the Xbox 360 in addition to running on Windows Phone.

No talk of acceleration would be complete without talking of Newton's second law of motion. The second law of motion describes the relationship between an objects mass, the force applied to that mass, and the object's change in motion. The mathimatic expression for this relationship is F=ma. F is the force applied to the mass. Like velocity and acceleration Force also has a direction component. Even without placing real units of force or mass in the equation there's a few things that can be infered from this relationship. If we rearrange the expression to F/m=a (which is just a different expression for the same relationship) then we can see the difference that the same amount of force would have on objects of two different masses. If we had one object that weighed 12 kilograms and another that weighed 6 kilograms and applied the same amount of force to both we would find the 6 kilogram object would accelerate at twice the rate as the 12 kilogram object. I see this concept employed most often in games in which the player can customize a vehicle and change parts that have various impacts on the vehicle's mass or the engine's strength (force).

The SI unit of force is the Newton (guess who that is named after). A Newton is defined as the amount of force needed to accelerate one kilogram of mass at a rate of a meter/second^2. If you held a kilogram of mass in your hands under the influence of gravity it would exert a force of about 9.81 Newtons downwards. Now let's say you take a coin and apply force to it to slide it across your desk. Once it is no longer under the influence of you pushing it the coin will begin to slow down. This is because of friction. There are usually several different types of friction applied to a moving body. That is a discussion that is deserving of a post on its own. So for now I will bring this post to a close and in the next one I'll continue with either Friction of Gravity.