Apr 17 2012

Invoking through the Dispatcher on Windows Phone and Metro

Category: Desktop and Server | MobileJoel Ivory Johnson @ 09:26
Note: : Between the time that I wrote this and final release there were changes to the Windows Store Runtime. InvokeAsync nolonger exists. It has been replaced with RunAsync. Change noted below.

On the Windows Platforms there is a rule that you cannot modify UI elements from secondary threads. On Microsoft's XAML based platforms there is a member that exists on most UI objects called the Dispatcher that can be used to marshal a call to the proper thread.

On Windows Phone 7 and Windows 8 the way you go about calling this thread differs. I was recently working with some code that needed to compile for both platforms and wanted to minimize the amount of code that had to be wrapped in conditional compilation blocks. To do this I made a single method to handle my dispatching. The method itself contains conditional compilation blocks but because of this method I didn't need the blocks when I needed perform operations on the UI thread.

public void DispatchInvoke(Action a)
{
#if SILVERLIGHT
    if (Dispatcher == null)
        a();
    else
        Dispatcher.BeginInvoke(a);
#else
    if ((Dispatcher != null) && (!Dispatcher.HasThreadAccess))
    {
        Dispatcher.InvokeAsync( //RTM change
        Dispatcher.RunAsync(
                    Windows.UI.Core.CoreDispatcherPriority.Normal, 
                    (obj, invokedArgs) => { a(); }, 
                    this, 
                    null
         );
    }
    else
        a();
#endif
}

The code will compile for both Windows Phone 7 and Windows 8 Metro without any alterations. Using the code is the same regardless of which of the two platforms that you are using.

DispatchInvoke(()=>
  {
    //your operations go here
    TextBox1.Text="My Text";
  }
);

Tags: , , ,

Oct 11 2011

What Does Windows 8 Mean for Windows Phone Developers?

Category: Desktop and Server | MobileJoel Ivory Johnson @ 01:24

It was only a few weeks ago that Windows 8 was unveiled at the Build conference. At first glance it looks a lot like Windows Phone with heavy use of the Metro visual language. The only part of the system that hasn't had the Metro touch is the desktop (unlike previous versions of Windows the Desktop is not something that is always running). The Start menu looks like the Windows Phone start screen only it scrolls horizontally instead of vertically. The only mention of Silverlight is that you could still use it in Desktop mode for backwards compatibility, but the Metro [default] instance of IE would run no plug-ins, including Silverlight. The programming model also is not based off of Silverlight or the Desktop .Net runtime. Its based on something new called WinRT (Windows Runtime). 

At first glance this is something that has concerned Silverlight and Windows Phone developers. At first glance some one might come to the conclusion that the skill in which he or she has invested has become second class in Windows 8. Is Silverlight really getting killed off? What's going to happen for the Silverlight based Windows Phone?

I don't know the future any more than the next person, but what I saw at Build isn't something that raised concern. I found it to be rather reassuring. Before I explain why let me grant the elephant in the room, the rumor that Silverlight is going to be dead. I don't believe this rumour. For years people have predicted that certain Microsoft Technologies were dead (DirectX, .Net, and many other technologies that we still use today). But I'll grant it anyway so that we can explore what seems to be a popular concern. 

Let's assume that next year Microsoft announces that it is going to sunset Silverlight and toss out the Windows Phone programming model in favour of the Windows 8 programming model. What does this mean for the skills that you have developed? Are they now useless? You've been developing skills in C#/VB, XAML, asynchronous programming, and some APIs that were specific to Silverlight and Windows Phone. Let's look at how each one of these will contribute to your Windows 8 development. 

Languages: C# and VB

C# and VB are still being used on Windows 8. If you've been using these languages you can continue to use them. Additionally if you know C++ or have algorithms that had been written in C++ you'll be able to port them over to Windows 8. Windows 8 also supports JavaScript as a programming language too. 

XAML

XAML is still used on Windows 8 for building your UI. Many of the elements you've become familiar with are present in addition to some new ones. No huge changes there. 

Asynchronous Programming

One of the challenges for developers that were new to Silverlight was that task that one may have been used to doing synchronously are only available as asynchronous calls. On Windows 8 you'll find that many of the tasks that were asynchronous in Silverlight and Windows Phone are still asynchronous. Additionally other APIs have been made asynchronous, including File IO. 

The Familiar and What This All Means

You'll come across APIs that look similar of not identical to what you've seen in Windows Phone and Silverlight. Windows 8 has the concept of an application getting tombstoned, specifying the permissions it needs, and so on. Windows 8 Metro applications will only be distributed through the Marketplace. Doesn't all of this sound familiar. If you are a Windows Phone developer it should. You've already got a head start on Windows 8 development. This is far from the doom and gloom picture that some stories would have some one believe. 

If you want to dive into Windows 8 programming the 64-bit development images are available for download. I suggest running them on real hardware. I tried them in the emulator VirtualBox and it's just not the same experience there. 

Tags: , , ,

Sep 27 2011

Windows Phone 7.5 (Mango) Availability

Category: Joel Ivory Johnson @ 05:46

Mango is starting to roll out! It was several months ago that Microsoft made known that Mango would be available this fall, though when this fall had never been specified. The first day of fall was a few days ago and Microsoft is making good on their promise with Mango rolling out to some devices as early as today. While the Mango BETA had been out for some time there are some questions that are now answered with the final release.

Microsoft is going to start pushing the update to a small number of customers and gradually ramp up the availability. Most customers will have access to Mango by the end of October. Be sure to check the Where's My Update page to know when the Mango deployment begins for your network.

The availability and cost of Internet Connection Sharing will depend on your carrier. It will only be available on new Mango devices. The previously existing devices won't be getting the feature. Keyboards for additional languages may be available on some devices, but the underlying language for a device will still be the same as it was when it was purchased.

Information from the new OS release is still being made known, so I'll be making updates to this page as I encounter them.

Tags: , ,

Sep 10 2011

Passing thoughts, video effects on Windows Phone

Category: MobileJoel Ivory Johnson @ 08:10

Some years ago I saw the movie "A Scanner Darkly." There isn't much to talk about as much as the plot goes, but the visuals of the movie were unique. The movie was done with real actors but it the look of everything was as though it were drawn like a cartoon.

I thought about making an application that would allow some one to produce a similar effect in real time (or close to it) using a phone's camera. I thought I would be able to implement it with the K-means algorithm operating within color space (I will do another post on the details of this). Before diving into this task I needed to make sure that the phone was capable of doing this. I started by taking a look at Windows Phone and these were the main things that I needed to be able to satisfy:

  • Is real time access to the camera available
  • Can I render video frames to the screen at a rate
  • Can the phone provide the computational capability to quickly do the image processing

One of the new capabilities that comes with the Mango update to Windows phone is access to the camera. In addition to getting information from the camera through tasks (which was available with the initial release of Windows Phone) Microsoft has granted developers the ability to paint a surface with a live feed from the camera, capture a video from the camera, capture a frame from the preview buffer, and take a photograph (without user interaction) from the camera. Let's examine how each one of those features does or does not contribute towards my goal and the program design.

Because of the the nature of my goal (to work with video) the Windows Phone Tasks (Camera Capture and Photo Chooser) won't work for my program. They both require user interaction for each frame captured. That's no way to work with video.

What about taking pictures automatically? This doesn't quire work either. Picture taking is slow. In general you'll find that the CCDs used in many digital devices are now able to capture and transmit the information from a full resolution photograph as quickly as they do when sending lower resolution video.

The ability to display the video buffer on screen looks promising. With it you can display what ever the camera sees. However this capability is only for displaying the camera's "vision" on the screen and rendering over it (such as in augmented reality).

This leaves two methods left: using the preview buffer and using the phone's video capturing abilities. Using the phone for video capture gives the highest framerate but it ceases to be real time. I'd be fine with that. That would just mean that some one would need to film a video and then it would play back with the video affect applied. But that would also require that I decode the resulting MP4 video myself (there's no video codec available to do this). So the preview buffer seemed like the best option. So I did a quick test to see how many frames I could capture per second (before performing any processing).

 

public MainPage()
{
    InitializeComponent();
    _camera = new PhotoCamera();
    _camera.Initialized += new EventHandler<CameraOperationCompletedEventArgs>(_camera_Initialized);            
    videoBrush.SetSource(_camera);                 
}

void _camera_Initialized(object sender, CameraOperationCompletedEventArgs e)
{
    var x = _camera.PreviewResolution;
    int pixelCount = (int) (x.Width*x.Height);
    buffer = new int[pixelCount];
    _camera.PreviewResolution
    Dispatcher.BeginInvoke(() => { });

    Thread ts = new Thread(new ThreadStart(GrabFrames));
    ts.Start();
}

void GrabFrames()
{
    _camera.GetPreviewBufferArgb32(buffer);
    var startDate = DateTime.Now;
    for(int i=0;i<100;++i)
    {
        _camera.GetPreviewBufferArgb32(buffer);
    }
    var endTime = DateTime.Now;
    var delta = endTime.Subtract(startDate);
}

The results I got back on a Mango Beta HD7 worked out to 10 frames per second. Not quite real time video. So it looks like my best option is to go with the MP4 video recorder. I'll have to figure out how to read frames from an MP4 file.

I'm glad I was able to figure that out before writing a substantial amount of code or doing a substantial amount of design.

Tags: ,

May 7 2011

John Conway's Game of Life part 1 of N

Category: MobileJoel Ivory Johnson @ 14:59

The Game of Life is a refinement of an idea from John von Newman in the 1940's. The refinement was done by John Conway and appeared in Scientific America in October 1970. I'll skip over the details of why such a program is of interest. But the program produces some interesting patterns.

The typical version of the game is composed of a grid of cells where some number of cells are initially marked as having life. The grid of cells is evaluated and cells get marked as alive or dead based on a small set of rules based on it's neighbors. Two cells are neighbors with each other if they touch diagonally or side-by-side.

  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

The above algorithm enough and the program is easy to implement. The challenge is more in creating a decent user interface for the program. I decided to make this program myself. The first step in making the program was to implement the algorithm. I wanted to make sure the algorithm worked so I created a simple XNA program that would allow me to see the algorithm work. It's non-interactive so you can only see the program run but not impact the outcome.

Theres a small amount of data that needs to be tracked for each cell. I need to know if a cell is alive and whether or not it should be alive during the next cycle. The cell will also need to interact with other cells in the community. Some time in the future I plan to allow the cells to express something about the parent from which it came. Though I won't be doing that for this first version.

public class Cell
{
     public CellCommunity  Community   { get; set; }
     public bool           IsAlive     { get; set; }
     public bool           WillSurvive { get; set; }
     public Gene           GeneList { get; set; }
}

The community of cells themselves will be saved in a two dimensional array. The cell community class has two methods that will do the work of calculating whether or not a cell should be alive the next cycle and another for applying the results of those calculations.

public void EvaluateNewGeneration()
{
    ++GenerationCount;

    for (var cx = 0; cx < CellGrid.GetUpperBound(0); ++cx)
    {
        for (var cy = 0; cy < CellGrid.GetUpperBound(1); ++cy)
        {
            var neighborsneighborList = GetNeighborList(cx, cy);
            var len = neighborsneighborList.Length;

            if ((IsAlive(cx, cy)))
            {
                if ((neighborsneighborList.Length > MAX_NEIGHBOR_COUNT) || (neighborsneighborList.Length < MIN_NEIGHBOR_COUNT))
                    KillCell(cx, cy);
                else
                    KeepCellAlive(cx, cy);
            }
            else
            {
                if ((neighborsneighborList.Length ==3))
                {
                    KeepCellAlive(cx, cy);
                }
            }
        }
    }
}

public void ApplySurvival()
{
    for (var cx = 0; cx < CellGrid.GetUpperBound(0); ++cx)
    {
        for (var cy = 0; cy < CellGrid.GetUpperBound(1); ++cy)
        {
            var cell = CellGrid[cx, cy];
            if (cell != null)
            {
                cell.IsAlive = cell.WillSurvive;
            }
        }
    }
}

I decided to make the UI in XNA. I have an idea on how to visualize a cell changing state and I can more easily implement it using a 3D API. Since the "world" of the Game of Life is in a grid I'm going to represent the state of a cell with a square that is either black (if the cell is not alive) or some other color (if the cell is alive). I'm drawing the squares by rendering vertices instead of writing sprites. This give me greater liberty in changing the color or shape of a cell. The following will draw one of the squares.

const int _squareWidth = 5;
const int _squareHeight = 5;
private const int _offsetX = -_squareWidth*30;
private const int _offsetY = -_squareHeight*18;

void DrawSquare(int x, int y, Color c)
{
    _vertices[0].Color = c;
    _vertices[1].Color = c;
    _vertices[2].Color = c;
    _vertices[3].Color = c;

    _vertices[0].Position.X = _offsetX + _squareWidth * x + _squareWidth;
    _vertices[0].Position.Y = _offsetY + _squareHeight * y;

    _vertices[1].Position.X = _offsetX + _squareWidth*x;
    _vertices[1].Position.Y = _offsetY + _squareHeight*y;

    _vertices[2].Position.X = _offsetX + _squareWidth * x + _squareWidth;
    _vertices[2].Position.Y = _offsetY + _squareHeight * y + _squareHeight;

    _vertices[3].Position.X = _offsetX + _squareWidth * x;
    _vertices[3].Position.Y = _offsetY + _squareHeight * y +_squareHeight;

    graphics.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, _vertices, 0, _vertices.Length-2);     
}

With the ability to draw the square completed it's easy to iterate through the collection of cells and render them to the screen according to whether or not they are alive.

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    var effect = new BasicEffect(GraphicsDevice);
    effect.World = _world;
    effect.Projection = _projection;
    effect.View = _view;
    effect.VertexColorEnabled = true;
    effect.TextureEnabled = false;
    effect.LightingEnabled = false;

    foreach(var effectPass in effect.CurrentTechnique.Passes)
    {
        effectPass.Apply();
        for (int cx = 0; cx < 60;++cx )
        {
            for(int cy=0;cy<36;++cy)
            {
                Color c = _community.IsAlive(cx, cy) ? Color.Red : Color.Black;
                DrawSquare(cx,cy,c);
            }
        }                    
    }
    base.Draw(gameTime);
}

