Create Games for Windows Phone 7!

I have to admit, that I don’t post too much in the blog lately. I’m sorry for that!

This is not because I have nothing too blog about – I have a lot of very interesting things. I’m not writing much partly because some of those things are still under NDA, but the main reason that I simply have no time to blog – I’m leading very interesting and very tight-scheduled project.

Today (finally!) I could share some of this project details.

The project is – a new XNA Game Studio 4.0 and the Windows Phone 7 content for XNA Creators Club. I’m writing educational content about creating a games for Windows Phone 7! It has a comprehensive hands-on labs, samples and articles. I’m happy to announce, that the first part of it is now live!

Wait no longer – browse to the educational content of XNA Creators Club and start developing your games!

The content is here:

http://creators.xna.com/en-US/education/gettingstarted

image

Guess why some of items are “”? Yes, I am the author (or in case of the lab - one of the them)

The rest of published (and coming) items are product of very hard work produced by team members. They are most talented and most motivated persons I’ve seen (and believe me, I’ve seen many) – I’m very proud to work with you all of you as a team and each one personally! Thank you team!

 

Along with hard work I’m personally (and the team) having much fun doing this and I hope that you will enjoy our work as much as we do creating it!

So, what are you waiting for? Download the tools here, browse to the content and start the fun!

 

 

Stay tuned for more to come soon!

Alex

 

P.S.: Philosophical question or even a poll if you wish: do you think the company logo reflects a company’s nature?

LightSwitch Beta available!

As published today by LightSwitch team, the first beta is available for MSDN subscribers. If you have a subscription, visit your subscriptions page.

If not, the public download will be available from Monday – via the LightSwitch Developer Center.

 

For more information about this promising product visit the LightSwitch Team Blog.

 

Stay tuned,

Alex

Posted by Alex Golesh | with no comments

Silverlight for Windows Phone 7: “Tombstoning”

This post will talk about tombstoning (what a name!) – the part of application lifecycle on Windows Phone 7.

The Windows Phone execution model governs the life cycle of applications running on a Windows Phone, from when the application is launched until it is terminated.

The execution model is designed to provide end users with a fast, responsive experience at all times. To achieve this, Windows Phone allows only one application to run at a time. This eliminates the possibility of users getting their device into a state where multiple applications are running in the background, causing the application in the foreground to become sluggish. image

In addition to responsiveness, the execution model provides users with a consistent navigation experience between applications. On Windows Phone, users navigate forward by launching applications from the installed applications list or from a tile on Start. Users can also navigate backwards, through the pages of a running application, or through the stack of previously running applications by using the hardware Back button.

To enable seamless navigation by limiting the phone to run one application at a time, Windows Phone activates and deactivates applications dynamically, exposing events to developers to respond to when the application state changes. By implementing handlers for these events, developers can save and restore application state as their application transitions between active and inactive states. This behavior creates an experience in which it seems to the user like the application continued to run in the background.

The procedure in which the operating system terminates an application’s process when the user navigates away from the application called Tombstoning. The operating system maintains state information about the application. If the user navigates back to the application, the operating system restarts the application process and passes the state data back to the application.

In addition the developer could use tombstoning events in order to preserve Application state and Page state.

Application state is a state of the application that is not associated with a specific page. Application state is managed in the events exposed by the PhoneApplicationService class.

Page state is a visual state of an application page. This includes such things as the scroll position of a ScrollViewer control and the contents of TextBox controls. Page state should be managed in the OnNavigatedTo and OnNavigatedFrom event handlers.

Most important – application is not guaranteed to wake up from tombstoned state, so preserve all really important things in persistent storage  (like Isolated Storage)! This will give you a chance to restore the data when application will be launched.

After short theoretical part lets get to business :)

Imagine you have multiple page application. Application collects some information from user and sends it to corporate server (WCF backend which will store the information somewhere) – in my case I have “Field Note” application, which allows to collect notes an send it to my WCF service. The service is very simple.

Data class:

[DataContract]
  public class Article
  {
    [DataMember]
    public Guid ID;

    [DataMember]
    public string Title;

    [DataMember]
    public string Body;

    [DataMember]
    public int AuthorID;

    [DataMember]
    public string AuthorName;

    [DataMember]
    public DateTime Date;
  }

The interface:

[ServiceContract(Namespace = "http://www.alexgolesh.com/services/StorageService")]
  public interface IStorageService
  {
    [OperationContract, WebGet]
    Guid SaveArticle(Article info);
  }

Phone application will submit data here… But before data could be submitted user first have to fill it out on the device. While writing simple “blah-blah-blah” on emulator is very fast task without real chance to be interrupted, composing real note could take some time and on real device many interruptions could happen, for example incoming call, user switches to calendar application to check exact dates related to the note, SMS arrived, etc. In all those cases application should preserve the state seamlessly to user (even giving the fact that the different application instance could be launched next time). From user’s point of view the unsaved/non-submitted data should stay. Here tombstoning events come to play.

