Sudhindra Kovalam's Blog

My Geeky Blog

Archive for the ‘Windows Phone 7’ Category

Community Techdays Mumbai

leave a comment »

I am travelling to Mumbai tomorrow. I would be speaking at community tech days there along with mayur tendulkar. My session is called

Developing Line of Business applications for Windows Phone

Hope to catch some of you folks there :)

For more details visit : http://www.communitytechdays.com/agenda.aspx#mumbai

Those who are attending , Lemme assure you, You folks are in for a treat :)

See you there.

Also, if you are keen on learnign windows phone development, there is an ongoing screencast series (organised by Pune User Group) on windows phone 7 development. you can find more info at

http://www.puneusergroup.org/windows-phone-7-webcasts.aspx

Also stay tuned on this blog.

 Some really really cool articles are in the works :)

Written by sudheerkovalam

November 26, 2010 at 4:49 am

Posted in Windows Phone 7

Writing windows phone apps for SharePoint

with 6 comments

Writing a blog post after quite some time. (Well frankly was thinking on what sort of post to write)

We have heard / seen / read about how windows phone has good SharePoint 2010 integration features as to how the office hub can integrate with your corporate intranet SharePoint site and how, you can leverage the SharePoint workspace capabilities in windows phone.

after reading about this, you’d say cool, can i write an app which speaks to my SharePoint site. Well the answer is Yes. But there are some changes that you need to to do on SharePoint site configuration.

“Argh!!, making changes on SharePoint site, My boss(and/or system admin) will kill me! “.

Was this your reaction ? (at least, that was my initial reaction).

In that case, this post might not be of that much help.

However, we can always host a cloud service that would help you get data from SharePoint and you can consume the data from this “middle man” cloud service. ( Off course this does add up expenses that at the end of the day needs to be taken care off by some one)

So, why is that I cannot consume SharePoint service directly from my windows phone.

Well it all began, when windows phone SDK team decided to omit NTLM auth support from the SDK, thus preventing us 3rd party developers from directly writing cool apps that speak to your SharePoint site.

“Why did they do this to us? “ you ask!!, Well frankly, i don’t have an answer to that.

But, There is a way out of this. How is that? Well , all you got to do is enable Forms based authentication for your SharePoint site.

How do I do that? There is a good article here. (Remember, you need to be very very strong hearted to take up all these changes, as these changes might literally take down your SharePoint site. )

Here’s a pictorial representation of auth mechanisms and SharePoint support for the same.

(Stolen from Paul Stubbs blog on MSDN, Sorry!! )

5488.image_thumb_0D9FC62A

Well what story, the above diagram is trying to tell is:

SharePoint 2010 supports two different authentication modes.

1. Classic mode (The Loner left side branch, support NTLM authentication only)

2. Claims based mode (The right side branch of the diagram above)

What you can realise is that if you use the claims based mode for creating your SharePoint web application, you can use any of the claims providers to authenticate yourself (in this case, your phone app’s code) to your SharePoint site. (Off course, your system administrator can have hard time configuring the same, but lets not get into that Open-mouthed smile)

Once you have the infrastructure in place. All you got to do is use the SharePoint 2010 Web services to access SharePoint lists etc.

In SharePoint, you cannot make any changes to a spsite until you are an authenticated user. So You need to log in programmatically to make changes such as adding list items, modifying ‘em etc.

For Logging in , you can use the authentication.asmx web service to authenticate yourself.

(the spsite you are trying to access via your code needs to allow form based authentication.) The Authentication site is available at : http://[YourSiteName]/_vti_bin/authentication.asmx

Logging into SharePoint

Here’s what happens when you visit a SharePoint site: (Again stolen for Paul stubbs’ blog , sorry again!!)

4606.image_4D69ACAF

1. you visit a SharePoint site page.

2. you are redirected to the login page(this internally uses the authentication web service), you enter your credentials here.

3. the authentication service returns a security token(FEDAUTH).

4. this security token is passed for all subsequent calls to the SharePoint site.

5. this security token is verified by the server for validity and then the server returns the requested resource.

How Do I do this Programatically?

Well, for programmatically mimicking the above mentioned behaviour, you can write  code that looks something like this:

CookieContainer cookieJar = new CookieContainer();
    private void Authenticate()
    {
      System.Uri authServiceUri = new Uri("http://[YourSPSite]/_vti_bin/authentication.asmx");

      HttpWebRequest spAuthReq = HttpWebRequest.Create(authServiceUri) as HttpWebRequest;
      spAuthReq.CookieContainer = cookieJar;
      spAuthReq.Headers["SOAPAction"] = "http://schemas.microsoft.com/sharepoint/soap/Login";
      spAuthReq.ContentType = "text/xml; charset=utf-8";
      //spAuthReq.Accept = "text/xml";
      spAuthReq.Method = "POST";

      //add the soap message to the request
      spAuthReq.BeginGetRequestStream(new AsyncCallback(spAuthReqCallBack), spAuthReq);
    }

    private void spAuthReqCallBack(IAsyncResult asyncResult)
    {
      string envelope =
          @"<?xml version=""1.0"" encoding=""utf-8""?>
          <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
               xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
                xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
          <soap:Body>
            <Login xmlns=""http://schemas.microsoft.com/sharepoint/soap/"">
            <username>{0}</username>
            <password>{1}</password>
            </Login>
          </soap:Body>
          </soap:Envelope>";

      UTF8Encoding encoding = new UTF8Encoding();
      HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
      Stream _body = request.EndGetRequestStream(asyncResult);
      envelope = string.Format(envelope, "userName", "password");
      byte[] formBytes = encoding.GetBytes(envelope);

      _body.Write(formBytes, 0, formBytes.Length);
      _body.Close();

      request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
    }

    private void ResponseCallback(IAsyncResult asyncResult)
    {
      HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
      HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
      Stream content = response.GetResponseStream();

      if (request != null && response != null)
      {
        if (response.StatusCode == HttpStatusCode.OK)
        {
          using (StreamReader reader = new StreamReader(content))
          {
            //Put debugging code here
            string _responseString = reader.ReadToEnd();
            reader.Close();
          }
        }
      }

      //authentication complete
      //Use the Cookie Container for all subsequent calls
    }

 

Now that you have the FEDAUTH token in the CookieContainer instance, you can pass it around to access other list services.

System.Uri listServiceUri = new Uri("http://[YourSpSite]/_vti_bin/lists.asmx");
HttpWebRequest spAuthReq = HttpWebRequest.Create(listServiceUri) as HttpWebRequest;
spAuthReq.CookieContainer = cookieJar;

 

Will try and post up a complete working sample of the same very very soon! Till then keep checking this space for more updates Smile

Written by sudheerkovalam

November 4, 2010 at 3:03 pm

Posted in Application Design, Windows Phone 7

Tagged with

A Windows Phone Twitter Application : Part 2 of 2

with 32 comments

(Update : For trying out code posted on this blog post, Kindly use the official/ locked emulator . The unlocked emulator images have a known issue with HTTPS )

This is the second post in the series of posts explaining how you can build your own twitter application on Windows Phone 7

Post(s) in this series:

Part 1: Understanding oAuth

As explained in part one, the hard part of writing a twitter application is, to figure out/ understand the authentication/ authorization mechanism. Once You have done that, you can pretty much write an app for any service that has oauth as its authentication/authorization mechanism.

Now that we have obtained all the necessary authorization token(s), we can now access the protected resources on the user’s behalf.

How to Post a Tweet on a User’s behalf?

Using the access token and our app’s consumer secret , we need to make a POST request to twitter’s API to post a tweet from our app.

Using Hammock’s REST Library, You would do something like this :

if (txtBoxNewTweet.Text.Trim().Length == 0) { return; }
var credentials = new OAuthCredentials
{
      Type = OAuthType.ProtectedResource,
       SignatureMethod = OAuthSignatureMethod.HmacSha1,
       ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
       ConsumerKey = TwitterSettings.consumerKey,
       ConsumerSecret = TwitterSettings.consumerKeySecret,
       Token = this.accessToken,
       TokenSecret = this.accessTokenSecret,
       Version = "1.0"
};

var restClient = new RestClient
{
        Authority = TwitterSettings.StatusUpdateUrl,
        HasElevatedPermissions = true,
        Credentials = credentials,
        Method = WebMethod.Post
};

restClient.AddHeader("Content-Type", "application/x-www-form-urlencoded");

// Create a Rest Request and fire it
var restRequest = new RestRequest
{
       Path = "1/statuses/update.xml?status=" + txtBoxNewTweet.Text
};

var ByteData = Encoding.UTF8.GetBytes(txtBoxNewTweet.Text);
restRequest.AddPostContent(ByteData);
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));

Now that you are able to make posts, you need a way to see the posts you have made on the user’s twitter account!

Well For looking at status updates, you don’t need authorization. You can directly give a call to the twitter api and you will get your status updates. ( This sample code is as demonstrated on Scott Gu’s blog )

 private void GetUserTimeLine()
        {
            WebClient wcTwitterTimeline = new WebClient();
            wcTwitterTimeline.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wcTwitterTimeline_DownloadStringCompleted);
            wcTwitterTimeline.DownloadStringAsync(new System.Uri("http://api.twitter.com/1/statuses/public_timeline.xml?screen_name=" + userScreenName));
        }

        void wcTwitterTimeline_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            { return; }
            XElement Tweets = XElement.Parse(e.Result);
            listboxMyTimeline.ItemsSource = from tweet in Tweets.Descendants("status")
                                            select new TwitterItem
                                            {
                                                UserName = tweet.Element("user").Element("screen_name").Value,
                                                Tweet = tweet.Element("text").Value,
                                                ImageSource = tweet.Element("user").Element("profile_image_url").Value
                                            };
            Dispatcher.BeginInvoke(() =>
            {
                listboxMyTimeline.Visibility = Visibility.Visible;
                txtBoxNewTweet.Visibility = Visibility.Visible;
                btnPostTweet.Visibility = Visibility.Visible;
            });
        }