I manually populated the grid and let it run. I'm happy to say it seems to be working. Now onto designing and making the user interface.

Screen Shot

Tags: ,

Mar 30 2011

Voice Memo source for WP7

Category: MobileJoel Ivory Johnson @ 18:00

This question keeps coming up in the forums so I decided to put the application together and make it publically available. If you head over to CodeProject you'll find a small article that I uploaded on making a voice memo application on Windows Phone 7. Among other things is demonstrates how to convert the raw recording bytes to a proper wave file, simple serialization, and a few other tid bits. For the sake of the article I did send the code through certification. 

However the application looks ugly right now. I've got a graphic artist that I'll be paying to design the UI for me and since I'm paying her for this I've decided not to include the graphic assets that she is producing in the code that I'm gicing away for free. 

There's no obligations attached to the code. But if you use it in your own products I would appreciate a heads up just so that I know where it's being used. 

Share photos on twitter with Twitpic

Tags: , ,

Mar 19 2011

Changing the Background on a Button

Category: MobileJoel Ivory Johnson @ 02:49

A recent question in the Windows Phone Development Forums asking for the XAML to display a background image in a button when it is pressed. Generating the XAML to do this is pretty easy (if you know how!). While the request was for the XAML for doing this I thought the instructions for producing the XAML to do this are of great value.