Application template includes 2 events which will be launched when application being tombstoned (dehydrated) and when it comes back. In addition, 2 events will fire when application first launches and when it completely closes.

When the user taps the entry for the application in the phone’s installed applications list or the tile for the application on Start application starts, and Launching event is raised.

When application is running, there is a possibility is that the user presses the hardware Back button to navigate backwards through the pages of the application and even past the application’s first page. When this occurs, the Closing event is raised and the application is terminated.

When 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  the device timeout causes the lock screen to be engaged or application invokes a Launcher or a Chooser. In any of these cases, the running application will be deactivated and the Deactivated event is raised.

When the application has been deactivated and tombstoned, it is possible that it will never be reactivated: user could launch the application again from Start invoking a new instance of the application, or the user could launch several other applications knocking the tombstoned application off of the back of the application stack where it cannot be reached with the Back button. It is also possible that the user will return to the application. This could happen if the user presses the Back hardware key until the application is reached or if a Launcher or Chooser was the cause of the deactivation, the user could complete the task or cancel out of it. When the user returns to a tombstoned application, it is reactivated and the Activated event is raised.

In my sample app I’ll preserve the unsaved date in Applicaton State in case of tombstoning, and will try to reload it in case of activation.

All the pages in my application are using the same data object, thus I initiated it as a DataContext for the Application’s Frame.

When deactivating:

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
  //Add current data object to Application state
  PhoneApplicationService.Current.State.Add(StateKey, RootFrame.DataContext as Article);
}

If it is lucky enough to get activated:

private void Application_Activated(object sender, ActivatedEventArgs e)
    {
      //Create new data object variable
      Article article = null;

      //Try to locate previous data in transient state of the application
      if (PhoneApplicationService.Current.State.ContainsKey(StateKey))
      {
        //If found, initialize the data variable and remove in from application's state
        article = PhoneApplicationService.Current.State[StateKey] as Article;
        PhoneApplicationService.Current.State.Remove(StateKey);
      }

      //If found set it as a DataContext for all the pages of the application
      //An application is not guaranteed to be activated after it has been tombstoned, 
      //thus if not found create new data object
      if (null != article)
        RootFrame.DataContext = article;
      else
        RootFrame.DataContext = new Article();

      (RootFrame.DataContext as Article).PropertyChanged += 
new System.ComponentModel.PropertyChangedEventHandler(article_PropertyChanged); }

Note: I’m subscribing to PropertyChanged of Article object in order to know when my data is “dirty” (changed).

When user closes the application, and for sure next time the new instance will ne activated I’m preserving the date in Isolated Storage:

private void Application_Closing(object sender, ClosingEventArgs e)
    {
      if (!(bool)Application.Current.Resources[IsSyncedKey])
      {
        using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
        {
          //If user choose to save, create a new file
          using (IsolatedStorageFileStream fs = isf.CreateFile(FileName))
          {
            //and serialize data
            XmlSerializer ser = new XmlSerializer(typeof(Article));
            ser.Serialize(fs, RootFrame.DataContext as Article);
          }
        }
      }
      else
      {
        using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
        {
          if (isf.FileExists(FileName))
            isf.DeleteFile(FileName); //delete synced data forom temp storage
        }
      }
    }
Note: I’m saving the date only if it still not synced with the server

When the user starts the application for the first time I need to check if I have some data from previous session, and if yes reload it for current session:

private void Application_Activated(object sender, ActivatedEventArgs e)
    {
      //Create new data object variable
      Article article = null;

      //Try to locate previous data in transient state of the application
      if (PhoneApplicationService.Current.State.ContainsKey(StateKey))
      {
        //If found, initialize the data variable and remove in from application's state
        article = PhoneApplicationService.Current.State[StateKey] as Article;
        PhoneApplicationService.Current.State.Remove(StateKey);
      }

      //If found set it as a DataContext for all the pages of the application
      //An application is not guaranteed to be activated after it has been tombstoned, 
      //thus if not found create new data object
      if (null != article)
        RootFrame.DataContext = article;
      else
        RootFrame.DataContext = new Article();

      (RootFrame.DataContext as Article).PropertyChanged += 
new System.ComponentModel.PropertyChangedEventHandler(article_PropertyChanged); }

Note: I’m subscribing to PropertyChanged of Article object in order to know when my data is “dirty” (changed) – exactly like I did in Activated case.

We almost there… My application UI (the page which really does data entry) looks like the following:

image

First two input fields are part of my Article object, but last one is not… this means it will not be preserved along with my data context… For such case I’ll use Page State and save this data in case of tombstoning there. In case of navigating away from the app itself I’ll save this info in Application Setting (in Isolated Storage). To hook up with page state I’ll override OnNavigatedTo and OnNavigatedFrom event handlers. They will fire in any case of arriving to the page and leaving the page.