With this, you are pretty much able to make a basic twitter app, that allows you to post tweets.

Using the Twitter api (Found here) You can create a full fledged twitter app.

As promised, I am uploading the source code for the app. You can download the source here.

(UPDATE : I have updated the code snippet, so that the app now runs on the public beta of the tools , Thanks Don for pointing this out )

Once again, Thanks for your support. With the final SDK Bits coming out this September 16th and with WP7 hitting the RTM status (Congratulations to the Windows Phone team @MSFT, Will be  queuing up the store when, it hits retail Smile), The next couple of weeks seem to be really really interesting.  Stay tuned for more exciting WP7 stuff

Written by sudheerkovalam

September 5, 2010 at 2:12 pm

A Windows Phone 7 Twitter Application : Part 1 of 2 (Understanding oAuth)

with 58 comments

(Update : For trying out code posted on this blog post, Kindly use the official/ locked emulator . The unlocked emulator images have a known issue with HTTPS )

As Promised in the previous post(I Know it was very long ago), We will try to build a Twitter application. Building a twitter app is a very easy task, and this post intends to guide you Step by step in creating your first twitter application. This post will speak about getting the app authenticated/authorized using the oAuth Mechanism.
The target platform is Windows Phone 7  in  this post, but you can pretty much a build a twitter app on any other platform based on this tutorial
Step 1: Register Your Twitter app on dev.twitter.com
Twitter needs to know that You are writing an app which accesses/posts tweets on your behalf. You tell this to twitter by registering your app on twitter.
image
twitterAppRegistration
When Registering your app, ensure that You set the Application type to browser and specify a call-back URL. (Twitter has certain requirements on Call-back URLs, i.e. it will not accept non HTTP URLs ( You need to ask twitter specially for  that ). For Demo purposes, i have specified Google.com as my default call-back URL.You can specify your custom page hosted on your domain, if you want to
This is how your app settings on twitter would look like:
AppSettings
Make a note of the highlighted URLs and your consumer key and secret.( Wondering what these are? Continue Reading or Read about oauth here)
Now comes the fun part, As usual fire up Visual studio 2010. Do a File | New Project. Select a Windows Phone Application from Silverlight for Windows Phone Section.
Twitter exposes a RESTful Service to access a user’s tweets etc. Twitter as of now only allows oAuth and XAuth as the only authorization mechanism. Since we have to have to consume a REST service along with oAuth, we will be  using a REST Client helper, that abstracts a lot of the hard work for me. (Such as adding the necessary headers, Computing oAuth Parameters such as Signature, Nonce, Timestamp etc. etc.)
For this demo, we’d be using the Hammock REST client available for download here. (Ohh BTW, Hammock is a very good example as to how same source code can target multiple platforms and multiple .net versions. Curious , about knowing how ? Go straight to the site and download the source code and have a look for yourselves.)
Now Lets get our hands dirty with some code for our first Twitter Application on Windows Phone 7 Smile
First Using the consumer Key and consumer key secret that you got by registering your application on twitter’s site, you need to request for a request token and request token secret
Request Token and request token secret are temporary set of credentials that let you acquire oauth access Tokens. The access token and access token secret are needed to access a user’s tweets.
To do this, I will use some neatly written helper classes in the Hammock library.( Else I would be actually writing code to do a lot of ugly stuff)

 var oauth = new OAuthWorkflow
{
     ConsumerKey = TwitterSettings.consumerKey,
     ConsumerSecret = TwitterSettings.consumerKeySecret,
     SignatureMethod = OAuthSignatureMethod.HmacSha1,
     ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
     RequestTokenUrl = TwitterSettings.RequestTokenUri,
     Version = TwitterSettings.oAuthVersion,
     CallbackUrl = TwitterSettings.CallbackUri
};

var info = oauth.BuildRequestTokenInfo(WebMethod.Get);
var objOAuthWebQuery = new OAuthWebQuery(info);
objOAuthWebQuery.HasElevatedPermissions = true;
objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock";
objOAuthWebQuery.SilverlightMethodHeader = "GET";

What this helper class does is, hide a lot of stuff from the end user that needs to be done to acquire the request token and secret. Using the oauth WebQuery object all i have to do is to instantiate  a Hammock Rest Client object to fire a request to twitter’s servers.

 var requestTokenQuery = oAuthHelper.GetRequestTokenQuery();
 requestTokenQuery.RequestAsync(TwitterSettings.RequestTokenUri, null);
 requestTokenQuery.QueryResponse += new EventHandler(requestTokenQuery_QueryResponse);
In the response received event, I parse the response sent across by twitter. This should have the request token and request token secret in the response body.
var parameters = HelperMethods.GetQueryParameters(e.Response);
OAuthTokenKey = parameters["oauth_token"];
tokenSecret = parameters["oauth_token_secret"];
var authorizeUrl = TwitterSettings.AuthorizeUri+ "?oauth_token=" + OAuthTokenKey;

Now using the request token and secret, we need to get our app authorized to read/write data from the end user’s twitter account. To do this, we need to open a web browser and redirect the end user to twitter’s sign-in/ authorize page. To do this, I will be using a Web browser control and redirecting it to the authorize URL I have created above.

Dispatcher.BeginInvoke(() =>
{
      this.objAuthorizeBrowserControl.Navigate(new Uri(authorizeUrl));
});
The XAML for the browser control would look something like this:







The User sees the twitter page, where s/he signs in to twitter. Here, s/he is asked to authorize our twitter app.
twiiter_HomeScreentwitter_startScreentwitter_signIntwitter_signIn_2tiwtter_authorize
After you have authorized the application to access your data on your behalf, twitter will send the oauth request token (you received in the previous step) and a verification pin. Using these tokens, you can now request for the access token and access token secret. ( Arrgh!!! another set of tokens….)
Using the Hammock helper class that we used to get request tokens, we can acquire Access tokens as follows:
 var AuthorizeResult = HelperMethods.GetQueryParameters(e.Uri.ToString());
var VerifyPin = AuthorizeResult["oauth_verifier"];
this.objAuthorizeBrowserControl.Visibility = Visibility.Collapsed;

//We now have the Verification pin
//Using the request token and verification pin to request for Access tokens

var AccessTokenQuery = oAuthHelper.GetAccessTokenQuery(
                                             OAuthTokenKey,     //The request Token
                                             tokenSecret,       //The request Token Secret
                                             VerifyPin         // Verification Pin
                                          );

AccessTokenQuery.QueryResponse += new EventHandler(AccessTokenQuery_QueryResponse);
AccessTokenQuery.RequestAsync(TwitterSettings.AccessTokenUri, null);
In response twitter sends us the access tokens, the userID and the user’s screen name. I am going to store ‘em all, (Can prove to be very handy.)
var parameters = HelperMethods.GetQueryParameters(e.Response);
 accessToken = parameters["oauth_token"];
accessTokenSecret = parameters["oauth_token_secret"];
userID = parameters["user_id"];
userScreenName = parameters["screen_name"];

HelperMethods.SetKeyValue("AccessToken", accessToken);
HelperMethods.SetKeyValue("AccessTokenSecret", accessTokenSecret);
Dispatcher.BeginInvoke(() =>
{
    MenuItemSignIn.IsEnabled = false;
    MenuItemSignOut.IsEnabled = true;
    TweetButton.IsEnabled = true;
});
Phew!!! Now we are authenticated. We can now use the tokens we have received till now and the app can now access the user’s data(such as tweets, timeline etc.)

Written by sudheerkovalam

August 28, 2010 at 7:58 am

Windows Phone 7 : Launcher and Choosers : Part 2

leave a comment »

Let us continue our exploration of Windows Phone 7 Launchers and Choosers.

I had described Windows Phone 7 launchers here.

Chooser is an API , that launched a  built in functionality for the user to accomplish some task and returns back the data that was chosen by the user to the app.

We had seen how we could do a new launcher as and where needed, But in case of Choosers, the game is a little different.

A Chooser starts a different application ( Your app gets tombstoned)  and after the intended action is complete, ( Your app is back from the grave mwahahah!! ) the results are returned to your application. So we will have to declare the Chooser objects at a global scope within the PhoneApplicationPage class and  instantiate  it  in the page’s ctor and do the necessary plumbing (By that, i mean handling the necessary events etc.)

As of now following choosers are exposed

1. CameraCaptureTask:

The Camera Capture Task starts the camera of the phone. Now, the user is  actually seeing the phone’s camera app, where s/he can click  photos. Once the Photo is taken , we can save this photo in the Phone’s Media library. For doing this, we need to add a reference to XNA.Framework assembly.

using Microsoft.Xna.Framework.Media;
public partial class page2 : PhoneApplicationPage
{
   CameraCaptureTask cameraCaptureTask;

   // Constructor
   public page2()
   {
      InitializeComponent();
      // Initialize the CameraCaptureTask and assign the Completed handler in the page constructor.
      cameraCaptureTask = new CameraCaptureTask();
      cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
   }

   private void btnCamera_Click(object sender, RoutedEventArgs e)
   {
      cameraCaptureTask.Show();
   }
   void objCameraCapture_Completed(object sender, PhotoResult e)
   {
       if (e.TaskResult == TaskResult.OK)
       {
          MediaLibrary library = new MediaLibrary();
          Random r = new Random(1234);
          Picture pic = library.SavePicture("SavedPicture_" + r.Next(11, 99).ToString() + ".jpg", e.ChosenPhoto);
       }
    }
}

ScreenShots:
Picture Capture Screen Accept or Retake the Pic


2. PhotoChooserTask:

As the Name suggests, the choosers shows you the WP7 picture library,from where you are allowed to pick a photo, in the completed event,
you receive a PhotoResult object that contains the Stream representation of the photo Chosen.
You Can do what you want to with the Photos’ File stream.
(Such as displaying it, uploading it to some service provider etc etc)

public partial class Page2 : PhoneApplicationPage
{
     PhotoChooserTask objPhotoChooser;
     public Page2()
     {
            InitializeComponent();
            objPhotoChooser = new PhotoChooserTask();
            objPhotoChooser.Completed += new EventHandler<PhotoResult>(objPhotoChooser_Completed);
     }
     private void btnChosePhoto_Click(object sender, RoutedEventArgs e)
        {            objPhotoChooser.Show();        }

     void objPhotoChooser_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
                MessageBox.Show("Photo Selected");
        }
}