Open expressions blend and start a new project. In your project add a new button. Right-click on the button and select "Edit template"->"Edit Copy" You will be prompted for the name of the new button style that we are creating (call it what you want) and whether the template will be defined in the document (page) or defined globally for the application. If you only plan on using the style in one page then it's fine to define it within the document. In general you are probably going to use your style on more than one page. In either case for this exercise select the option to create the style within the document.

Switch to code view so that we can edit the XAML. Towards the top of your document you will see a style defined with the name you gave to it. Scroll down within the style until you find the construct with a ContentControl enveloped within a Border element. It will look like the following.

<Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" 
            BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" 
            CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}">								
     <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" 
                             Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" 
                             HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" 
                             Padding="{TemplateBinding Padding}" 
                            VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>

We are going to make most our changes here. We need to place an image within this border element. It is going to be behind the content and so it will have to appear before the ContentControl element. The Border element can only have one child so we will need to make a Grid the Border's direct child and then place the Image element and ContentControl element within the Grid. The Image attribute will need to have a name and it will need to have its Opacity set to zero since the image usually will not be visible. The resulting XAML will look like the following.

<Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}">								
	<Grid>
		<Image x:Name="BackgroundImage" Source="/Background.png" 
                            Stretch="Fill" VerticalAlignment="Bottom" Opacity="0" />
		<ContentControl x:Name="ContentContainer" 
                                       ContentTemplate="{TemplateBinding ContentTemplate}" 
                                       Content="{TemplateBinding Content}" 
                                       Foreground="{TemplateBinding Foreground}" 
                                       HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                       Padding="{TemplateBinding Padding}" 
                                       VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
	</Grid>
