Skip to content


Starting Something is Easy

I started off the new year with Microsoft D3 Live and Interactive. The talk focused on “Starting Something New” in 2012. I decided to start off the year showing how easy it is to use your existing knowledge of .NET, indeed, even use some of your existing code, to make cool new things for Windows Phone.

In my part I decided to make a simple web page that loaded some data from an XML file and displayed it on the screen.

The Demo:

I started with a very simple page:

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

    </div>

    </form>

</body>

</html>

I did say simple Winking smile  All the stuff that was done on this page is done in the code behind:

protected void Page_Load(object sender, EventArgs e)

{

    CoolSites.Load();

 

    string line = "{0} <br />     ({1})<br /><br />";

 

    foreach (Site site in CoolSites.Sites)

    {

        Response.Write(string.Format(line, site.Name, site.Url));

    }

}

 

The code behind is calling the following class(es):

public class Site

{

    public string Name { get; set; }

    public string Url { get; set; }

}

 

public static class CoolSites

{

    //List of cool sites

    public static List<Site> Sites { get; set; }

 

    /// <summary>

    /// Loads the list of cool sites from the CoolSites xml file.

    /// </summary>

    public static void Load()

    {

        //initialize the list

        Sites = new List<Site>();

 

        //open the xml document

XDocument sitesXmlDocument =

XDocument.Load(

HostingEnvironment.MapPath(@"/App_Data/CoolSites.xml"));

XDocument sitesXmlDocument =

XDocument.Load(@"Data/CoolSites.xml");

        

        //read the xml document

var data = (from siteRecord in

sitesXmlDocument.Descendants("site")

                    select new Site

                    {

Name =

(string)siteRecord.Attribute("name").Value,

Url =

(string)siteRecord.Attribute("url").Value

                    });

 

        //load the object list

        foreach (Site siteRecord in data)

        {

            Sites.Add(siteRecord);

        }

    }

}

 

That code is used to read this XML:

<?xml version="1.0" encoding="utf-8" ?>

<sites>

  <site name="Developer Movement" 

        url="http://www.DeveloperMovement.com" />

  <site name="My Blog" 

        url="http://www.atleyhunter.com" />

  <site name="Canadian Mobile Developer Blog" 

        url="http://blogs.msdn.com/b/cdnmobiledevs/" />

  <site name="The App Hub" 

        url="http://create.msdn.com/" />

</sites>

 

That little code exercise gives you this output:

image

 

Now for the cool part !!!

Now we take that simple site and make a simple phone app in a few short minutes and with ALMOST NO CODE CHANGES!!!

Step 1:

Start by adding a new Windows Phone Application project:

image

Now your phone Project will look like this:

image

 

In ASP.NET the default name for the first page is Default.ASPX, in Windows Phone, it’s MainPage.xaml.  this is where we will be doing most of our work (using that term really loosely) today.

To give ourselves somewhere to place our outputted text, we will need to add a TextBlock (label) to the MainPage.xaml and give it a name (I used coolSitesTextBlock):

image

Now, in order to get the data, we copy the XML file, and the Sites.cs to the Phone app:

image

Now in the Sites.cs file, we have to make three changes:

  1. Remove the using System.Web.Hosting; line at the top as it is no longer applicable to this platform.
  2. Add a reference to System.Xml.Linq to  the Windows Phone project to allow the XML code to work.
  3. Change the namespace in the class from CoolSitesWeb to CoolSitesPhone
  4. Finally, change the following line:
//open the xml document

XDocument sitesXmlDocument = XDocument.Load(

               HostingEnvironment.MapPath(@"/App_Data/CoolSites.xml"));

to

XDocument sitesXmlDocument = XDocument.Load(@"Data/CoolSites.xml");


The reason for this is plain, the XML file is found in a different location on the phone as apposed to the web application.

Now for one of the coolest parts!  You can copy the entire loading code from the ASPX page in the ASP.NET page and copy it to the phone, make a few simple changes and you’re done!

Create a simple Loaded event handler on the code behind for the Phone’s MainPage.xaml:

public partial class MainPage : PhoneApplicationPage

{

    // Constructor

    public MainPage()

    {

        InitializeComponent();

 

        Loaded += new RoutedEventHandler(MainPage_Loaded);

    }

 

    void MainPage_Loaded(object sender, RoutedEventArgs e)

    {

        throw new NotImplementedException();

    }

}

Replace the throw new NotImplementedException(); line with this code from the Default.aspx page’s Page_Load event.

void MainPage_Loaded(object sender, RoutedEventArgs e)

{

    CoolSites.Load();

 

    string line = "{0} <br />     ({1})<br /><br />";

 

    foreach (Site site in CoolSites.Sites)

    {

        Response.Write(string.Format(line, site.Name, site.Url));

    }

}

 

Now make three little changes:

Add a string variable to hold the concatenated text to be desplayed in the coolSitesTextBlock on the MainPage.xaml (I used coolSitesText)

Change the Response.Write line to a line that concatenates your text for you in the foreach loop.

Add a line that sets the coolSitesTextBlock.Text value to your cool sitesText variable.

And last, but not least, change the <br /> for \r\n to add the same formatting you had in the web page on the Phone form.

Your new code should look something like this:

void MainPage_Loaded(object sender, RoutedEventArgs e)

{

    CoolSites.Load();

 

    //Old Code -> 

    //string line = "{0} <br />     ({1})<br /><br />";

    string line = "{0} \r\n     ({1})\r\n\r\n";

 

    //New Code

    string coolSitesText = string.Empty;

 

    foreach (Site site in CoolSites.Sites)

    {

        //Old Code -> 

        //Response.Write(string.Format(line, site.Name, site.Url));

        coolSitesText += string.Format(line, site.Name, site.Url);

    }

 

    //New Code

    coolSitesTextBlock.Text = coolSitesText;

}

Now, surprisingly, we’re done!  Running your new phone app will give you this:

image

As you can see, it is remarkably easy to port code from other .NET applications to the Phone.

You can get the source code here for both the Web and the Phone sides of this little project so you can see for yourself how easy this is.

You Should:

Check out the tools and the other cool stuff at the App Hub

Find out how you can get a free phone or XBox (and other cool stuff) by joining the Developer Movement!!!

And keep tuning into Microsoft D3 Live and Interactive for great new shows and lots of other cool stuff!

And most of all:

GET SOMETHING STARTED!!!

IT’S EASY!!!

 

Disclaimer

Now, before you start telling me all the better ways that you can add data to either a Web app or a Phone app, I want to let you know that this is just for demonstration purposes and not necessarily an example of Best Practices or the best way to code either of these two instances.

Other than that, I’d like to hear your suggestions, stories and/or answer your questions about  getting started with Windows Phone development, after all, that is why I do this!!!

Posted in Devices, Events, Microsoft, Windows Phone 7.


2 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. denna buck says

    Hi! I’ve been following your site for a while now and finally got the courage to go ahead and give you a shout out from Lubbock Tx! Just wanted to tell you keep up the fantastic job!

    • Atley says

      thanks for the shout out, have you made any apps?



Some HTML is OK

or, reply to this post via trackback.