ScreenShots:

Media Library : Album ViewPhoto List shown in a pivot

3. SavePhoneNumberTask:

This Chooser, as  the name suggests, saves a phone number in the Phone’s contacts. This chooser does not return anything. The Completed event receives argument stating the status of the operation.

Note : You need to set the PhoneNumber property before you call the Choosers show() method. (Else your code might not work)

</span>
<pre>public partial class Page2 : PhoneApplicationPage
{
     SavePhoneNumberTask objSavePhoneNumber;
     public Page2()
     {
            InitializeComponent();
            objSavePhoneNumber = new SavePhoneNumberTask();
            objSavePhoneNumber.Completed += new EventHandler<TaskEventArgs>(objSavePhoneNumber_Completed);
     }
     private void btnSavePhoneNumber_Click(object sender, RoutedEventArgs e)
     {
            objSavePhoneNumber.PhoneNumber = "123-345-4567";
            objSavePhoneNumber.Show();
     }

     void objSavePhoneNumber_Completed(object sender, TaskEventArgs e)
     {
            if (e.TaskResult == TaskResult.OK)
            {
                MessageBox.Show("Phone Number Saved..");
            }
     }
}

Screenshots:
Saving a phone number for a existing contact Phone Number Type

4. PhoneNumberChooserTask