First let’s look at OnNavigatedFrom:

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
    {
      if (null == e.Content) //Navigating outside the application - application being tombstoned
      {
        //Save it also to Isolated storage, since application could not resurrect
        if (IsolatedStorageSettings.ApplicationSettings.Contains(stateKey))
          IsolatedStorageSettings.ApplicationSettings[stateKey] = txtPersonalNotes.Text;
        else
          IsolatedStorageSettings.ApplicationSettings.Add(stateKey, txtPersonalNotes.Text);

        //Anyway save it to page state
        if (State.ContainsKey(stateKey))
          State.Remove(stateKey);

        State.Add(stateKey, txtPersonalNotes.Text);
      }
      else //navigating back to first page - not tombstoned, state couldn't help here
      {
        if (PhoneApplicationService.Current.State.ContainsKey(stateKey))
          PhoneApplicationService.Current.State.Remove(stateKey);

        PhoneApplicationService.Current.State.Add(stateKey, txtPersonalNotes.Text);
      }

      base.OnNavigatedFrom(e);
    }

Note: if NavigationEventArgs has a Content, thus we are navigating inside the application. Alternatively you could check the Uri in NavigationEventArgs – if navigating away it will indicate “external”

image

When getting back to the page:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {

      //try to find the value in State first;
      //Will catch the resurrection and navigating from First Page
      if (State.ContainsKey(stateKey))
        txtPersonalNotes.Text = State[stateKey].ToString();
      else if (IsolatedStorageSettings.ApplicationSettings.Contains(stateKey)) //try to find in Isolated storage
      {
        txtPersonalNotes.Text = IsolatedStorageSettings.ApplicationSettings[stateKey].ToString();
        IsolatedStorageSettings.ApplicationSettings.Remove(stateKey);
      }
      else if (PhoneApplicationService.Current.State.ContainsKey(stateKey))
      {
        txtPersonalNotes.Text = PhoneApplicationService.Current.State[stateKey].ToString();

        PhoneApplicationService.Current.State.Remove(stateKey);
      }

      base.OnNavigatedTo(e);
    }

Well, thats it… The rest of logic not related to the tombstoning and could be skipped here.

Source for this sample is here.

Stay tuned for more,

Alex

Silverlight for Windows Phone 7: Launchers and Choosers

This post will talk about launchers and choosers mechanism in Windows Phone 7 applications.

The Windows Phone application model isolates every application in its own sandbox, both for execution and file storage. Applications are not able to directly access common stores of information, such as the contacts list to directly invoke other applications such as the phone or messaging applications. To enable scenarios that require common tasks such as these, Windows Phone exposes a set of APIs referred to as Launchers and Choosers that allow applications indirect access to these useful phone features. The Launcher and Chooser APIs invoke distinct built-in applications that replace the currently running application.

A Launcher is an API that launches one of the built-in applications through which a user completes a task, and in which no data is returned to the calling application. An example of this is the PhoneCallTask. An application can provide this Launcher with a phone number and a display name with which to invoke the phone. When the Phone application is displayed, the user can choose whether to initiate a call using the supplied parameters. When the user closes the Phone application, the calling application is usually activated again, but the Phone application does not return any data about or resulting from the user’s actions. When an application invokes a Launcher, it does not get a return value.

A Chooser is an API that launches one of the built-in applications through which a user completes a task, and which returns some kind of data to the calling application. An example of this is the PhotoChooserTask. An application can use this Chooser to show the Photo Chooser application. The user can either select a photo or cancel out of the Photo Chooser. Usually, when this occurs, the calling application is activated and supplied with the Chooser result. The result includes a value that indicates whether the user completed the task and, if the user did complete the task, the result includes an IO stream that contains the image data of the chosen photo. Note: that after the Photo Chooser chooser is launched, the user can also press the Start button and select another application. In this case, the calling application may never be reactivated and the result of the Chooser may never be returned. Applications should expect and handle this ambiguity properly.

Recall application I created to introduce push notifications. This application uses two launchers (SearchTask and EmailComposeTask) and one Chooser (EmailAddressChooserTask).

All the launchers work very similar way – create new instance of correspondent launcher class, add launcher properties (where relevant) and invoke Show() function. For example, launching search task looking for myself:

SearchTask searchTask = new SearchTask();
searchTask.SearchQuery = "Alex Golesh";
searchTask.Show();

The result will show the follwing screen:

image

Note: for the first time after emulator startup you could see the following screen:

image

Accept privacy statement – it happens only once between emulator restarts and only once in real device.

The second launcher (EmailComposeTask) expects the mail address. It could be provided just as a string, but in-real world application user expect to select it from his contacts and if not found enter manually. To provide the email address I’ll use EmailAddressChooserTask. Using the Choosers in generally is pretty similar to using launchers with one big difference – you have to subscribe to Completed event to receive your data back:

EmailAddressChooserTask emailAddressChooserTask; //defined at class level
////////////////////////////////////
emailAddressChooserTask = new EmailAddressChooserTask(); emailAddressChooserTask.Completed += (s, args) => { if (args.TaskResult == TaskResult.OK) { EmailComposeTask emailComposeTask = new EmailComposeTask(); emailComposeTask.To = args.Email; emailComposeTask.Subject = "Weather Sample"; emailComposeTask.Body = "Hi!\nJust wanted to share, how good Weather sample is!\n\nTake care!"; emailComposeTask.Show(); } }; emailAddressChooserTask.Show();

