Phone Gap Tutorial #1- Getting Started


This is a   tutorial Series in which I will create a phone gap application for each of the platforms it supports. It is mostly a journey of my own that you get to follow along on.  I will start with Windows Phone and then convert it to IPhone, IPad, Android, Blackberry, Symbian. We will discuss tips and tricks along the way.

In this post, we will look at what you need to do to get started using using Windows Phone.  The first thing you need to do is download the tools.

Go to http://phonegap.com and click on the Download PhoneGap button. It is currently at version 1.41image

The file will be called callback-phonegap-1.4.1-0-g0d1f305.zip (of course the number will change as new updates are applied).  It is called callback-phonegap because…. now take a breath here…. Nitobi, the company that create (at a hackathon… cool), was acquired by  Adobe who then jointly with Nitobi donated the project to the Apache Software Foundation (ASW).  This is a good thing since Adobe will continue to back the project while allowing others to continue to contribute. Now why is it called Callback you ask?  Well, the name inside ASW for is Callback….. or at least it was, it has since been changed to Apache Cordova, so I assume the file name will change soon to.

So once you have downloaded and unziped the file, you will want to navigate to \callback-phonegap-1.4.1-0-g0d1f305\callback-phonegap-0d1f305\lib\windows.  You will see many things in here, but we are only concerned with one right now. PhoneGapStarter.zip (We will talk about PhoneGapCustom.zip later).  We want to copy this to our Visual Studio Templates folder so we can create projects in Visual Studio. 

Copy the PhoneGapStarter.zip file to C:\Users\[USERNAME]\Documents\Visual Studio 2010\Templates\ProjectTemplates\Silverlight for Windows Phone

Now open up Visual Studio (This works with the full or express version) and go to File –> New Project

Select Visual C# –> Silverlight for Windows Phone

You should see a project template for PhoneGapStarter

image

Name Your project and hit OK.  That will create your project.

In the next tutorial, we will walk through all off the files and the set up of your New Phonegap project.

Other Posts in this Series

(This list will automatically grow as I write them)

[catlist name=phone-gap-tutorial]



WP7 Rest … The Easy Way

Over and over again, I see developers that have this great idea for an application that pulls cool data from a  great services BUT get tied up in the implementation of “Getting It Done”.  So I thought I would show you a quick and easy way to get REST data from a service, transfer the JSON data to a POCO list and Bind it to a listbox.  (In under 3 minutes)

On your Mark

Get Set

Go.

The first think you need to do is find some Data that is interesting to you.  For me, I LOVE coffee so I want to create an application that shows me all the coffee places that are near to me.  I can do this using Bing Search  http://msdn.microsoft.com/en-us/library/dd251014.aspx 

Specifically, I am going to use the PhoneBook Request part of the API that is like a Yellow Pages API.  It will give me all the business that designate themselves as “Coffee” places.

(Yes I know I am not using MVVM)

The first thing I do is Create a method called GetData() and call it from my MainPage() Constructor

  public MainPage()
        {
            InitializeComponent();
            GetData();
        }

        private void GetData()
        {
            string uri = "http://api.bing.net/json.aspx?AppId=YOUR_APP_ID&Version=2.0&Market=en-US&Query=Coffee&Sources=phonebook&latitude=33.8563&longitude=-118.1232";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(uri));
            request.BeginGetResponse(new AsyncCallback(ReadCallback), request);

        }

In GetData() the first thing I do is make a call to the BING  API. 

The first part of the call shows that I want json returned and supplies my App_ID (Removed from post)  ( You can get your own Bing API key here http://msdn.microsoft.com/en-us/library/dd251020.aspx )

http://api.bing.net/json.aspx?AppId=YOUR_APP_ID

Next I set the version, Market, and what I am looking for

&Version=2.0&Market=en-US&Query=Coffee&

And finally, I tell it I am looking at the phonebook part of the API and where I want to search… In this example I am hardcoding the lat/long but you would of course use the Geo Location from the phone, but I wanted to keep this simple.

Sources=phonebook&latitude=33.8563&longitude=-118.1232";

Next, We then need to make the call to the service.  We will use a HttpWebRequest by passing it the URI we just created

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(uri));

And then making in the call and supplying it the CallBack method (Where the call returns to when it is finished)