PhoneNumberChooserTask Allows you to pick a phone number from your contacts. If the contact has multiple phone numbers, you get to pick one of the phone numbers ( Isn’t that quite handy)

public partial class Page2 : PhoneApplicationPage
{
     PhoneNumberChooserTask objPhoneNumberChooser;
     public Page2()
     {
            InitializeComponent();
            objPhoneNumberChooser = new PhoneNumberChooserTask();
            objPhoneNumberChooser.Completed += new EventHandler<PhoneNumberResult>(objPhoneNumberChooser_Completed);
     }
     private void btnChoosePhoneNumber_Click(object sender, RoutedEventArgs e)
     {
            objPhoneNumberChooser.Show();
     }

     void objPhoneNumberChooser_Completed(object sender, PhoneNumberResult e)
     {
            if (e.TaskResult == TaskResult.OK)
            {
                MessageBox.Show("Selected :" + e.PhoneNumber);
            }
     }
}

Screenshots:

5. SaveEmailAddressTask

As the name suggests, this choosers saves an email to the contact list.

6. EmailAddressChooserTask

As the name suggests, this choosers shows you the contact list from where , you can chose a  contact and your app will receive the chosen contact’s default email address. Again, if multiple email addresses are available, the user is presented a choice of picking up an email address. This is sent back to your app.

Source Code for the sample Launcher and Chooser Demo,( whose screenshots are visible above )

Once Again, thanks for your support by reading this post. Keep watching this space for more on windows Phone 7.

Next Post : Building your twitter client for Windows Phone 7 with oAuth :)

Written by sudheerkovalam

August 14, 2010 at 9:01 am

Windows Phone 7 : Launchers and Choosers

with 5 comments

Windows Phone 7 seems to have captured my attention a lot these days. So I am ( and will be ) blogging about Windows Phone 7 like crazy. I believe that it is Microsoft’s first step in the right direction (in the phone OS business). So coming back to Windows phone 7 Platform. We all, by now know that all applications in Windows Phone 7 runs in its own sandbox (execution and file storage, both). And since, we  are developing apps for windows Phone 7, we will certainly need access to common, phone related functionality, say like sending an email, SMS etc. Recently, in Community Tech Days Pune, in the Windows Phone 7 app development session by Mayur Tendulkar, a very cool app was demoed for Windows Mobile 6.x. This app would send “happy new year” or “happy holidays” message to all the contacts in your phone. The idea was pretty cool. So for designing this app, we would need access to the phone’s contact list and then, will have to use the phone’s SMS API to send out Text messages. It is a different ball game here on Windows Phone 7 platform. Windows Phone 7 doesn’t give you access to native functionality directly, so Microsoft has exposed certain common functionality that you would want to use in your apps in the form of Launchers and Choosers.

A Launcher is an API, that launches built in functionality for the user to accomplish some task and returns nothing back to the calling function in  your app. API to make calls, Send SMS or Emails etc are an example of such APIs