Note: to create a create a contact(s) on emulator use “Add email” menu item of sample application :)

Sources here.

Stay tuned for more posts about Windows Phone 7 development,

Alex

Silverlight for Windows Phone 7: Push Notifications (Part 2 of 2)

In previous post I described how to build server part of push notification mechanism for Windows Phone 7. This time I’ll show how to handle push notifications on the phone.

To demonstrate it I created pretty simple Silverlight application for Windows Phone. The UI of this application looks like the follows:

image

Lets see how the push mechanism is implemented. Phone API defines a class, which responsible for push notifications: HttoNotificationChannel. This class is responsible for subscribing to events and receiving those messages once they arrives.

Phone registers to such channel with channel name (and optionally service name). Once channel is opened, phone will get the event. In addition, channel could be “retrieved” by name – this helps to maintain minimum required number of opened channels from the phone to MPNS.

Best practice is to try find the existing channel first, and only if it is not found then open new channel.

The major difference between opened channel and not opened is ChannelUri property – this property initialized only when channel opened (or found and retrieved). My phone application will try to find existing channel, and if not will open a new one. After channel opened or found it will register the channel (ChannelUri) with my cloud service. This Uri will be used by service to send a notifications to the phone. In addition it will subscribe to various channel events – some of them to respond on arrived messages, some of them to handle possible communication errors. Lets see “DoConnect” function which executed in sample’s constructor:

//First, try to pick up existing channel
        httpChannel = HttpNotificationChannel.Find(channelName);

        if (null != httpChannel)
        {
          SubscribeToChannelEvents();

          SubscribeToService();
          SubscribeToNotifications();

          Dispatcher.BeginInvoke(() => UpdateStatus("Channel recovered"));
        }
        else
        {
          //Create the channel
          httpChannel = new HttpNotificationChannel(channelName, "HOLWeatherService");

          //Register to UriUpdated event - occurs when channel successfully opens
          httpChannel.ChannelUriUpdated += 
new EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated); SubscribeToChannelEvents(); httpChannel.Open(); Dispatcher.BeginInvoke(() => UpdateStatus("Channel open requested")); }

Exactly according to best practice first it tries to find a channel and if not found opens a new one. If channel found, then the variable will be initialized and ChannelUri returned from MPNS. Same will happen after successful Open command.

SubscribeToService function (executed also from httpChannel_ChannelUriUpdated handler) calls the WCF Registration service (described in first part):

private void SubscribeToService()
    {
      RegistrationSVC.RegistrationServiceClient client = new RegistrationSVC.RegistrationServiceClient();
      client.RegisterCompleted += (s, e) =>
        {
          if (null == e.Error)
            Dispatcher.BeginInvoke(() => UpdateStatus("Registration succeeded"));
          else
            Dispatcher.BeginInvoke(() => UpdateStatus("Registration failed: " + e.Error.Message));
        };
      client.RegisterAsync(httpChannel.ChannelUri.ToString());
    }

And subscribing to channel events do the following:

private void SubscribeToChannelEvents()
{
  //Subscribe to the channel events
  httpChannel.HttpNotificationReceived += 
new EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived); httpChannel.ShellToastNotificationReceived +=
new EventHandler<NotificationEventArgs>(httpChannel_ShellToastNotificationReceived); httpChannel.ErrorOccurred +=
new EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ExceptionOccurred); }

When notification received (in my case I have to take care for real only for RAW notifications), event handler function will parse received payload and initialize UI fields with received data:

private void ParseRAWPayload(Stream e, out string weather, out string location, out string temperature)
    {
      XDocument document;

      using (var reader = new StreamReader(e))
      {
        string payload = reader.ReadToEnd().Replace('\0', ' ');
        document = XDocument.Parse(payload);
      }

      location = (from c in document.Descendants("WeatherUpdate")
                  select c.Element("Location").Value).FirstOrDefault();
      Trace("Got location: " + location);

      temperature = (from c in document.Descendants("WeatherUpdate")
                     select c.Element("Temperature").Value).FirstOrDefault();
      Trace("Got temperature: " + temperature);

      weather = (from c in document.Descendants("WeatherUpdate")
                 select c.Element("WeatherType").Value).FirstOrDefault();
    }

Once all the data parsed I could update the UI:

void httpChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
    {
      string weather, location, temperature;
      ParseRAWPayload(e.Notification.Body, out weather, out location, out temperature);

      Dispatcher.BeginInvoke(() => this.PageTitle.Text = location);
      Dispatcher.BeginInvoke(() => this.txtTemperature.Text = temperature);
      Dispatcher.BeginInvoke(() => this.imgWeatherConditions.Source = 
new BitmapImage(new Uri(@"Images/" + weather + ".png", UriKind.Relative))); }

This way my UI updated with data sent from Cloud Service Client (Silverlight) application.

In order to receive Toast & Tile events, I have to bind the channel to Toast notifications:

httpChannel.BindToShellToast();

and also bind it to Tile notifications:

Collection<Uri> uris = new Collection<Uri>();
uris.Add(new Uri("http://devcorner.info/Notifications/DevCorner.png"));

httpChannel.BindToShellTile(uris);

Now my application complete :)

Instructions to run: the whole project could be executed from single machine – just change service references in phone & Silverlight client projects. But – this is IMHO not so interesting :) Compile phone part only and deploy XAP file to emulator (pr real device if you already lucky to have it) using XAP Deployment utility installed with Windows Phone Developer Tools (WPDT):

image

Navigate to the list of phone applications and long click on “Weather Sample [DevCorner]” icon. Select “Pin to start”:

image

Now start the application from start tile

image

and navigate to Silverlight client hosted on my site here. Send notification to emulator running on YOUR machine from my site and see it arrives:

image

Click “Windows” button and send Toast & Tile alerts:

image

Sources here.

Stay tuned for more posts about new features of Windows Phone 7!

Alex

Silverlight for Windows Phone 7: Push Notifications (Part 1 of 2)

Now, after Beta tools released it is a time to start talking about new features and changes since Apirl CTP.

This is the first part of two parts blog post about push notification mechanism in Windows Phone 7. The API described in this article according to recently released Beta version of Windows Phone Development Tools (WPDT).

Windows Phone 7 application can’t run in the background (performance, battery life, usage of radio) and therefore there is a need to have a mechanism that facilitates a communication channel between backend services and application on the phone. Push Notification is the mechanism through which backend services can send “messages” to the phone to notify the user for any state changes. The Push Notification service is designed to provide a cloud service with a dedicated, resilient, and persistent channel for pushing a notification to a mobile device.

image

When a cloud service needs to send a push notification to a device, it sends a notification request to the Push Notification service, which in turn routes the notification to the application, or to the device as a toast or tile notification, depending on the type of notification that is sent.

The Push Client on the device receives push notifications through a notification channel. When the channel is created, a subscription is also created which allows the cloud service to push notifications to that channel. A channel is represented by a URI which contains all of the information associated with the subscription.

Once an application receives the push notification, it can access the cloud service using the cloud service’s protocol to retrieve any needed information.

Since, applications today tends to share multiple screens running on local computer, in the cloud and on the phone. The push notification services, enables seamless integration between all three with a simple and unified API.

This post will talk about creating the Cloud Service (in my case IIS hosted WCF service) which will talk to Microsoft Push Notification Service (MPNS). In addition I’ll use Silverlight application to send a messages through this WCF service to registered phone clients.

I’ll start from creating the WCF service (Actually two of them, but second is not related to Push Notification directly).

Notification messages sent through MPNS could be from 3 types:

RAW HTTP notification – notification passed to the phone application in user defined format. The data constructed by cloud service, and need to be parsed in phone application according to application logic

TOAST notification - special kind of push notification which displays as an overlay onto the user’s current screen. For example, a weather application may wish to display a toast notification if a severe weather alert is in effect. If the user decides to click the toast notification, the application can launch and perform other actions. A cloud service can control a toast notification’s title and sub-title. The toast notification will also display the application’s icon that is included in the application’s deployment package. Notification format:
Content-Type: text/xml
X-WindowsPhone-Target: toast
   
<?xmlversion="1.0"encoding="utf-8"?>
<
wp:Notification xmlns:wp="WPNotification">
   <
wp:Toast>
      <
wp:Text1><string></wp:Text1>
      <
wp:Text2><string></wp:Text2>
   </
wp:Toast>
</
wp:Notification>

Tile notification - is a visual, dynamic representation of an application or its content within the Quick Launch area of the phone’s Start experience. For example, a weather application may choose to display the user’s local time and climate conditions in a tile. Because a cloud service can alter its tile’s appearance at any time, this mechanism can be used to communicate information to the user on an ongoing basis. A cloud service can control a tile's background image, counter (or 'badge'), and title properties. Notification format:
Content-Type: text/xml
X-WindowsPhone-Target: token
   
<?xmlversion="1.0"encoding="utf-8"?>
<
wp:Notification xmlns:wp="WPNotification">
   <
wp:Tile>
      <
wp:BackgroundImage><backgroundimage path></wp:BackgroundImage>
      <
wp:Count><count></wp:Count>
      <
wp:Title><title></wp:Title>
   </
wp:Tile>
</
wp:Notification>

