J2i.Net

Nothing at all and Everything in general.

Invoking through the Dispatcher on Windows Phone and Metro

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

What Does Windows 8 Mean for Windows Phone Developers?

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. 

Windows Phone 7.5 (Mango) Availability

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.

Passing thoughts, video effects on Windows Phone

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.

John Conway's Game of Life part 1 of N

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

Voice Memo source for WP7

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

Changing the Background on a Button

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>

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. 

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.