</Border>

Almost done! There's only a couple of things left. We want the image to be visible when the user is pressing the button. Scroll up within the template and you'll find several VisualStateGroup elements defined. This area contains the changes and transitions that need to occur on the button when certain things happen such as the button going to a disabled state, loosing or gaining focus, and so on. We are interested in changes that occur in the pressed state. Within the VisualState named Press is a StoryBoard containing several animations. We need to add one more animation that changes the opacity of our button. As the last child of the StoryBoard element add the following.

<DoubleAnimation To="100" Duration="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundImage" />

Now if you run the project you'll see the image show up in the button any time you press it, and disappear when ever you release it. Now how do you use this in another project? If you copy the Style element from this project and place it as a resource within your other projects it will be readily available for you (just make sure that your image source also appears in your target project). The style can be applied to a button through setting the buttons style.

<Button  Style="{StaticResource MyCustomButton}"/>

If you want to see what my entire style looks like here it is.

<Style x:Key="MyCustomButton" TargetType="Button">
	<Setter Property="Background" Value="Transparent"/>
	<Setter Property="BorderBrush" Value="{StaticResource PhoneForegroundBrush}"/>
	<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
	<Setter Property="BorderThickness" Value="{StaticResource PhoneBorderThickness}"/>
	<Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilySemiBold}"/>
	<Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMediumLarge}"/>
	<Setter Property="Padding" Value="10,3,10,5"/>
	<Setter Property="Template">
		<Setter.Value>
			<ControlTemplate TargetType="Button">
				<Grid Background="Transparent">
					<VisualStateManager.VisualStateGroups>
						<VisualStateGroup x:Name="CommonStates">
							<VisualState x:Name="Normal"/>
							<VisualState x:Name="MouseOver"/>
							<VisualState x:Name="Pressed">
								<Storyboard>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
										<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneBackgroundBrush}"/>
									</ObjectAnimationUsingKeyFrames>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
										<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
									</ObjectAnimationUsingKeyFrames>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
										<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
									</ObjectAnimationUsingKeyFrames>
									<DoubleAnimation To="100" Duration="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundImage" />
								</Storyboard>
							</VisualState>
							<VisualState x:Name="Disabled">
								<Storyboard>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
										<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
									</ObjectAnimationUsingKeyFrames>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
										<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
									</ObjectAnimationUsingKeyFrames>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
										<DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
									</ObjectAnimationUsingKeyFrames>
								</Storyboard>
							</VisualState>
						</VisualStateGroup>
					</VisualStateManager.VisualStateGroups>
					<Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}">								
						<Grid>
							<Image x:Name="BackgroundImage" Source="/Background.png" Stretch="Fill" VerticalAlignment="Bottom" Opacity="0" />
							<ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
						</Grid>
					</Border>
					
				</Grid>
			</ControlTemplate>
		</Setter.Value>
	</Setter>