A Chooser on the other hand is an API , that launched a  built in functionality for the user to accomplish some task and returns back the data that was chosen by the user to the app. API for Choosing contacts, photos etc. come under this category.

Important Note : Your application de-activates (i.e. gets tombstoned), when you trigger a launcher or a chooser. (Not sure what tombstoned means, read more about Windows Phone app life cycle here ). How to use Launchers in your application : Launchers are available in Microsoft.Phone.Tasks Namespace. Make sure to add a using statement for this namespace.

As of now Following Launchers have been exposed to us (Not exactly …):

1. EmailComposeTask :

As the name suggests, The EmailComposeTask lets you compose emails and send ‘em. You will off course need to setup an email account before you can actually use the email compose functionality. The good news, if no email account has been setup, the shell will ask you to setup an account. ( I guess in the final RTW SDK, this might actually trigger email setup, if not done already)


EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.To = "bill.gates@microsoft.com";
emailComposeTask.Body = "Windows Phone Rocks!!!"
emailComposeTask.Cc = "SteveBallmer@MSFT.com";
emailComposeTask.Subject = "Windows Phone";
emailComposeTask.Show();

2. PhoneCallTask:

Again, quite evident by the name itself. Phone call task will let you make a phone call.

PhoneCallTask phoneCallTask = new PhoneCallTask();
phoneCallTask.PhoneNumber = "180018001800";
phoneCallTask.DisplayName = "Steve Jobs";
phoneCallTask.Show();

Quite a wrong person to call, I know ;)

3. SMSComposeTask :

Lets you compose an SMS

SmsComposeTask smsComposeTask = new SmsComposeTask();
smsComposeTask.To = "1800-180-1800";
smsComposeTask.Body = "Cool Phone!!";
<pre>smsComposeTask.show();</pre>

4. SearchTask :

Lets you open the shell search engine

SearchTask searchTask = new SearchTask();
searchTask.SearchQuery = "Windows Phone 7";
searchTask.Show();

5. MediaPlayerLauncher:

Will Trigger the Phone’s Media Player Application

MediaPlayerLauncher mediaPlayerLauncher = new MediaPlayerLauncher();
mediaPlayerLauncher.Media = new Uri("vs_logo2010_WMV9_640x360.wmv", UriKind.Relative);
mediaPlayerLauncher.Show();

6. WebBrowserTask:

The WebBrowserTask will let you trigger the phone’s IE mobile browser and redirect the user to the page specified.

WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.URL = "http://developer.windowsphone.com";
webBrowserTask.show();

I was not able to find much detail on these Launchers. Folks reading this block can contribute.:

7.MarketplaceDetailTask:

From the Name of it seems, it will launch the phone’s Marketplace app and show details. Not used this one.

8. MarketplaceHubTask:

Launches the Marketplace Hub, i guess. I don’t think we will be able to test this on the locked emulator.

9. MarketplaceReviewTask

10. MarketplaceSearchTask

I will be posting the next post on using the Choosers and will also post the entire solution for your ready reference. Once again, thanks for your support and keep looking at this space for more Windows Phone 7 related posts.

Written by sudheerkovalam

August 6, 2010 at 3:02 am

Windows Phone 7 Design Considerations

with 4 comments

Windows Phone 7 is an amazing platform. It delivers what it promised. But the experience is not 100% complete. Now it’s up to us to complete the experience by developing some cool apps.

Now We all are aware that a Silverlight developer can easily develop apps for Windows Phone. Yeah, we still have all the Drag and Drop goodness, but we need to keep into consideration , when we are designing the application, that the target device is a phone with 1 GHz  single core processor , Most of us will develop apps on a Core 2 Duo machine.

Since, I have been playing around with Silverlight development experience, am not sure about whether these points are exactly applicable( as is) to XNA game development. But still, here it goes:

1. Keep the User Experience simple:

The Silverlight runtime on the phone does not exactly have a lot of raw processing power available, so it has been optimized accordingly. There are certain points that you need to take into consideration when designing UI for the phone.

- Keep it simple

Less Elaborate UI means Less Code means less activity which will lead to better performance

- Limit the activity on the UI thread

The UI thread must be limited to User interaction , accepting input etc.

- Leverage the Render thread

The render thread, is separate thread that will take care of simple animations etc. This will result in smoother User Experience ( Remember, customer experience comes first)

- Leverage the GPU of the phone

We have a dedicated GPU on the phone. Use it! And Since yours is the only program that runs in the foreground, you can design your app to leverage the GPU (and by that I meant justifiable usage , remember you are running on a small handheld device )

If you are interested in drilling down more, there was a nice session at MIX’10 on Silverlight performance on Windows Phone. Seema Ramchandani’s session on Silverlight performance on Windows Phone.

2. Make sure you only upload necessary data:

As you must be aware that on a small radio device, transmitting from the device can always prove to be more costly as compared to receiving transmission ( in terms of battery life). The Same principle applies here too.