My WCF service will expose 3 functions (each one for corresponding notification type) and will use Silverlight 4 polling duplex mechanism (http://msdn.microsoft.com/en-us/library/cc645027(VS.95).aspx) to callback client once message being dispatched through MPNS.

Service interface:

[ServiceContract(Namespace = "http://www.alexgolesh.com/services/NotificationService", CallbackContract = 
typeof(INotificationClient))] public interface INotificationService { [OperationContract] void SendRAWNotification(List<Uri> Uris, byte[] payload); [OperationContract] void SendToastNotification(List<Uri> Uris, string message1, string message2); [OperationContract] void SendTileNotification(List<Uri> Uris, string TokenID, string BackgroundImageUri, int Count, string Title); }

Callback interface:

[ServiceContract]
  public interface INotificationClient
  {
    [OperationContract(IsOneWay = true)]
    void NotifyOnMessageSend(WindowsPhone.PushNotificationManager.CallbackArgs args);
  }

The service implementation is very easy – I’ll use external reusable library to communicate with MPNS:

public class NotificationService : INotificationService
  {
    INotificationClient client;

    #region INotificationService Members

    public void SendRAWNotification(List<Uri> Uris, byte[] payload)
    {
      client = OperationContext.Current.GetCallbackChannel<INotificationClient>();

      NotificationSenderUtility.SendRawNotification(Uris, payload, SendNotificationToMPNSCompleted);
    }

    public void SendToastNotification(List<Uri> Uris, string message1, string message2)
    {
      client = OperationContext.Current.GetCallbackChannel<INotificationClient>();

      NotificationSenderUtility.SendToastNotification(Uris, message1, message2, SendNotificationToMPNSCompleted);
    }

    public void SendTileNotification(List<Uri> Uris, string TokenID, string BackgroundImageUri, int Count, string Title)
    {
      client = OperationContext.Current.GetCallbackChannel<INotificationClient>();

      NotificationSenderUtility.SendTileNotification(Uris, TokenID, BackgroundImageUri, Count, Title, 
SendNotificationToMPNSCompleted); } private void SendNotificationToMPNSCompleted(CallbackArgs response) { client.NotifyOnMessageSend(response); } #endregion }

Not the interesting part – the NotificationSenderUtility. This utility handles all the communications to MPNS. All the “main” functions will work according to simple algorithm: prepare payload (the message in format according to notification type – will use “helper” functions), and send the message to each URI in the list received from Cloud Service Client. The payload should be the XML messages (as defined above), in byte array format. To communicate with MPNS I’ll use HttpWebRequest class. Method used in communication – POST. In addition I have to set some request headers in order to make MPNS handle my request correctly.

Let’s see for example one of “PrepareXXXPayload” helper functions:

private static byte[] prepareToastPayload(string text1, string text2)
    {
      MemoryStream stream = new MemoryStream();

      byte[] prefix = Encoding.UTF8.GetBytes("Content-Type: text/xml\r\nX-WindowsPhone-Target: toast\r\n\r\n");
      stream.Write(prefix, 0, prefix.Length);

      XmlWriterSettings settings = new XmlWriterSettings() { Indent = true, Encoding = Encoding.UTF8 };
      XmlWriter writer = XmlWriter.Create(stream, settings);
      writer.WriteStartDocument();
      writer.WriteStartElement("wp", "Notification", "WPNotification");
      writer.WriteStartElement("wp", "Toast", "WPNotification");
      writer.WriteStartElement("wp", "Text1", "WPNotification");
      writer.WriteValue(text1);
      writer.WriteEndElement();
      writer.WriteStartElement("wp", "Text2", "WPNotification");
      writer.WriteValue(text2);
      writer.WriteEndElement();
      writer.WriteEndElement();
      writer.WriteEndDocument();
      writer.Close();

      byte[] payload = stream.ToArray();
      return payload;
    }

In this function I’m using XmlWriter to create XML according to format described above and write it to MemoryStream. Once I finished I’m returning the byte array from the memory stream. This is exactly the payload I need to send to MPNS.

Function which uses this prepareToastPayload method is public function being executed from my WCF:

public static void SendToastNotification(List<Uri> Uris, string message1, string message2, 
SendNotificationToMPNSCompleted callback) { byte[] payload = prepareToastPayload(message1, message2); foreach (var uri in Uris) SendNotificationByType(uri, payload, NotificationType.Toast, callback); }  

Now the main “communication part” of the utility – the SendMessgae function. This function is used by SendNotificationByType and prepares an HttpWebRequest, sets the headers according to the message types and handles the Request/Response events to the MPNS:

private static void SendMessage(Uri channelUri, byte[] payload, NotificationType notificationType, 
SendNotificationToMPNSCompleted callback) { //Check the length of the payload and reject it if too long if (payload.Length > MAX_PAYLOAD_LENGTH) throw new ArgumentOutOfRangeException("Payload is too long. Maximum payload size shouldn't exceed "
+ MAX_PAYLOAD_LENGTH.ToString() + " bytes"); try { //Create and initialize the request object HttpWebRequest request = (HttpWebRequest)WebRequest.Create(channelUri); request.Method = WebRequestMethods.Http.Post; request.ContentType = "text/xml; charset=utf-8"; request.ContentLength = payload.Length; request.Headers[MESSAGE_ID_HEADER] = Guid.NewGuid().ToString(); request.Headers[NOTIFICATION_CLASS_HEADER] = ((int)notificationType).ToString(); if (notificationType == NotificationType.Toast) request.Headers[WINDOWSPHONE_TARGET_HEADER] = "toast"; else if (notificationType == NotificationType.Token) request.Headers[WINDOWSPHONE_TARGET_HEADER] = "token"; request.BeginGetRequestStream((ar) => { //Once async call returns get the Stream object Stream requestStream = request.EndGetRequestStream(ar); //and start to write the payload to the stream asynchronously requestStream.BeginWrite(payload, 0, payload.Length, (iar) => { //When the writing is done, close the stream requestStream.EndWrite(iar); requestStream.Close(); //and switch to receiving the response from MPNS request.BeginGetResponse((iarr) => { using (WebResponse response = request.EndGetResponse(iarr)) { //Notify the caller with the MPNS results OnNotified(notificationType, (HttpWebResponse)response, callback); } }, null); }, null); }, null); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { //Notify client on exception OnNotified(notificationType, (HttpWebResponse)ex.Response, callback); } throw; } }

Constants used in this function defined as follows:

public const string MESSAGE_ID_HEADER = "X-MessageID";
public const string NOTIFICATION_CLASS_HEADER = "X-NotificationClass";
public const string NOTIFICATION_STATUS_HEADER = "X-NotificationStatus";
public const string DEVICE_CONNECTION_STATUS_HEADER = "X-DeviceConnectionStatus";
public const string SUBSCRIPTION_STATUS_HEADER = "X-SubscriptionStatus";
public const string WINDOWSPHONE_TARGET_HEADER = "X-WindowsPhone-Target";
public const int MAX_PAYLOAD_LENGTH = 1024;

The very same way done the rest of this communication service…

The second service I have is a “RegistrationService”, which registers the Windows Phone 7 client applications, and provides the registrants data to Cloud Service Client application. The service is super simple – here the interface it implements:

[ServiceContract(Namespace = "http://www.alexgolesh.com/services/RegistrationService")]
  public interface IRegistrationService
  {
    [OperationContract, WebGet]
    void Register(string uri);

    [OperationContract, WebGet]
    void Unregister(string uri);

    [OperationContract, WebGet]
    List<Uri> GetRegisteredSubscribers();
  }

Now the client – simple Silverlight 4 application, which uses provides an “operator” the UI to send weather information to registered clients. It uses Registration services to get the list of connected clients, and Notification service to sent message with data according to type user selects to send. The UI is pretty simple:

image

The client application (and services) are available online here.

Sources here.

Stay tuned for the next part – I’ll show the phone part of the picture.

Alex

Windows Phone 7 Tools Beta Available for Download

Windows Phone 7 Tools beta available for download.

Download from here:

http://www.microsoft.com/downloads/details.aspx?FamilyID=c8496c2a-54d9-4b11-9491-a1bfaf32f2e3

image

The Beta includes:

  • Visual Studio 2010 Express for Windows Phone
  • Windows Phone Emulator
  • Silverlight for Windows Phone
  • XNA Game Studio 4.0
  • Expression Blend 4 for Windows Phone Beta.

 

Posts about new features & techniques – to follow very soon :)

 

 

Stay tuned,

Alex

Silverlight 4 – Open House

Silverlight 4 coming to the North (of Israel)!

Tomorrow afternoon I’ll hold an open house about Silverlight 4 for Haifa and surroundings based developers.

The open house will take a place in Philips building (building No. 34) at MATAM (Haifa industrial area).

Registration is FREE but required (subject to free sitting places availability and auditorium capacity).

More information and registration proceed here.

Thanks to Sela Group and Philips Israel to organize it!

 

Cool samples, live coding and Q&A session promised :)

 

 

See you there tomorrow!

Alex

Silverlight for Symbian goes RTM

Microsoft just announced the general availability of Silverlight for Symbian. This brings the Silverlight experience to the 20+ million users of Nokia S60 5th edition Nokia 5800 XPressMusic and Nokia N97 devices. Highlighted features in this product are:

  • Media: Hardware assisted Media playback of H.264 content. This gives a great media viewing experience using full hardware decode and hardware post processing.

  • IIS Smooth Streaming: Enables users to access live and on demand media content streamed using IIS Smooth Streaming including multiple bit rate switching.

  • Rich UI: Developers get access to the Silverlight V2 surface area to create Rich Interactive Web Applications.

  • .NET Programmability: .NET Compact Framework class libraries and runtime.

Nokia users can download Silverlight from the Ovi Store. Nokia S60 5th Edition devices such as Nokia 5800 XpressMusic and N97 are supported.

This release provides Nokia users with wide range of applications developed with Silverlight 2.

Silverlight for Symbian Developer tools download here.

You can create Silverlight-based applications for devices by using Expression Blend 2 (free trial version), Visual Web Developer 2008 Express with SP1, or Visual Studio 2008 SP1 with Silverlight Tools for Visual Studio 2008 SP1.

 

Stay tuned,

Alex

I’m Microsoft MVP for second time!

About an hour ago, I received an email presenting me with the Microsoft MVP Award in Silverlight!

image 

I am very honored to receive an MVP Award for second year in row and I will continue contributing to the online and offline developer community in Israel and abroad.

This is a great opportunity and place to thank quite a few people who helped me to win this Award for the second year in row:

  • My wife and daughter for having so much patience and providing the best support I could only dream about!
  • My current and past managers (Dudu, Caro, Ishai, Alon) and coworkers at Sela Group, which is easily the best software company to work for that I could think of;
  • Guy Burstein of Microsoft Israel (and a former MVP himself);
  • All other peoples who helped me get this MVP award;

Stay tuned for posts on Silverlight (and not only)!

Alex

New Desktop

Seems many of us changing primary PC those days… Following Sasha’s announcement about new desktop, I want to present my new desktop too – the old machine is also about 3 years old.

Ironically, a day after assembling and installing the new system, old machine had one of HDD failure and right now I’m fighting nasty Trojan Horse VirusWho said, that computers don’t feel what’s happening around?

I also used Alon’s recommendations to build my new machine and finally assembled it as follows:

Intel i7 930 processor @ 2.80 Ghz (overclocked to 3.0Ghz), 8Mb cache

Gigabyte GA-X58A-UD7 motherboard (SATA2, SATA3 & USB 3.0 ports)

Team Xtreem Dark DDR3 1600Mhz 4Gb x 3 – total 12Gb of RAM

Intel 80Gb SSD X25-M (system disk)

Seagate Barracuda 1.5Tb 7200RPM HDD x2 (storage disks)

Asus ATI Radeon HD 5870 graphics card with 1 GB DDR5 memory and DirectX 11 support (also slightly overclocked)

Cooler Master HAF-932 full tower case

Thermaltake ThroughPower 750w power supply24” LED Backlit LCD Computer Monitor W2486L

LG W2486L 24” 1080p LED Backlit LCD Monitor (still waiting this one to arrive)

 

After tweaking a little bit my sytem setting, removing page file (who need it if computer has 12Gb of memory), the system rocks!

My biggest impression (exactly like Sasha’s) right now is the boot speed of system (about 17 seconds), install speed (Office 2010 install was <2.5 minutes):

and office 2010 applications launch (less than 1 second):

 

In my case the SSD sustained read transfer rate in my case is ~240Mb/s!!!

Some screenshots of the system:

image

image image

image

In my case I’ve got almost maximum for SSD, and final mark for my setup is unbelievable 7.5!!!

image

(In my case the bottleneck is a CPU!)

Getting ~60FPS in all games tried until now (all setting maxed out) – too bad, that I almost have no time to play

image

Just installed Visual Studio 2010 Ultimate and Expression 4 Ultimate – blazing fast, exactly how the developer machine should be!

 

Stay tuned,

Alex

Posted by Alex Golesh | with no comments

Silverlight 4 @WDC

Thanks for all participants at WDC monthly meeting! I really enjoyed to present Silverlight 4 before such nice audience!

I really enjoyed the Q&A session ah the end of the meeting. If you have more questions – keep them coming!

image

As promised, I’m posting the links for demos and presentation for your convince.

Presentation slides are here. You could see them online (guess what – pure Silverlight presentation) at my home page:

http://www.devcorner.info/

 

Demo #1 – Webcam, Printing, Install OOB here.

Demo #2 – Elevated OOB here

Demo #3 – Localized Text Editor here.

Demo #4 – HTML Hosting sample is here.

Demo #5 – Localized LOB sample here.

 

 

See you next time!

Alex

http://www.alexgolesh.com/

http://www.alexgolesh.net/

http://www.alexgolesh.info/

Windows Phone Developer Tools CTP Refresh Available

Windows Phone Developer Tools CTP refresh available! This build is compatible with Visual Studio 2010 RTM! For those who are in Silverlight development – from now it is possible to develop Silverlight 4 applications with Silverlight 4 RTW and Windows Phone 7 applications with this CTP refresh.

 

The download location here.

Make sure you are reading what’s new document here and Release Notes (from download location). Additional information about changes could be found here.

 

Enjoy!

Alex

Silverlight 4 Available

Silverlight 4 finally here!!!

It works with Visual Studio 2010 RTM!

All downloads you need to start developing great line of business applications:

Silverlight 4 Tools for Visual Studio 2010

Blend 4 RC here

Silverlight 4 Toolkit (April 2010)

 

For those who are in Windows Phone 7 development: Do not install this build! If you need to develop for Windows Phone 7 stay with Silverlight 4 RC build and Visual Studio 2010 RC. The update for Windows Phone 7 tools is not ready yet and will be available in a few weeks.

 

Stay tuned,

Alex

DevAcademy 4 – the event is over…

Today we had great event – DevAcademy 4 – for the developers in Israel. Thanks for all participants, organizers and sponsors!

 

image

I had a session about Silverlight 4 new features.

Thanks for all attendees! It was a pleasure to present for such nice audience!

As promised, the sessions slides here.

image

For samples visit “Samples” page

image

Direct samples links:

Text Editor

Silverlight 4 Features

 

Stay tuned for articles about Silverlight 4 and Windows Phone 7 development – arriving soon!

 

 

Enjoy,

Alex

More Posts Next page »