</Style>

Tags:

Feb 10 2011

Simple Data Serialization on WP7

Category: MobileJoel Ivory Johnson @ 04:21

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. 

Tags: ,

Feb 5 2011

WP7 Team Member Interviews

Category: MobileJoel Ivory Johnson @ 14:57

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.

Tags:

Feb 4 2011

Copy and Paste rolling out for Windows Phone

Category: Microsoft | MobileJoel Ivory Johnson @ 10:38

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.

Tags:

Jan 13 2011

Begining WCF for Windows Phone Developers

Category: MobileJoel Ivory Johnson @ 04:37

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();
}

Tags: ,

Dec 16 2010

Physics 101 Part 1 of N : Acceleration

Category: MobileJoel Ivory Johnson @ 04:10

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.

Tags: , ,

Dec 15 2010

Building content threw InvalidOperationException D3DERR_NOTAVAILABLE

Category: MobileJoel Ivory Johnson @ 13:37

I was working on a Windows Phone XNA example earlier and decided to run it on my Xbox. After duplicating the project as an Xbox 360 project I kept running into the same error that seemed to have no explanation. 

 

<pre>Building content threw InvalidOperationException D3DERR_NOTAVAILABLE</pre>

 

<p>

It took a bit of time to figure out what was going on here. From doing a search on the Internet I found out that certain Direct3D programs cannot run at the same time as an XNA project. I don't fully understand why. But as it turns out the program that was causing me to experience this problem was the Zune client. Once I closed the Zune client I was able to compile and run my Xbox 360 program. Weird. 