Upload/ Send to server only the data you need to, Say for example, In your app, you receive an array if  say tasks, in which say you update some of these tasks, instead of sending the entire updated array to the server ( or your backend service) send across only some information, such as only the ID of the Task, property changed and the updated value.

This will result in overall better application performance as well as better battery life on the phone ( Very crucial IMO)

3. Deactivate Quickly

In WM 6.x, apps never had an exit option, There never was an event that would let us know that the app is about to get killed. So in order to overcome this danger, what people did was to save state of the application periodically.

Well in Windows Phone 7, You do have an App Closing and App Deactivating event. ( Not sure about what that means? , read my post on WP7 app life cycle). When you receive this event, you save data to the phone’s isolated storage/ or some backend service  and retrieve it back when the app activates again.

Now If your app is mammoth and needs to save a lot of data in the deactivating event, Your app will take time to tombstone. What this will lead to is a delay in the launched/chooser to show up making the phone run sluggish.

What we can do to overcome this is  to save state  periodically ( When people say OLD IS GOLD, they aren’t kidding, are they?)

We can do something on these lines:

    // Constructor
    public App()
    {
        UnhandledException += Application_UnhandledException;

        // Standard Silverlight initialization
        InitializeComponent();

        // Phone-specific initialization
        InitializePhoneApplication();

        // Add a Timer to save state Periodically
        DispatcherTimer dt = new DispatcherTimer();
        dt.Interval = new TimeSpan(0, 0, 0, 10); // 10 seconds
        dt.Tick += new EventHandler(dt_Tick);
    }

    void dt_Tick(object sender, EventArgs e)
    {
        //Dirty Flag is set, when something that has to saved 
        // in the application's state has changed.
        if (_dirtyFlag)
        {
            // Save state incrementally.
        }
    }

    // Code to execute when the application is deactivated (sent to background)
    // This code will not execute when the application is closing
    private void Application_Deactivated(object sender, 
        DeactivatedEventArgs e)
    {
        System.Diagnostics.
            Debug.WriteLine("Go to sleep...zzz");
        if (_dirtyFlag)
        {
            // Only save state if there is a change.
        }
    }


Well these are all the points i can think off as of now.

These may not be applicable to all apps that we will write on WP7 , But i believe it is “Good to Know / Things to ponder on, when designing my WP7 app” stuff.

Any suggestions/ comments/ thoughts/ abuses are welcome.

Written by sudheerkovalam

July 26, 2010 at 5:14 am

Windows Phone 7 Process Life cycle

with 6 comments

What was made clear at Mix’10 was that third party apps in Windows Phone 7 wont be able to multi task. The reason provided was that too many apps running in the background may make the app in foreground run slowly. Once an user sees that s/he will definitely say that “Windows Phone 7 Sucks!, It is very slow and sluggish”.

Well what If we say that we will need multi tasking and will use it judiciously? well AFAIK, not Third party app multi tasking will be available in V1 ( Not sure , if MSFT intends to publish an OTA update to add multi tasking later )

With Windows phone 7, what MSFT promised was no  sluggish interfaces and apps that consume various data service and provide all the information you need in one place. And Frankly speaking off, they have done a decent job.

So, No Multi tasking, What does that mean for us developers?

Well in order to answer this question, we need to understand how an app will live on the phone ( the Windows Phone off course Open-mouthed smile )

When the app is Launched:

The app that you , me and many more developers will write will need to be launched from either the start experience or application list. When we do this, (from the programmer’s perspective) , a new instance of our application is created.  Well this does mean that we do get to write event handlers for events such as application launched etc..

However anywhere in the app, when the user presses the Start Button and/or triggers a Launcher or a chooser ( such as ‘”send an SMS” , “send an email”) etc, Your app’s state is saved and your app is put to sleep.

This process is called as “Tombstoning”

Wp7 App lifecycle

Following are the main events that we can use in our app to make our app feel as if it were really running in the background

1. Launching Event

When the app is launched, the Launching Event is fired. we can use this event, (usually an empty method pre written for you in app.xaml.cs) which we can use to instantiate stuff from the isolated storage. For e.g. , say you have an app that depends on some XML files that you need to read when the app launches, this is the event for you!, Write the code in the launching event

2. Closing Event

When the user clicks navigates through the app, a stack of page navigation is maintained. When the user hits the back button, the user is taken to previous screen.

Now when the user keep on hitting back button through the first page of the app. The app gets terminated and the closing event is fired. You can now write some app level data that you wish to persist, to the phone’s isolated storage.

3. Activated Event

Your app can be in the foreground or can be replaced with some app in foreground on some Launcher (such as send an email, call etc..). This is when the app is tombstoned and it also becomes possible that the app might not get activated again. The user can open many such apps,knocking off your app from the application stack ( the back button relies on the application stack to take you to a page in the current app or some page in previous app you had launched.) If the user were to launch the app from the start screen, it would create a new instance of the app