request.BeginGetResponse(new AsyncCallback(ReadCallback), request);

Now here is the fun part. To work with the JSon data the is returned from this query, we need to create the class structure that represents the data…….. ugggggg what a pain right?   Nope Wrong, All we need to do is use http://json2csharp.com/    Just paste in either the JSon returned OR the URI String, and it will create the classes for you. So when I paste in my URI String above, it gives me the following.

(you can, of course, break up these classes into separate files but for now, I just pasted them at the bottom of the MainPage.xaml.cs file.)

 

public class Query
    {
        public string SearchTerms { get; set; }
    }

    public class Result
    {
        public string Title { get; set; }
        public string Url { get; set; }
        public string Business { get; set; }
        public string PhoneNumber { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string StateOrProvince { get; set; }
        public string CountryOrRegion { get; set; }
        public string PostalCode { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }
        public string UniqueId { get; set; }
        public string DisplayUrl { get; set; }
    }


    public class Phonebook
    {
        public int Total { get; set; }
        public int Offset { get; set; }
        public string LocalSerpUrl { get; set; }
        public string Title { get; set; }
        public List<Restuarnt> Results { get; set; }
    }

    public class SearchResponse
    {
        public string Version { get; set; }
        public Query Query { get; set; }
        public Phonebook Phonebook { get; set; }
    }

    public class RootObject
    {
        public SearchResponse SearchResponse { get; set; }
    }

Now that you have the classes that hold the json that is returned, all you need to do is create the ReadCallback Method (Defined above)

private void ReadCallback(IAsyncResult asynchronousResult) 
        { 
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; 
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); 
            using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream())) 
            { 
                string resultString = streamReader1.ReadToEnd(); 
                var ser = new DataContractJsonSerializer(typeof(RootObject));

                var stream = new MemoryStream(Encoding.Unicode.GetBytes(resultString));
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(RootObject));
                RootObject myBook = (RootObject)jsonSerializer.ReadObject(stream);
              
                

                Deployment.Current.Dispatcher.BeginInvoke(() => coffeeShops.ItemsSource = myBook.SearchResponse.Phonebook.Results); 
                
            } 
        }

You can see that we use a stream reader to read the results and then use a DataContractJsonSerializer to add the data to the RootObject (Root Object is one of the classes that were created for us that encapsulates all the others)

On the last line, I marshall the data to the UI thread using Dispatcher.BeginInvoke and bind it to a ListBox called coffeeShops.

That’s IT….

Now it took me 30 minutes to write this up, but it should take you only 3 minutes to implement.

Enjoy Smile

Free Windows Phone

image

UPDATE:  YES THIS IS AN OLDER POST BUT I STILL HAVE PHONES

Are you looking for a Free Windows Phone?  Are you a developer?  Do you live on the West Coast of the US? (CA, AZ,ID, WA, NM, CO, NV, OR, UT)  Then I have a phone for you. (Read Below)  If you have been looking for a free windows phone to do development on then all you need to do is contact me.  Email me at Daniel.Egan@microsoft.com and I will send you all the details. (INCLUDE WHERE YOU LIVE in the email or I will not respond  — too many emails :)  )

I want to be clear on a couple of things.

  1. I am getting these phones to developers that are writing applications for the marketplace
  2. I have a limited supply (First ones to get me the info I need)
  3. You must live on the West Coast of the US  (CA, AZ,ID, WA, NM, CO, NV, OR, UT)

If you do not live on the West Coast of the US, I can try to find your windows phone champ for you.  Just post the request here :  http://thesociablegeek.com/forum/?mingleforumaction=viewforum&f=3.0

This does not mean that they will have a phone for you, but if you are developing for Windows Phone, you WANT to know your windows phone champ.  If they don’t have phones, they may know someone who does ( I repeat, I am not saying they have phones Smile , but they may know a way.  Either way, they are a great resource for you. )

So all of you West Coasters, get your Free Windows Phone while they last.  Email me at Daniel.Egan@microsoft.com for the details. UPDATE :  PLEASE INCLUDE WHERE YOU ARE FROM SO I DONT HAVE TO ASK YOU IN EMAIL. (Slowes down the process)

PhoneGap for Windows Phone

 