</p>

Tags: ,

Dec 15 2010

Calculating Distance from GPS Coordinates

I've been carrying this equation around forever and a day and thought I would share it. With this equation you can calculate the distance between GPS coordinates. I tend to use SI units, but you should be able to easily adjust it for units of your choosing.

using System; 
using System.Device.Location; 
 
namespace J2i.Net.GPS 
    public static class DistanceCalculator 
    { 
 
        public const double EarthRadiusInMiles = 3956.0; 
        public const double EarthRadiusInKilometers = 6367.0; 
        public const double EarthRadiusInMeters = EarthRadiusInKilometers*1000; 
 
        public static double ToRadian(double val) { return val * (Math.PI / 180); } 
        public static double ToDegree(double val) { return val * 180 / Math.PI; } 
        public static double DiffRadian(double val1, double val2) { return ToRadian(val2) - ToRadian(val1); } 
 
 
 
        public static double CalcDistance(GeoCoordinate p1, GeoCoordinate p2) 
        { 
            return CalcDistance(p1.Latitude, p1.Longitude, p2.Latitude, p2.Longitude, EarthRadiusInKilometers); 
        } 
 
        public static Double Bearing(GeoCoordinate p1, GeoCoordinate p2) 
        { 
            return Bearing(p1.Latitude, p1.Longitude, p2.Latitude, p2.Longitude); 
        } 
 
        public static double CalcDistance(double lat1, double lng1, double lat2, double lng2, double radius) 
        { 
 
            return radius * 2 * Math.Asin(Math.Min(1, Math.Sqrt((Math.Pow(Math.Sin((DiffRadian(lat1, lat2)) / 2.0), 2.0) 
                + Math.Cos(ToRadian(lat1)) * Math.Cos(ToRadian(lat2)) * Math.Pow(Math.Sin((DiffRadian(lng1, lng2)) / 2.0), 2.0))))); 
        } 
 
        public static Double Bearing(double lat1, double lng1, double lat2, double lng2) 
        { 
 
            { 
                var dLat = lat2 - lat2; 
                var dLon = lng2 - lng1; 
                var dPhi = Math.Log(Math.Tan(lat2 / 2 + Math.PI / 4) / Math.Tan(lat1 / 2 + Math.PI / 4)); 
                var q = (Math.Abs(dLat) > 0) ? dLat / dPhi : Math.Cos(lat1); 
 
                if (Math.Abs(dLon) > Math.PI) 
                { 
                    dLon = dLon > 0 ? -(2 * Math.PI - dLon) : (2 * Math.PI + dLon); 
                } 
                //var d = Math.Sqrt(dLat * dLat + q * q * dLon * dLon) * R; 
                var brng = ToDegree(Math.Atan2(dLon, dPhi)); 
                return brng; 
            } 
        } 
 
    } 
 

Tags: ,

Dec 8 2010

Is My Media Locked?

Category: MobileJoel Ivory Johnson @ 12:22

If you've used the Media element on Windows Phone (or one of the other media related components) then you probably know that it won't work with the phone is connected to Zune. But Zune is needed for debugging. So how do you debug if part of your software package renders your phone half-functional while you are debugging?!  Well, you don't actually need to have Zune running to debug. There was a command line utility in the October update to the Windows Phone Developer Tools called WPConnect.exe. Upon connecting your phone to your computer Zune will open. Close it and run WPConnect.exe and you'll be able to deploy , run, and debug without your media library being crippled. 

But after distribution of your program it's still possible for a user to have their media functionality locked if they try to run the program you wrote while the phone is connected to Zune. You'll probably want to notify the user of what must be done to unlock the full functionality of your program. Eric Fleck of Microsoft had a suggestion that seems to work pretty well (original source here). In short he checks to see if the phone reports that it is connected to an Ethernet adapter. If it does then chances are it is connected to a computer with Zune. There are scenarios in which the phone could report that it is connected to an Ethernet adapter while the media file is not locked (ex: when connected using WPConnect.exe). The code is pretty simple:

 

        void CheckNetworkStatus()
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                if (NetworkInterface.NetworkInterfaceType == 
                    NetworkInterfaceType.Ethernet)
                {
                    MediaState = "Possibly locked, disconnect Zune";
                    return;
                }
            }
            MediaState = "All's Well! Media is available!";
        }

If you want a the code in project form you can find it here

Tags: ,