Now it is also possible that the user can reactivate your app by pressing the back button and coming to your app or even after the launcher completes. This is when your app is activated again. The Activated Event is fired when your app is activated after , say you complete a phone call when you were using the app . This is a good place where you can reload data you had stored in persistent store ( such as textbox data ,selected item etc . If you intend to store data entered in textboxes and you want to persist it )

4. Deactivated Event.

If an application is running and is subsequently replaced in the foreground by another application or experience, the first application will be deactivated. There are several ways in which this state can be invoked. An application will be deactivated if the user presses the Start button or if the device timeout causes the lock screen to be engaged. An application will also be deactivated when it invokes a Launcher or a Chooser, helper applications that allow the user to perform common tasks such as taking a picture or sending an email. In any of these cases, the running application will be deactivated and the Deactivated event is raised.

 

// Code to execute when the application is launching (e.g., from Start)

// This code will not execute when the application is reactivated

private void Application_Launching(object sender, LaunchingEventArgs e)
{
  //Get Data from Isolated Storage or a web service etc...
  System.Diagnostics.Debug.WriteLine("In Application_Launching event"+
     "... Nice Place to Initialize your app");
}

// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
   System.Diagnostics.Debug.WriteLine("And We are back!!");
}

// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
   System.Diagnostics.Debug.WriteLine("Go to sleep...zzz");
}

// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
   System.Diagnostics.Debug.WriteLine("goodbye cruel world.");
}

 

Hope this blog post helps you understand the Windows Phone 7 app lifecycle.

I will try and cover many more details in further posts as and how I discover them Smile

Thanks for your support. I will be back with my next post in a few days

Written by sudheerkovalam

July 21, 2010 at 4:20 pm

My Experiences in Windows Phone 7 Development :Part 2

leave a comment »

In Recently concluded Community tech days in pune, we had a sizable audience for Windows Phone 7 development session by Mayur Tendulkar. I was there in the crowd and must say, It was a good session on WP7 :)

While the in the crowd  I did realize that Not  many have started WP7 development, But still, If you have done some development using April CTP and are probably itching to download the July Beta of the tool, Behold  There are some breaking changes.

Changes in the July Beta :

1. You Cannot now use the Bing maps control for silverlight in WP7 projects :

This my friends was very misleading  in the April CTP, You must have noticed that using the Bing Maps for SL , you could actually create apps on the phone that utilize, however  the performance would have been really bad, even on the emulator (it used to take around 4-6 min to load the map ).

The SL controls used to work on the April CTP due to a glitch in the, then released SDK.

2. The issue of needing to use unsigned versions of the dll that were signed using third party certificates has now been resolved

In the April CTP, you  could not use a signed DLL from a third party , as the emulator would not allow you to use these DLLs, You would have needed to unsign these DLLs to use ‘em in your WP7 project.  the Good news is that this has now been fixed in the July Beta. Now You can use the singed DLLs that you always wanted to use

3. Some of the assemblies have been merged into a single assembly:

One thing that you will probably notice is that once you open your April CTP project after you install the beta tools, the project compilation will result into a lot of errors. Most of these have got to do with the assembly mergers and deprecation of certain controls. A more detailed blog has been written by Jamie Rodriguez from Microsoft , where this is explained in much more detail (Link to Jamie’s Blog)

Upgrading to the July Beta:

I have  heard a lot of complaining about the setup experience on upgrading from April CTP to july Beta. What I’d Suggest ( the way which worked smoothly for around 5-6 PCs in my office) is to uninstall the CTP by hitting the uninstall option for Windows Phone Developer tools CTP in the add/remove programs. This will uninstalll all the components and ask for a reboot. After the reboot is done, we can now start the installation of the July beta SDK and tools.

Issue that I have observed :

One thing, you might notice is that whenever you do a DateTime.Now in your code and you are running this code in the emulator, the emulator will always return the install date and not the system date. If this is an issue that you are facing there is a workaround for this. Go to %ProgramData%\Microsoft\XDE and delete all files with .dess extension there (These are the state files, once these are deleted you will see the current date on the emulator, However time zone is set to Alaska GMT -9). So Once you start noticing the offset, delete the .dess file and you are back on time :)

 

Much more to come in the following blog posts… Keep reading and thanks for your support

Written by sudheerkovalam

July 18, 2010 at 5:53 pm

My Experiences on Windows Phone 7 development : Part 1

leave a comment »

Wow. its been almost 6 months that I posted anything on my blog.

Anyways, I have been working on windows phone 7 for the past month or so.

This blog  post (of a series of blogs) will try and tell about my experiences of working on WP7.

First of all, We (As in our client, A Microsoft Partner Award 2010 winner) had an amazing demo at Worldwide Partner Conference. As you might have guessed, we worked on the demo and the actual product that will be unveiled soon.

I will put in my experience in much more details in days to come ( I will, I Promise!! )

Written by sudheerkovalam

July 14, 2010 at 2:02 am

Follow

Get every new post delivered to your Inbox.