If you are writing your phone applications using HTML5, you will want to check this out. PhoneGap has released an update to work with Windows Phone.  What PhoneGap does is allow you to write your phone application in HTML5 and still access most of the Native API’s and wrap it in a Native application wrapper so that you can put it in the marketplace.  This means you can write your application cross platform.

You can download it from here : http://phonegap.com/  or just watch the video below for more information.

The Web Role was started in a wrong port

imageOne of the great things about Windows Phone is all of the samples that are out there.  And topping them all is the Windows Azure Toolkit for Windows Phone 7 .  The toolkit gives you everything you need to develop a Windows Phone application using Windows Azure. I will do a full post walkthrough of using the toolkit, but I thought I would post about one thing that seems to be tripping people up when they are trying to get things up and running.

If you start the project and get the error Sorry, an error occurred while processing your request, the web role was started in a wrong port, You might scratch your head.  If you peek at the url you will notice that it is running on port 444 instead of 443

image

The reason it is doing this is because if it does not find port 443 open, it will increment by one until it finds an open port. If you look in your compute emulator you will also see the wrong port. Which is the reason it says The web role was started in a wrong port.  Because it was :)

image

So now, to fix this you want to see what is running on port 443.  To do this open a cmd window and type in the following netstat –aon

This will bring up a list of what is running on each port.

image

You want to look for anything that has a :443 at the end of it and look at the last column.  This is the process ID for the process that is using that port.

Next, open up Task Manager and look for the process ids that you found. ( You may need to go to View –> Select Columns first to add the PID column)

 

image

My offending applications were:

  • SQL Reporting Services (Which I shut down in Services)
  • TweetDeck
  • Skype

That fixed it for me… hope that helps

Daniel

Live Tiles–Windows Phone Workshop

Today is the day we start the Windows Phone Workshop.  You can either watch it here (below) or head over to livestream. You can find the recorded session below..

Here are the files :

http://dl.dropbox.com/u/32614089/SimpleTileDemo.zip

http://dl.dropbox.com/u/32614089/SimpleTileDemo%20WithPush.zip

SPECIAL NOTE : Since we were doing alot of testing, you will want to skip to 1 hour in to see the session.

Watch live streaming video from microsoftdevelopers at livestream.com

Suggest a Windows Phone Workshop

unclesamNow that we are doing Windows Phone Workshops, we would like to know what YOU would like to see.  There are so many things to do on Windows Phone that we want to make sure that you get the sessions that are important to you.

All you need to do is either VOTE for a suggestion already there OR add your own suggestion.  Let me know if you have any suggestions.

Vote Here  http://thesociablegeek.com/workshop-suggestions/

WindowsPhoneWorkshops

Windows Phone App of the Day–LilDemonsSpplatter

Those that know me, know that I am not really a gamer.  I enjoy a game once in a while but usually don’t spend much time playing them.  I came across this FREE  game today that is really cool.  It’s a first person shooter game for the phone.  The graphics could be a bit better but hey… Its free.  Check it out.  http://www.windowsphone.com/en-US/search?q=LilDemonsSplatter 

Nokia Developer Program

In addition to the launch of the Phones from Nokia is the launch of the Nokia Developers Program.  The program includes Tools, Documentation, Code Examples, Videos and a vibrant community to get you on your way.  Head over to the developer site http://Developer.Nokia.com/WindowsPhones  or go directly to the code samples to check them out. http://www.developer.nokia.com/Develop/Windows_Phone/Code_examples/

Examples are a great way to jumpstart the development on that app you have been thinking about.

 

This work is licensed under a Creative Commons license.

Free Windows Phone Workshops

Starting Next week, I will be doing a series of Windows Phone Workshops online to teach people how to program with Windows Phone.  You can find the current workshops available by either clicking on the Upcoming Workshops link above or by clicking here : http://thesociablegeek.com/event-registration/

In these workshops I plan to talk about one subject matter at at time. I will be LiveStreaming from beautiful LA so you can follow along from wherever you are in the world.  I am completely open to suggestions, so feel free to join in the chat and suggest something OR email me daniel.egan AT microsoft DOT com.  Since this is new, there may be some bumps along the road while I get the technology sorted out.   I hope you enjoy the upcoming events.  Please Register for the events so I know how many people to expect.

Daniel – The Sociable Geek

This work is licensed under a Creative Commons license.