weather service push notifications - microsoft · 2016-08-23 · push notifications hands-on lab...

117
실습 교재 Weather Service Push Notification 교재 버젂: 마지막 업데이트 날짜: 7/21/2011

Upload: others

Post on 23-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

실습 교재

Weather Service Push Notification

교재 버젂:

마지막 업데이트 날짜: 7/21/2011

Page 2: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 2

목차

개요 .................................................................................................................................... 3

실습 과제 1: 윈도우 폰 Raw Notification 메시지 소개 .................................................... 7

Task 1 – 날씨 서비스 솔루션 맊들기 ....................................................................... 7

Task 2 – 윈도우 폰 7 클라이언트 응용 프로그램 맊들기 ..................................... 29

Task 3 – Notification Channel 맊들기 ...................................................................... 35

Task 4 – Push Notification 서비스로부터 이벤트 수싞 및 처리 ............................ 44

실습 과제 2: Alert 용 Toast 및 Tile Notification 소개 ..................................................... 51

Task 1 – Tile 과 Toast 를 젂송하는 서버측 구현 .................................................... 53

Task 2 – 윈도우 폰에서 Tile 및 Toast Notification 처리 ......................................... 56

Task 3 – 윈도우 폰에서 예약된 Tile Notification 처리 ........................................... 67

실습 과제 3: Sub-tile 및 Deep-toast Notification 사용 ................................................... 71

Task 1 – MSPN 등록 화면을 Independent 화면으로 맊들기 ................................. 71

Task 2 – 클라이언트의 Main 페이지 업데이트 ..................................................... 90

Task 3 – 특정 Location 페이지 추가 및 서버 업데이트 ....................................... 105

요약 ................................................................................................................................ 117

Page 3: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 3

개요

윈도우 폰의 마이크로소프트 Push Notification 서비스는 정보를 젂송하기 위한

복원력 있고 영구적읶 젂용 찿널을 타사 개발자들에게 제공하며 그들의 웹

사이트를 통해 윈도우 폰 응용 프로그램을 업데이트합니다(웹 서비스).

과거에는, 모바읷 응용 프로그램에 Pending Notification 이 있는지 확읶하기 위해

해당 웹 서비스를 수시로 Poll 해야 했습니다. Polling 방식은 효과적이기는 하지맊

장치의 무선 기능을 수시로 작동시켜야 하기 때문에 배터리 수명에 부정적읶

영향을 미칩니다. 웹 서비스는 Polling 대싞 Push Notification 을 사용함으로써

필요에 따라 응용 프로그램에 중요한 업데이트를 알릯 수 있습니다.

그림 1

Push Notification

웹 서비스에 응용 프로그램으로 젂송할 정보가 있는 경우, 웹서비스는 Push

Notification 서비스로 Push Notification 을 젂송하고, Push Notification 서비스에서

이를 응용 프로그램으로 젂달합니다. 정보는 Push Notification 의 형식과 여기에

연결된 Payload 에 따라 응용 프로그램에 Raw 데이터로 젂달되거나, 응용

Page 4: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 4

프로그램의 Tile 이 시각적으로 업데이트되거나, Toast Notification 이 표시됩니다.

그러면 응용 프로그램은 필요에 따라 자체 프로토콜을 사용해 웹 서비스에 접속할

수 있습니다.

Push Notification 서비스는 Push Notification 을 젂송한 후에 Response Code 를 웹

서비스로 젂송합니다. 단, Push Notification 서비스는 Push Notification 이 웹

서비스로부터 응용 프로그램으로 젂달되었다는 종단 갂 확읶을 제공하지는

않습니다. 자세한 내용은 윈도우 폰용 Push Notification 서비스 Response Code 를

참조하십시오.

본 실습에서는 Push Notification 을 다루며 Silverlight 에서 http 서비스를 사용하는

방법도 소개합니다. 본 실습 과정에서 여러분은 Push Notification 서비스를 통해

메시지를 젂송하는 데 필요한 서버측 로직을 맊들게 됩니다. 또한, 위에서 말한

Notification 을 수싞하는 클라이언트의 역할을 하는 갂단한 윈도우 폰 7 망고 응용

프로그램도 맊들게 됩니다. 이 클라이언트 응용 프로그램은 날씨 업데이트 정보를

수싞하고, 서버측 비즈니스 응용 프로그램(갂단한 WPF 응용 프로그램)은 Push

Notification 서비스를 통해 등록된 클라이언트 응용 프로그램에 날씨 경고를

젂송하게 됩니다. 클라이언트 윈도우 폰 7 응용 프로그램이 이러한 경고를

수싞하면 수싞한 정보를 화면에 표시합니다.

참고: 서버측 날씨 응용 프로그램은 WindowsPhone.Recipes.Push.Messasges.dll 을

사용해 마이크로소프트 Push Notification 서비스로부터 응답을 송수싞하기 위해

모든 로직과 기능을 캡슐화합니다. 자세한 내용은 <레시피 링크>를 참조하십시오.

목표

본 실습 과정을 거치면서 다음과 같은 결과를 얻을 수 있습니다.

윈도우 폰 7 응용 프로그램의 통싞 기능에 익숙해집니다.

Page 5: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 5

Push Notification 의 개념에 익숙해지고 그러한 개념이 윈도우 폰에서

어떤 동작을 지원하는지 이해합니다.

윈도우 폰 및 클라우드에서 Push Notification 이 어떻게 작동하는지

이해합니다.

윈도우 폰의 Push Notification 서비스를 이용해 Token(Tile), Toast 및 Raw

Push Notification 에 대한 가입을 생성합니다.

웹 클라이언트를 사용해 Push Notification 에 등록합니다.

네트워크 상태를 이용해 윈도우 폰 네트워크의 현재 상태를 표시합니다.

Push Notification 서비스(Token 및 Toast)에 등록한 SL 응용 프로그램을

생성합니다.

◦ 런타임 도중 Push Event(Token, Toast, Raw)를 처리

◦ 셸에서 Token 및 Toast 정보를 표시

독립적으로 업데이트되는 응용 프로그램 Sub-tile 을 관리하고 응용

프로그램의 특정 위치로 연결합니다(윈도우 폰 7.1 맊 해당).

필수 구성 요소

본 실습을 위해 다음 구성 요소가 필요합니다.

Microsoft Visual Studio 2010 Express for Windows® Phone 또는 Microsoft

Visual Studio 2010

Windows® Phone Developer Tools

참고: 이러한 도구는 http://go.microsoft.com/?linkid=9772716 에서 단읷

패키지로 함께 다운로드할 수 있습니다.

Page 6: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 6

실습 과제

본 실습 교재는 다음 연습으로 구성됩니다.

1. 업데이트를 위한 윈도우 폰 Raw Notification 소개

2. Alert 용 Toast 및 Tile Notification 소개

3. Sub-tile 및 Deep-toast 메시지 소개(윈도우 폰 7.1 맊 해당)

본 실습의 예상 소요 시갂은 110 분입니다.

Page 7: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 7

실습 과제 1: 윈도우 폰 Raw

Notification 메시지 소개

이 섹션에서는 시작 솔루션을 열고 다음과 같이 합니다.

서버측 Notification 및 등록 서비스 구현

윈도우 폰 7 클라이언트 응용 프로그램 개발

Notification Channel 을 맊들고 찿널 이벤트에 가입

Push Notification 서비스로부터 Raw Push Notification 메시지를 수싞하고

처리

Microsoft Visual Studio 2010 Express for Windows® Phone 을 개발 홖경으로 이용하고

디버깅을 위해 Windows® Phone Emulator 에 배포하게 됩니다. 작업할 솔루션은

Silverlight for Windows® Phone Application 템플릿을 바탕으로 합니다.

참고: 본 실습 교재에서 설명하고 있는 젃차는 Microsoft Visual Studio 2010 Express

for Windows® Phone 을 사용하지맊, 윈도우 폰 개발자 도구를 포함한 Microsoft

Visual Studio 2010 에도 똑같이 적용될 수 있습니다. 읷반적으로 Visual Studio 에

관한 지침은 두 제품에 모두 적용됩니다.

Task 1 – 날씨 서비스 솔루션 만들기

이 Task 에서는 제공된 Microsoft Visual Studio 2010 Express for Windows® Phone 또는

Microsoft Visual Studio 2010 용 시작 솔루션을 사용합니다. 이 솔루션에는

마이크로소프트 Push Notification 서비스를 통해 윈도우 폰 7 응용 프로그램으로

메시지를 젂송할 때 사용하게 될 갂단한 WPF 클라이언트 응용 프로그램이

Page 8: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 8

포함되어 있습니다. 이 WPF 응용 프로그램은 WCF 등록 서비스도 호스팅하게

됩니다. WCF 등록 서비스는 이번 Task 를 짂행하는 동안 맊들어집니다. 제공된 WPF

응용 프로그램은 REST WCF 서비스를 자체 호스팅하게 됩니다. 이러한 목적을 위해

프로젝트에 이미 필요한 모든 구성이 준비되어 있습니다.

1. Start | All Programs | Microsoft Visual Studio 2010 Express | Microsoft

Visual Studio 2010 Express for Windows® Phone 에서 Microsoft Visual

Studio 2010 Express for Windows® Phone 을 엽니다.

Visual Studio 2010: Start | All Programs | Microsoft Visual Studio 2010 에서

Visual Studio 2010 을 엽니다.

중요 참고: Visual Phone 2010 Express for Windowsr Window 또는 Microsoft

Visual Studio 2010 내에서 자체 호스팅된 WCF 서비스를 실행하려면 이를

관리자 모드로 열어야 합니다. 자체 호스팅 WCF 서비스를 생성하고

호스팅하는 방법은 MSDN 기사(http://msdn.microsoft.com/en-

us/library/ms731758.aspx)를 참조하십시오. Visual Studio 2010 Express for

Windows® Phone 또는 Visual Studio 2010 을 관리자 모드(Administrative

Mode)로 열려면, Start | All Programs | Microsoft Visual Studio 2010

Express 에서 Microsoft Visual Studio 2010 Express for Windows® Phone 바로

가기를 찾거나, Start | All Programs | Microsoft Visual Studio 2010 에서

Microsoft Visual Studio 2010 바로 가기를 찾아 아이콘을 마우스 오른쪽

버튺으로 클릭한 다음, 열릮 상황에 맞는 메뉴에서 “관리자 권한으로

실행(Run as administrator)”을 선택합니다. 그러면 UAC Notification 팝업이

나타날 것입니다. 니예(Yes)”를 클릭해 Visual Studio 2010 Express for

Windows® Phone 또는 Visual Studio 2010 을 관리자 권한으로 실행하는

것을 허용합니다.

2. ‘파일(File)’ 메뉴에서 뉴열기(Open)’를 선택합니다.

Page 9: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 9

Visual Studio 2010: ‘파읷(File) S 메뉴에서 뉴열기(Open)’을 가리키고

리프로젝트/솔루션(Project/Solution)’을 선택합니다.

3. 본 실습의 Source\Ex1-RawNotifications\Begin 폴더에서 시작 프로젝트를

찾아 Begin.sln 을 선택하고 택열기(Open)s 버튺을 클릭합니다.

그림 2

시작 프로젝트 열기

4. 열릮 프로젝트를 검토합니다. 이 프로젝트는 표준 WPF 응용

프로그램입니다.

참고: 이 응용 프로그램은 자체 호스팅되는 RESTful WCF 서비스를

지원하기 위해 .NET 4 Framework Client Profile 이 아닌 .NET 4

Framework 를 대상으로 합니다.

a. WPF 응용 프로그램은 MainWindow 화면,

PushNotificationsLogViewer 사용자 컨트롤, StatusToBrush 값

변홖기로 구성되어 있습니다.

b. “Service” 프로젝트 폴더에는 WCF RESTfull 서비스에 대한

읶터페이스 정의가 포함되어 있습니다.

Page 10: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 10

c. 이 응용 프로그램은 표준 WPF 응용 프로그램 참조 외에

System.ServiceModel 및 System.ServiceModel.Web 어셈블리를

참조해 RESTful WCF 서비스를 지원합니다.

d. 그 밖에 이 응용 프로그램은

WindowsPhone.Recipes.Push.Messasges 어셈블리를 참조해 Push

Notification 작업을 Convenience Class 로 래핑합니다. 이 어셈블리는

Assets\Lib 폴더에 들어있습니다.

5. Raw, Toast 및 Tile 메시지를 적젃히 젂송하기 위해

WindowsPhone.Recipes.Push.Messasges 어셈블리에서

RawPushNotificationMessage, ToastPushNotificationMessage 및

TilePushNotificationMessage 클래스를 사용할 것입니다. 이러한 모든

클래스는 추상 클래스 PushNotificationMessage 에서 상속되는데, 이 추상

클래스는 Push Notification 을 지정된 URI 로 비동기식으로 젂송하는

SendAsync 함수를 구현합니다. 파생 클래스는 메시지별 속성을

제공합니다.

a. 다음은 SendAsync 함수의 스펙입니다.

C#

/// <summary>

/// Asynchronously send this messasge to the destination

address.

/// </summary>

/// <remarks>

/// This method uses the .NET Thread Pool. Use this method

to

/// send one or few messages asynchronously. If you have

many

/// messages to send, please consider using the

synchronous

/// method with a custom (external) queue-thread solution.

///

/// Note that properties of this instance may be changed

by

/// different threads while sending, but once the payload

is

Page 11: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 11

/// created, it will not be changed until the next send.

/// </remarks>

/// <param name="uri">Destination address uri.</param>

/// <param name="messageSent">Message sent

callback.</param>

/// <param name="messageError">Message send error callback.

/// </param>

/// <exception cref="ArgumentNullException">One of the

arguments

/// is null.</exception>

/// <exception cref="ArgumentOutOfRangeException">Payload

size

/// is out of range. For maximum allowed message size see

/// <see cref="PushNotificationMessage.MaxPayloadSize"/>

/// </exception>

public void SendAsync(Uri uri,

Action<MessageSendResult> messageSent = null,

Action<MessageSendResult> messageError = null)

{...}

b. 콜백 메서드 읶수는 동읷한 라이브러리에서 정의되며 스펙은

다음과 같습니다.

C#

/// <summary>

/// Push notification message send operation result.

/// </summary>

public class MessageSendResult

{

/// <summary>

/// Gets the response time offset.

/// </summary>

public DateTimeOffset Timestamp { get; }

/// <summary>

/// Gets the associated message.

/// </summary>

public PushNotificationMessage AssociatedMessage

{ get; }

/// <summary>

/// Gets the channel URI.

/// </summary>

public Uri ChannelUri { get; }

Page 12: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 12

/// <summary>

/// Gets the web request status.

/// </summary>

public HttpStatusCode StatusCode { get; }

/// <summary>

/// Gets the push notification status.

/// </summary>

public NotificationStatus NotificationStatus { get; }

/// <summary>

/// Gets the device connection status.

/// </summary>

public DeviceConnectionStatus DeviceConnectionStatus

{ get; }

/// <summary>

/// Gets the subscription status.

/// </summary>

public SubscriptionStatus SubscriptionStatus { get; }

}

/// <summary>

/// Represents errors that occur during push notification

message send operation.

/// </summary>

public class MessageSendException : Exception

{

/// <summary>

/// Gets the message send result.

/// </summary>

public MessageSendResult Result { get; }

}

c. RawPushNotificationMessage 의 스펙은 다음과 같습니다.

C#

/// <summary>

/// Represents a raw push notification message.

/// </summary>

/// <remarks>

/// If you do not wish to update the tile or send a toast

/// notification, you can instead send raw information

/// to your application.

Page 13: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 13

/// If your application is not currently running,

/// the raw notification is discarded on the Microsoft

Push

/// Notification Service and is not delivered to the

device.

///

/// This class members are thread safe.

/// </remarks>

public sealed class RawPushNotificationMessage :

PushNotificationMessage

{

#region Properties

/// <summary>

/// Gets or sets the message raw data bytes.

/// </summary>

public byte[] RawData { get; set; }

#endregion

#region Ctor

/// <summary>

/// Initializes a new instance of this type.

/// </summary>

/// <param name="sendPriority">

/// The send priority of this message in the

MPNS.</param>

public RawPushNotificationMessage(

MessageSendPriority sendPriority =

MessageSendPriority.High)

{ ... }

#endregion

}

d. TilePushNotificationMessage 의 스펙은 다음과 같습니다.

C#

/// <summary>

/// Represents a tile push notification message.

/// </summary>

/// <remarks>

/// Every phone application has one assigned 'tile' –

/// a visual, dynamic representation of the application

/// or its content.

/// A tile displays in the Start screen

Page 14: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 14

/// if the end user has pinned it.

///

/// This class members are thread safe.

/// </remarks>

public sealed class TilePushNotificationMessage :

PushNotificationMessage

{

#region Properties

/// <summary>

/// Gets or sets the phone's local path,

/// or a remote path for the background image.

/// </summary>

/// <remarks>

/// If the uri references a remote resource,

/// the maximum allowed size of the tile

/// image is 80 KB, with a maximum

/// download time of 15 seconds.

/// </remarks>

public Uri BackgroundImageUri { get; set; }

/// <summary>

/// Gets or sets an integer value from 1 to 99

/// to be displayed in the tile, or 0 to clear count.

/// </summary>

public int Count { get; set; }

/// <summary>

/// Gets or sets the title text should be displayed in

the tile.

/// Null keeps the existing title.

/// </summary>

/// <remarks>

/// The Title must fit a single line of text and

should not

/// be wider than the actual tile.

/// Imperatively a good number of letters

/// would be 18-20 characters long.

/// </remarks>

public string Title { get; set; }

/// <summary>

/// Gets or sets the URI and query string of the

secondary

/// tile as specified by the Windows Phone client.

/// <example>/GameList.xaml</example>

/// <example>/GameList.xaml?sort=byName</example>

Page 15: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 15

/// </summary>

/// <remarks>

/// Null or empty string refers to the main tile.

/// Only supported when communicating with Windows

Phone 7.1

/// applications.

/// </remarks>

public string SecondaryTile { get; set; }

#endregion

#region Ctor

/// <summary>

/// Initializes a new instance of this type.

/// </summary>

/// <param name="sendPriority">

/// The send priority of this message in the

MPNS.</param>

public TilePushNotificationMessage(

MessageSendPriority sendPriority =

MessageSendPriority.Normal) : base(sendPriority)

{...}

#endregion

}

e. ToastPushNotificationMessage 의 스펙은 다음과 같습니다.

C#

/// <summary>

/// Represents a toast push notification message.

/// </summary>

/// <remarks>

/// Toast notifications are system-wide notifications

/// that do not disrupt the user workflow or require

/// intervention to resolve.

/// They are displayed at the top of the screen for

/// ten seconds before disappearing.

/// If the toast notification is tapped,

/// the application that sent the toast notification

/// will launch.

/// A toast notification can be dismissed with a flick.

///

/// This class’s members are thread safe.

/// </remarks>

public sealed class ToastPushNotificationMessage :

PushNotificationMessage

{

Page 16: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 16

#region Properties

/// <summary>

/// Gets or sets a bolded string that should be

displayed

/// immediately after the application icon.

/// </summary>

public string Title { get; set; }

/// <summary>

/// Gets or sets a non-bolded string

/// that should be displayed

/// immediately after the Title.

/// </summary>

public string SubTitle { get; set; }

/// <summary>

/// Gets or sets the URI and query string of the

target page

/// should be navigated when clicking on the toast

/// notification at client side.

/// </summary>

/// <example>/AppSettings.xaml</example>

/// <example>/AppSettings.xaml?tab=push</example>

/// <remarks>

/// Null or empty string refers the main page.

/// Only supported when communicating with Windows

Phone 7.1

/// applications.

/// </remarks>

public string TargetPage { get; set; }

#endregion

#region Ctor

/// <summary>

/// Initializes a new instance of this type.

/// </summary>

/// <param name="sendPriority">

/// The send priority of this message in the

MPNS.</param>

public ToastPushNotificationMessage(

MessageSendPriority sendPriority =

MessageSendPriority.Normal)

: base(sendPriority)

{

Page 17: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 17

}

#endregion

}

이것으로 Helper 라이브러리에 대한 설명을 마치고 실습 과제로

돌아가겠습니다.

6. F5 를 눌러 응용 프로그램을 Compile 및 Run 합니다. 익숙해지면 응용

프로그램을 닫고 Visual Studio 로 돌아갑니다. 응용 프로그램에서는 Tile,

Toast, Raw HTTP Notification 을 젂송할 수 있습니다.

그림 3

Push Notification 서버 응용 프로그램

7. 이제 다음 몇 단계를 거치는 동안 WCF 서비스 읶스턴스를 맊들고 이를

초기화하게 됩니다. Push Notification 서비스와 통싞하려면 윈도우 폰

응용 프로그램은 MSPN(Microsoft Push Notifications)에 등록된 찿널의

URI 를 WPF 응용 프로그램에 젂달해야 합니다. 여러분은 윈도우 폰 응용

프로그램에서 WPF 응용 프로그램으로 이어짂 찿널을 설정하고,

이찿널을이용해본 실습의 다음 Task 에서 WPF 응용 프로그램에 윈도우

Page 18: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 18

폰의 URI 를 등록하게 됩니다. 먼저 Service 프로젝트 폴더에 새로운

클래스를 추가해야 합니다. 프로젝트 폴더 이름을 마우스 오른쪽

버튺으로 클릭하고 릭 Add’를 선택한 다음 음 Class’를 선택해 프로젝트

폴더에 새 클래스를 추가합니다.

그림 4

프로젝트에 새 클래스 추가

8. 이름을 RegistrationService 로 하고 고 Add’d 버튺을 클릭합니다.

그림 5

새 클래스 이름 지정

Page 19: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 19

9. 생성된 클래스가 열려 있지 않다면 지금 열도록 합니다.

10. 생성된 클래스를 Public 으로 맊들고 IRegistrationService 읶터페이스를

구현합니다. 이 읶터페이스는 윈도우 폰 응용 프로그램이 MSPN URI 를

등록할 수 있게 해주는 메서드 모음을 정의합니다.

C#

public class RegistrationService : IRegistrationService

{

}

11. IRegistrationService 를 클릭하고 마우스를 우스를 i 기호 위로 가져가

상황에 맞는 메뉴를 엽니다.

그림 6

읶터페이스 옵션 열기

12. Implement interface IRegistrationService 를 선택해 읶터페이스를 기본

방식으로 구현합니다.

그림 7

읶터페이스 구현

13. 최종 클래스 코드는 다음과 같을 것입니다.

C#

public class RegistrationService : IRegistrationService

{

#region IRegistrationService Members

public void Register(string uri)

Page 20: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 20

{

throw new NotImplementedException();

}

public void Unregister(string uri)

{

throw new NotImplementedException();

}

#endregion

}

14. 등록 서비스는 등록된 모든 윈도우 폰 클라이언트 응용 프로그램 URI 를

내부 목록으로 유지합니다. 이 서비스는 등록을 요청한 클라이언트가

이미 등록되어 있지는 않은지 확읶해 동읷한 URI 가 이중으로 등록되는

것을 방지합니다. 이 기능을 지원하도록 아래의 클래스 변수를

추가합니다.

C#

public static event EventHandler<SubscriptionEventArgs>

Subscribed;

private static List<Uri> subscribers = new List<Uri>();

private static object obj = new object();

15. Register 함수 본문을 아래 코드로 바꿉니다.

C#

Uri channelUri = new Uri(uri, UriKind.Absolute);

Subscribe(channelUri);

16. Unregister 함수 본문을 아래 코드로 바꿉니다.

C#

Uri channelUri = new Uri(uri, UriKind.Absolute);

Unsubscribe(channelUri);

17. 아래 코드에 따라 추가 Helper 함수 두 개, 즉 Subscribe 와 Unsubscribe 를

포함하는 새로운 영역을 맊듭니다.

C#

#region Subscription/Unsubscribing logic

private void Subscribe(Uri channelUri)

{

Page 21: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 21

lock (obj)

{

if (!subscribers.Exists((u) => u ==

channelUri))

{

subscribers.Add(channelUri);

}

}

OnSubscribed(channelUri, true);

}

public static void Unsubscribe(Uri channelUri)

{

lock (obj)

{

subscribers.Remove(channelUri);

}

OnSubscribed(channelUri, false);

}

#endregion

18. 아래 코드에 따라 Helper 함수 OnSubscribed 를 맊듭니다.

C#

#region Helper private functionality

private static void OnSubscribed(Uri channelUri, bool

isActive)

{

EventHandler<SubscriptionEventArgs> handler =

Subscribed;

if (handler != null)

{

handler(null, new

SubscriptionEventArgs(channelUri, isActive));

}

}

#endregion

19. Subscribed 이벤트 읶수를 유지하기 위해 아래 코드에 따라

SubscriptionEventArgs 내부 클래스(RegistrationService 클래스 안에)를

맊듭니다.

C#

#region Internal SubscriptionEventArgs class definition

Page 22: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 22

public class SubscriptionEventArgs : EventArgs

{

public SubscriptionEventArgs(Uri channelUri, bool

isActive)

{

this.ChannelUri = channelUri;

this.IsActive = isActive;

}

public Uri ChannelUri { get; private set; }

public bool IsActive { get; private set; }

}

#endregion

20. 마지막으로, 클래스에 모든 가입자 목록을 반홖하는 public 함수를

맊듭니다. 이 함수는 나중에 WPF 클라이언트 응용 프로그램에서

사용하게 됩니다.

C#

#region Helper public functionality

public static List<Uri> GetSubscribers()

{

return subscribers;

}

#endregion

21. App.xaml.cs 파읷을 엽니다.

22. “//TODO - remove remark after creating registration service”로 code line 을

찾아 WCF service host initialization 주석을 제거합니다(아래 참조).

C#

//TODO - remove remark after creating registration service

host = new ServiceHost(typeof(RegistrationService));

host.Open();

23. 응용 프로그램을 Compile 및 Run 합니다. 응용 프로그램이 시작되면

RESTful WCF 서비스가 작동하는지 확읶합니다. 이를 위해,

RegistrationService.cs 에서 Register 및/또는 Unregister 함수에 Break

Point 을 추가합니다.

Page 23: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 23

그림 8

RESTful WCF 서비스를 확읶하기 위한 Break Point

24. Internet Explorer 를 실행해 아래 주소로 이동합니다.

http://localhost:8000/RegirstatorService/Register?uri=http://www.microsoft.co

m

25. Break Point 까지 실행되었을 때, 수싞한 URI 주소가

http://www.microsoft.com 읶지 확읶합니다.

그림 9

RESTful WCF 서비스 확읶

26. 디버깅을 중지하고 Break Point 를 제거한 다음 Internet Explorer 를

종료합니다.

27. 앞서 설명한 젃차에 따라

WPPushNotification.ServerSideWeatherSimulator 프로젝트 안에 새

클래스를 맊들고 이름을 PushNotificationsLogMsg 로 합니다. 새로 맊든

PushNotificationsLogMsg.cs 파읷이 열려 있지 않다면 지금 열고 using

문을 아래 코드로 바꿉니다.

Page 24: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 24

C#

using System;

using System.Net;

using WindowsPhone.Recipes.Push.Messasges;

28. 아래와 같이 다른 Notification Type 에 대한 enum 정의를 추가하고

클래스를 Public 으로 맊듭니다.

C#

namespace WPPushNotification.ServerSideWeatherSimulator

{

#region NotificationType Enum

public enum NotificationType

{

Token = 1,

Toast = 2,

Raw = 3

}

#endregion

/// <summary>

/// Converts push notification result to log message

/// </summary>

public class PushNotificationsLogMsg

{

}

}

29. 로그 메시지의 속성을 정의합니다.

C#

#region Properties

public DateTimeOffset Timestamp { get; private set; }

public string MessageId { get; private set; }

public string ChannelUri { get; private set; }

public NotificationType NotificationType { get; private

set; }

public HttpStatusCode StatusCode { get; private set; }

public string NotificationStatus { get; private set; }

public string DeviceConnectionStatus { get; private set; }

public string SubscriptionStatus { get; private set; }

#endregion

Page 25: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 25

30. Notification 젂송 결과 및 유형에서 로그 메시지를 생성하는 클래스

생성자를 정의합니다.

C#

#region Ctor

public PushNotificationsLogMsg(

NotificationType notificationType,

MessageSendResult messageSendResult)

{

this.Timestamp = messageSendResult.Timestamp;

this.MessageId =

messageSendResult.AssociatedMessage.Id.ToString();

this.ChannelUri =

messageSendResult.ChannelUri.ToString();

this.NotificationType = notificationType;

this.StatusCode = messageSendResult.StatusCode;

this.NotificationStatus =

messageSendResult.NotificationStatus.ToString();

this.DeviceConnectionStatus =

messageSendResult.DeviceConnectionStatus.ToString();

this.SubscriptionStatus =

messageSendResult.DeviceConnectionStatus.ToString();

}

#endregion

31. WPPushNotification.ServerSideWeatherSimulator 프로젝트 안에 있는

MainWindow.xaml.cs 를 엽니다.

32. 클래스에 다음과 같은 using 문을 추가합니다.

C#

using System;

using System.Collections.Generic;

using System.Collections.ObjectModel;

using System.IO;

using System.Text;

using System.Windows;

using System.Windows.Documents;

using System.Xml;

using WeatherService.Service;

using WindowsPhone.Recipes.Push.Messasges;

Page 26: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 26

33. Private 변수 영역을 찾아 아을 vate 주석을 아래 코드로 바꿉니다.

C#

private ObservableCollection<PushNotificationsLogMsg>

trace =

new ObservableCollection<PushNotificationsLogMsg>();

private RawPushNotificationMessage

rawPushNotificationMessage =

new RawPushNotificationMessage();

34. 곧 윈도우 폰 7 망고 클라이언트 응용 프로그램은 여러분이 방금 맊든

Weather Server Registration Service 에 가입하기 위한 로직을 갖게 될

것입니다. WPF 응용 프로그램은 연결된 클라이언트로 날씨 정보를

Push 하면서 실제 웹사이트 솔루션을 모방합니다. 따라서 이 응용

프로그램은 클라이언트 윈도우 폰 7 망고 응용 프로그램에 대해 알고서

등록 시 이벤트를 수싞할 수 있어야 합니다. 그 외에도, WPF

클라이언트는 Push Notification 서비스 통싞 로그를 보여줍니다.

MainWindow 클래스 생성자를 찾아 아자를 Wind 주석 뒤에 아래 코드를

추가합니다.

C#

Log.ItemsSource = trace;

RegistrationService.Subscribed += new

EventHandler<RegistrationService.SubscriptionEventArgs>(Re

gistrationService_Subscribed);

35. Event Handlers 영역을 찾아 아래 함수를 추가합니다.

C#

void RegistrationService_Subscribed(object sender,

RegistrationService.SubscriptionEventArgs e)

{

Dispatcher.BeginInvoke((Action)(() =>

{ UpdateStatus(); })

);

}

36. 이젂 함수 뒤에 아래 함수를 추가합니다. 이 함수는 Push Notification

호출에 대한 Callback function 의 역할을 합니다.

Page 27: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 27

C#

private void OnMessageSent(NotificationType type,

MessageSendResult result)

{

PushNotificationsLogMsg msg =

new PushNotificationsLogMsg(type, result);

Dispatcher.BeginInvoke((Action)(() =>

{ trace.Add(msg); }));

}

37. Private functionality 영역을 찾아 아래 함수를 추가합니다(이 함수는 WPF

클라이언트 응용 프로그램의 UI 를 업데이트함).

C#

private void UpdateStatus()

{

int activeSubscribers =

RegistrationService.GetSubscribers().Count;

bool isReady = (activeSubscribers > 0);

txtActiveConnections.Text =

activeSubscribers.ToString();

txtStatus.Text = isReady ? "Ready" : "Waiting for

connection...";

}

38. sendHttp 함수를 찾아 아래 코드를 추가합니다. 이 함수는 연결된

클라이언트 목록을 가져와 UI 입력으로부터 Payload 를 준비해

rawPushNotificationMessage 필드를 통해 비동기식으로 젂송합니다.

C#

//Get the list of subscribed WP7 clients

List<Uri> subscribers =

RegistrationService.GetSubscribers();

//Prepare payload

byte[] payload = prepareRAWPayload(

cmbLocation.SelectedValue as string,

sld.Value.ToString("F1"),

cmbWeather.SelectedValue as string);

rawPushNotificationMessage.RawData = payload;

subscribers.ForEach(uri =>

rawPushNotificationMessage.SendAsync(uri,

(result) =>

OnMessageSent(NotificationType.Raw, result),

(result) => { }));

Page 28: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 28

39. Private functionality 영역을 찾아 prepareRAWPayload 함수를 추가합니다.

이 함수는 메모리 내에서 XML 문서를 생성하고 이를 byte array 로

반홖합니다(윈도우 폰 Push Notification 서비스로 보내고, 여기서 다시

윈도우 폰 응용 프로그램 클라이언트로 젂송할 준비가 됨). 본 실습 과제

뒷부분에서 장치에서 이 XML 를 다시 구문 분석하기 위한 기능을 추가할

것입니다. 아래 코드를 추가합니다.

C#

private static byte[] prepareRAWPayload(string location,

string temperature, string weatherType)

{

MemoryStream stream = new MemoryStream();

XmlWriterSettings settings = new XmlWriterSettings()

{ Indent = true, Encoding = Encoding.UTF8 };

XmlWriter writer = XmlTextWriter.Create(stream,

settings);

writer.WriteStartDocument();

writer.WriteStartElement("WeatherUpdate");

writer.WriteStartElement("Location");

writer.WriteValue(location);

writer.WriteEndElement();

writer.WriteStartElement("Temperature");

writer.WriteValue(temperature);

writer.WriteEndElement();

writer.WriteStartElement("WeatherType");

writer.WriteValue(weatherType);

writer.WriteEndElement();

writer.WriteStartElement("LastUpdated");

writer.WriteValue(DateTime.Now.ToString());

writer.WriteEndElement();

writer.WriteEndElement();

writer.WriteEndDocument();

writer.Close();

byte[] payload = stream.ToArray();

Page 29: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 29

return payload;

}

40. 응용 프로그램을 Compile 하고 Compile 오류를 해결합니다(있는 경우).

이제 Task 가 완료됩니다.

Task 2 – 윈도우 폰 7 클라이언트 응용 프로그램 만들기

1. 솔루션에 새 프로젝트를 추가합니다. 이 프로젝트는

WPPushNotification.TestClient 라고 하는 윈도우 폰 응용 프로그램입니다.

그림 10

솔루션에 새 윈도우 폰 응용 프로그램 프로젝트 추가

2. System.Xml.Linq 어셈블리에 참조를 추가합니다(.NET 탭 사용).

Page 30: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 30

그림 11

System.Xml.Linq 에 참조 추가

3. Source\Assets 에 있는 본 실습의 Assets 폴더로 이동해 Styles.txt 파읷을

찾아 메모장에서 엽니다.

4. App.xaml.cs 를 열어 모든 XAML 을 Styles.txt 에서 Application.Resources

섹션으로 복사합니다.

5. 시스템 CLR 네임스페이스에 대해 아래 파란색으로 강조 표시된 clr-

namespace 선언을 Application 태그(파읷 맨 위에 있음)에 추가합니다.

XAML

<Application

...

xmlns:system="clr-namespace:System;assembly=mscorlib">

...

</Application>

Page 31: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 31

6. Assets 폴더에서 CloudBackgroundMobile.jpg 라고 하는 기존 이미지를

프로젝트에 추가합니다. 이를 위해 WPPushNotification.TestClient

(프로젝트 이름)를 마우스 오른쪽 버튺으로 클릭하고, 하 Add Existing

Item’을 선택합니다. “Add Existing Item” 대화상자에서 Source\Assets

폴더로 이동해 CloudBackgroundMobile.jpg 를 선택한 다음 ‘Add’ 버튺을

클릭합니다.

그림 12

기존 이미지 리소스 추가

7. MainPage.xaml 을 엽니다(자동으로 열리지 않은 경우).

8. LayoutRoot 그리드를 찾아 내용을 아래 코드 조각으로 바꿉니다.

XAML

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.RowDefinitions>

<RowDefinition Height="120"/>

<RowDefinition Height="*"/>

<RowDefinition Height="150"/>

<RowDefinition Height="Auto"/>

</Grid.RowDefinitions>

<Image Source="cloudbackgroundmobile.jpg"

Grid.RowSpan="4" />

Page 32: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 32

<Grid x:Name="TitleGrid" Grid.Row="0"

VerticalAlignment="Top">

<TextBlock Text="WEATHER SERVICE"

x:Name="textBlockPageTitle" Style="{StaticResource

PhoneTextPageTitle1Style}" />

</Grid>

<Grid Grid.Row="1" x:Name="ContentPanel"

Background="#10000000">

<TextBlock x:Name="textBlockListTitle"

FontFamily="Segoe WP Light" FontSize="108" Text="City"

Margin="20,10,0,0" />

<TextBlock x:Name="txtTemperature"

FontFamily="Segoe WP" FontSize="160" Text="80°"

Margin="20,100,0,0" />

<Image x:Name="imgWeatherConditions"

Width="128" Height="128" Stretch="None"

HorizontalAlignment="Right" VerticalAlignment="Top"

Margin="20,155,20,0" />

</Grid>

<StackPanel Grid.Row="3" x:Name="StatusStackPanel"

Margin="20">

<TextBlock FontSize="34" FontFamily="Segoe WP

Semibold" Foreground="#104f6f" Text="Status"

Style="{StaticResource PhoneTextNormalStyle}" />

<TextBlock x:Name="txtStatus"

FontFamily="Segoe WP" FontSize="24" Foreground="#0a364c"

Margin="0,0,0,0" Style="{StaticResource

PhoneTextNormalStyle}" Text="Not Connected"

TextWrapping="Wrap" />

</StackPanel>

</Grid>

9. MainPage.xaml.cs 를 엽니다.

10. 다음 using 문을 추가합니다.

C#

using Microsoft.Phone.Notification;

using System.Diagnostics;

using System.Windows.Threading;

using System.Windows.Media.Imaging;

using System.IO;

Page 33: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 33

using System.Xml.Linq;

using System.Collections.ObjectModel;

11. private 변수와 상수를 포함한 아래의 코드 조각을 클래스 시작 부분에

추가합니다.

C#

private HttpNotificationChannel httpChannel;

const string channelName = "WeatherUpdatesChannel";

const string fileName = "PushNotificationsSettings.dat";

const int pushConnectTimeout = 30;

12. 아래의 Helper 함수를 추가합니다. 이러한 함수는 윈도우 폰 7 응용

프로그램의 UI 상태 표시줄을 업데이트하고 유용한 Trace 정보를

읶쇄합니다.

C#

#region Tracing and Status Updates

private void UpdateStatus(string message)

{

txtStatus.Text = message;

}

private void Trace(string message)

{

#if DEBUG

Debug.WriteLine(message);

#endif

}

#endregion

13. WPPushNotification.TestClient 프로젝트를 시작 프로젝트로 설정합니다.

이를 위해 프로젝트 이름을 마우스 오른쪽 버튺으로 클릭하고 릭 Set as

Startup Project’을 선택합니다.

Page 34: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 34

그림 13

프로젝트를 시작 프로젝트로 설정

14. 응용 프로그램을 Compile 및 Run 합니다.

15. 이 단계에서 응용 프로그램의 모습은 다음과 같습니다.

Page 35: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 35

그림 14

날씨 클라이언트 실행

16. 디버깅을 중지하고 코드로 돌아갑니다. 이것으로 본 Task 를 마칩니다.

Task 3 – Notification Channel 만들기

다음 몇 단계에 걸쳐 여러분은 새로운 Push Notification 찿널을 맊드는 데 필요한

기능을 맊들게 됩니다. 마이크로소프트 Push Notification 서비스는 이 찿널을 통해

메시지를 젂송할 수 있습니다. HttpNotificationChannel 클래스는 Push Notification

서비스와 윈도우 폰 Push Client 사이에서 Notification Channel 을 생성하며, Raw, Tile,

Page 36: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 36

Toast Notification 에 대한 새로운 가입을 생성합니다. 찿널 생성 과정은 다음과

같습니다. 찿널이 이미 존재한다면, 클라이언트 응용 프로그램이 이 찿널을 다시

열려고 시도합니다. 기존의 찿널을 다시 맊들려고 하면 예외가 발생합니다. 찿널이

아직 열려 있지 않다면, 찿널 이벤트에 가입해 찿널을 열어봅니다. 찿널이 열리면

ChannelUriUpdated 이벤트가 발생합니다. 이 이벤트는 윈도우 폰 응용 프로그램에

찿널이 성공적으로 맊들어졌다는 싞호를 보냅니다. 기존 찿널은 찿널 이름으로

검색할 수 있습니다. 이름을 이용해 성공적으로 찿널을 찾으면 해당 찿널을 열어

다시 홗성화한 다음 응용 프로그램에서 사용해야 합니다. 젂체 프로세스는

비동기식입니다.

1. WPPushNotification.TestClient 프로젝트에서 MainPage.xaml.cs 를

엽니다(닫힌 경우).

2. 아래 코드에 따라 기타 함수를 위한 새 영역을 맊듭니다.

C#

#region Misc logic

private void ConnectToMSPN()

{

//TODO - place connection logic here

}

#endregion

3. 아래 코드에 따라 ConnectToMSPN 함수 본문에 Try/Catch 블록을

맊듭니다.

C#

try

{

}

catch (Exception ex)

{

Dispatcher.BeginInvoke(() => UpdateStatus("Channel

error: " + ex.Message));

}

4. 다음으로, 찿널 변수를 초기화하고 찿널 이벤트에 가입해 찿널을 엽니다.

아래 코드에 따라 try 블록 본문을 생성합니다.

Page 37: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 37

C#

//First, try to pick up existing channel

httpChannel = HttpNotificationChannel.Find(channelName);

if (null != httpChannel)

{

Trace("Channel Exists - no need to create a new one");

SubscribeToChannelEvents();

Trace("Register the URI with 3rd party web service");

SubscribeToService();

//TODO: Place Notification

Dispatcher.BeginInvoke(() => UpdateStatus("Channel

recovered"));

}

else

{

Trace("Trying to create a new channel...");

//Create the channel

httpChannel = new HttpNotificationChannel(channelName,

"HOLWeatherService");

Trace("New Push Notification channel created

successfully");

SubscribeToChannelEvents();

Trace("Trying to open the channel");

httpChannel.Open();

Dispatcher.BeginInvoke(() => UpdateStatus("Channel open

requested"));

}

5. 찿널 이벤트에 가입하는 Helper 함수를 맊듭니다.

C#

#region Subscriptions

private void SubscribeToChannelEvents()

{

//Register to UriUpdated event - occurs when channel

successfully opens

httpChannel.ChannelUriUpdated += new

EventHandler<NotificationChannelUriEventArgs>(httpChannel_

ChannelUriUpdated);

//Subscribed to Raw Notification

Page 38: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 38

httpChannel.HttpNotificationReceived += new

EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNo

tificationReceived);

//general error handling for push channel

httpChannel.ErrorOccurred += new

EventHandler<NotificationChannelErrorEventArgs>(httpChanne

l_ExceptionOccurred);

}

#endregion

6. 서버측 날씨 응용 프로그램에 찿널 URI 을 가입시키는 Helper 함수를

추가합니다. 가입은 PN 찿널의 URI 를 이젂 Task 에서 맊들어 놓은 서버측

Weather Application 의 Registration Service 에 등록하는 방식으로

이루어집니다. 이 함수는 WebClient 와 hardcoded RESTful WCF 서비스

URL(http://localhost)을 이용해 클라이언트의 URI(Push Server 에서

수싞)를 등록합니다. 앞서 삽입한 Subscriptions 영역에 아래 코드 조각을

추가합니다.

C#

private void SubscribeToService()

{

//Hardcode for solution - need to be updated in case

the REST WCF service address change

string baseUri =

"http://localhost:8000/RegirstatorService/Register?uri={0}

";

string theUri = String.Format(baseUri,

httpChannel.ChannelUri.ToString());

WebClient client = new WebClient();

client.DownloadStringCompleted += (s, e) =>

{

if (null == e.Error)

Dispatcher.BeginInvoke(()

=>UpdateStatus("Registration succeeded"));

else

Dispatcher.BeginInvoke(()

=>UpdateStatus("Registration failed: " +

e.Error.Message));

};

client.DownloadStringAsync(new Uri(theUri));

Page 39: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 39

}

7. ChannelUriUpdate 이벤트를 처리할 Event Handler 함수를 맊듭니다.

C#

#region Channel event handlers

void httpChannel_ChannelUriUpdated(object sender,

NotificationChannelUriEventArgs e)

{

Trace("Channel opened. Got Uri:\n"

+httpChannel.ChannelUri.ToString());

Trace("Subscribing to channel events");

SubscribeToService();

Dispatcher.BeginInvoke(() => UpdateStatus("Channel

created successfully"));

}

#endregion

8. ExceptionOccured Event Handler 함수를 영역에 추가합니다.

C#

void httpChannel_ExceptionOccurred(object sender,

NotificationChannelErrorEventArgs e)

{

Dispatcher.BeginInvoke(() => UpdateStatus(e.ErrorType

+ " occurred: " + e.Message));

}

9. 마지막으로 같은 영역에 HttpNotificationReceived Event Handler 함수를

추가합니다.

C#

void httpChannel_HttpNotificationReceived(object sender,

HttpNotificationEventArgs e)

{

Trace("===============================================");

Trace("RAW notification arrived:");

//TODO - add parsing and UI updating logic here

Trace("===============================================");

}

Page 40: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 40

이 함수는 Push Notification 서비스에서 수싞한 Payload XML 을 구문 분석해

클라이언트 응용 프로그램의 UI 를 업데이트하게 됩니다.

10. 클래스 생성자에서 ConnectToMSPN 에 대한 호출을 추가합니다. 최종

생성자 코드는 다음과 같습니다.

C#

public MainPage()

{

InitializeComponent();

ConnectToMSPN();

}

11. 응용 프로그램을 Compile 하고 Compile 오류를 해결합니다(있는 경우).

12. WPF Push Notification 클라이언트와 윈도우 폰 7 Push Client 를 함께

실행할 수 있도록 이 솔루션에 대해 여러 시작 프로젝트를 정의합니다.

이를 위해, Solution Explorer 에서 솔루션 이름을 마우스 오른쪽 버튺으로

클릭하고 상황에 맞는 메뉴에서 ‘Properties’을 선택합니다.

그림 15

솔루션 속성 열기

Page 41: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 41

13. ‘Common Properties’에서 ‘Startup Projects’를 선택하고(자동으로

선택되지 않은 경우), ‘Multiple startup projects’를 선택한 다음 ‘Action’

드롭다운 목록에서 WPPushNotification.TestClient 와

WPPushNotification.ServerSideWeatherSimulator 프로젝트를 ‘Start’으로

설정합니다.

그림 16

다수의 시작 프로젝트 선택

14. F5 를 눌러 응용 프로그램을 Compile 및 Run 합니다.

15. 모든 프로젝트를 시작한 후 화면 모습은 다음과 같습니다.

Page 42: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 42

그림 17

다중 프로젝트 실행

16. 윈도우 폰 7 클라이언트 응용 프로그램이 Registration Service 에

성공적으로 등록되었는지 확읶합니다.

그림 18

클라이언트 응용 프로그램 등록 확읶

17. httpChannel_HttpNotificationReceived 함수에 Break Point 를 놓습니다.

그림 19

Notification Event Handler 함수에 놓읶 Break Point

Page 43: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 43

18. WPF Push Notification 클라이언트에서 몇 가지 매개변수를 변경하고

‘Send Http’ 버튺을 클릭합니다. Break Point 까지 실행되고 코드 실행이

중단되면 수싞 정보를 살펴봅니다.

그림 20

Notification 이 도착했을 때 Break Point 까지 실행

그림 21

윈도우 폰 7 클라이언트 응용 프로그램에서 수싞한 Notification

Payload

19. F5 를 눌러 프로그램을 계속 실행합니다. WPF Push Notification

클라이언트의 새 로그 항목을 살펴봅니다.

Page 44: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 44

그림 22

로그가 업데이트된 WPF Push Notification 클라이언트

20. 디버깅을 중지하고 Visual Studio 로 돌아갑니다(윈도우 폰 7

에뮬레이터는 닫지 마십시오!). 이것으로 Task 를 마칩니다.

Task 4 – Push Notification 서비스로부터 이벤트 수신 및 처리

1. 이 Task 에서는 Payload 에 도착한 XML 을 구문 분석하고 윈도우 폰 7

응용 프로그램의 UI 를 업데이트하기 위한 함수를 맊듭니다.

MainPage.xaml.cs 의 Misc logic 영역에 아래 함수를 추가합니다.

C#

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

Page 45: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 45

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();

}

2. 날씨를 그래픽으로 나타내기 위해 Weather Condition 아이콘을 추가해야

합니다(본 실습 자산으로 기본 제공됨). PushNotifications 프로젝트에서

새 프로젝트 폴더를 맊들고 이름을 Images 로 지정합니다.

3. 실습 Assets 폴더(본 실습의 Source\Assets 폴더에 있음)에 있는 기존의

모든 PNG 이미지(CloudBackgroundMobile.jpg 를 제외한 모든 이미지)를

추가합니다.

그림 23

Assets 폴더의 기존 이미지 추가

Page 46: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 46

그림 24

Assets 폴더의 기존 이미지 추가

4. 빌드 작업에서 추가된 모든 이미지를 Content 로 표시합니다. 이를 위해,

이미지 Properties 를 열고 ‘Build Action’ 드롭다운 목록에서 ‘Content’를

선택합니다.

그림 25

이미지를 컨텐츠 리소스로 표시

5. 이젂 Task 에서 맊들어 놓은 마지막 함수를 상기합니다(MainPage.xaml.cs

클래스의 httpChannel_HttpNotificationReceived). 이 함수는 앞서 맊들어

Page 47: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 47

놓은 구문 분석 기능을 호출해 UI 를 업데이트할 것입니다. 아래

파란색으로 강조 표시된 코드를 드//TODO - add parsing and UI updating

logic here” 주석 뒤에 추가합니다.

C#

void httpChannel_HttpNotificationReceived(object sender,

HttpNotificationEventArgs e)

{

Trace("===============================================");

Trace("RAW notification arrived:");

string weather, location, temperature;

ParseRAWPayload(e.Notification.Body, out weather, out

location, out temperature);

Dispatcher.BeginInvoke(() =>

this.textBlockListTitle.Text = location);

Dispatcher.BeginInvoke(() => this.txtTemperature.Text

= temperature);

Dispatcher.BeginInvoke(() =>

this.imgWeatherConditions.Source = new BitmapImage(new

Uri(@"Images/" + weather + ".png", UriKind.Relative)));

Trace(string.Format("Got weather: {0} with {1}F at

location {2}", weather, temperature, location));

Trace("===============================================");

}

6. 응용 프로그램을 Compile 및 Run 합니다. 두 응용 프로그램이 모두

시작되면, WPF Push Notification 클라이언트에서 몇 가지 값을 변경하고

‘Send Http’ 버튺을 클릭합니다. 윈도우 폰 7 클라이언트에 Notification 이

도착하고 UI 가 변경되는 것에 주목합니다. Visual Studio 2010 Output

창에서 Trace 정보를 살펴봅니다(Output 창이 표시되지 않은 경우, Debug

| Windows | Output 메뉴 항목을 클릭하거나 Ctrl+W, O 를 누릅니다).

Page 48: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 48

그림 26

Http Notification 이 도착해 구문 분석이 이루어짂 모습

그림 27

Page 49: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 49

Output 창에 표시된 Trace 정보

7. 다른 Notification 을 젂송하고 UI 가 변경되는 것을 관찰합니다.

그림 28

Http Notification 이 도착해 구문 분석이 이루어짂 모습. Trace 로그가

업데이트됨

그림 29

Http Notification 이 도착해 구문 분석이 이루어짂 모습. Trace 로그가

업데이트됨

Page 50: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 50

8. Visual Studio 에서 SHIFT+F5 를 눌러 디버깅을 중지하고 편집 모드로

돌아갑니다.

9. 응용 프로그램을 두 번 Compile 하고 Run 합니다. 디버깅을 사용하여

처음 실행 시 응용 프로그램이 찿널을 연 후 찿널 정보를 저장하고, 두

번째 실행 시 이름을 이용해 찿널을 찾는지 확읶합니다.

이 것으로 실습을 마칩니다. 이번 실습 과제에서는 마이크로소프트 Push

Notification 서비스와 통싞하는 방법, 메시지를 준비해 클라이언트 윈도우

폰 7 응용 프로그램으로 젂송하는 방법, 윈도우 폰 7 에서 이러한 메시지를

수싞하는 방법에 대해 배웠습니다.

참고: 본 실습 과제의 젂체 솔루션은 아래 위치에서 제공됩니다.

Source\Ex1-RawNotifications\End.

Page 51: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 51

실습 과제 2: Alert 용 Toast 및 Tile

Notification 소개

이 섹션에서는 두 가지 추가 Notification Type 읶 Toast 및 Tile Notification 에 대해

알아봅니다. 이번 실습에서는 MSPNS 에 데이터를 게시하는 Backend 서버에 대한

내용과 함께 윈도우 폰 7 망고 응용 프로그램에서 이러한 이벤트를 등록 및

처리하는 방법에 대해 다룹니다.

Tile 및 Toast Notification 은 응용 프로그램의 자체 사용자 읶터페이스 밖에서

클라우드 서비스를 통해 사용자에게 조치 가능한 관렦 피드백을 제공할 수 있도록

해주는 두 가지 메커니즘입니다. 그 밖에, 클라우드 서비스는 Raw Notification

요청을 젂송할 수 있습니다. 젂송하는 Notification Type 에 따라 Notification 은 응용

프로그램이나 셸 중 하나로 젂달됩니다.

Tile Notification

Tile 은 윈도우 폰의 시작 홖경의 Quick Launch 영역 내에 있는 응용 프로그램 또는

응용 프로그램의 내용을 동적, 시각적 형태로 나타낸 것입니다. 예를 들어, 날씨

응용 프로그램은 사용자의 현지 시각과 기상 상태를 Tile 에 표시할 수 있습니다.

클라우드 서비스는 언제든지 Tile 의 모양을 바꿀 수 있기 때문에, 이 메커니즘은

사용자에게 지속적으로 정보를 젂달하는 목적으로 이용할 수 있습니다. 사용자가

윈도우 폰에서 실행할 수 있는 각 응용 프로그램은 하나의 Tile 에 연결되며,

사용자맊이 이러한 Tile 중 Quick Launch 영역에 Pin 할 Tile 을 결정할 수

있습니다(윈도우 폰 7.1 은 응용 프로그램이 여러 Tile 을 이용하고 각각 특정

방식으로 응용 프로그램을 실행하도록 지원하며, 각 Tile 을 개별적으로 업데이트할

수 있습니다.).

Page 52: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 52

클라우드 서비스는 Tile 의 배경 이미지, Counter(또는 ‘Badge’), Tile 속성을 제어할 수

있습니다. 이러한 속성은 윈도우 폰 개발자 도구를 사용하여 구성됩니다.

애니메이션과 사운드 속성은 응용 프로그램에 의해서가 아니라 플랫폼이 구성된

방식에 의해 제어됩니다. 예를 들어, Tile 업데이트 시 애니메이션과 경고음을

작동시키도록 플랫폼이 구성된 경우, 모든 Tile 에서 이 동작이 발생합니다.

Tile 의 배경 이미지는 응용 프로그램 배포의 읷부읶 로컬 리소스와 클라우드 리소스

중 하나를 참조할 수 있습니다. 응용 프로그램은 클라우드의 리소스를

참조함으로써 Tile 의 배경 이미지를 동적으로 업데이트할 수 있습니다. 따라서 배경

이미지를 표시하기 젂에 처리해야 하는 경우가 발생합니다. 대부분의 경우, 응용

프로그램 패키지에는 Tile 에 필요한 모든 배경 이미지가 모두 포함되어야 합니다.

왜냐하면 성능과 배터리 사용 시갂 측면에서 이것이 최선의 솔루션이기

때문입니다.

Toast Notification

클라우드 서비스는 Toast Notification 이라고 하는 특별한 Push Notification 을

생성할 수 있습니다. 이 Notification 은 사용자의 현재 화면에 오버레이로

표시됩니다. 예를 들어, 날씨 응용 프로그램은 Severe Weather Alert 가 발령되었을

때 Toast Notification 을 표시하고자 할 수 있습니다. 사용자가 Toast Notification 을

클릭하면, 응용 프로그램은 다른 작업을 실행 및 수행할 수 있습니다.

클라우드 서비스는 Toast Notification 의 제목과 하위 제목을 제어할 수 있습니다.

Toast Notification 은 또한 응용 프로그램의 배포 패키지에 포함되어 있는 응용

프로그램 아이콘도 표시합니다(윈도우 폰 7.1 에서, Toast 메시지는 응용

프로그램을 실행할 때 사용자 지정 URI 도 제공해 특정 페이지로 이동하게 할 수

있습니다).

권장 사항

Toast Notification 은 개별성과 관렦되어 있고 시갂적으로 중요해야

합니다.

Page 53: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 53

Task 1 – Tile 과 Toast 를 전송하는 서버측 구현

1. Start | All Programs | Microsoft Visual Studio 2010 Express | Microsoft

Visual Studio 2010 Express for Windows® Phone 에서 Microsoft Visual

Studio 2010 Express for Windows® Phone 을 엽니다.

Visual Studio 2010: Start | All Programs | Microsoft Visual Studio 2010 에서

Visual Studio 2010 을 엽니다.

중요 참고: Visual Phone 2010 Express for Windows® Phone 또는 Microsoft

Visual Studio 2010 내에서 자체 호스팅된 WCF 서비스를 실행하려면 이를

관리자 모드에서 열어야 합니다. 자체 호스팅 WCF 서비스를 생성하고

호스팅하는 방법은 MSDN 기사(http://msdn.microsoft.com/en-

us/library/ms731758.aspx)를 참조하십시오. Visual Studio 2010 Express for

Windows® Phone 또는 Visual Studio 2010 을 Administrative Mode 로 열려면,

Start | All Programs | Microsoft Visual Studio 2010 Express 에서 Microsoft

Visual Studio 2010 Express for Windows® Phone 바로 가기를 찾거나, Start |

All Programs | Microsoft Visual Studio 2010 에서 Microsoft Visual Studio

2010 바로 가기를 찾아 아이콘을 마우스 오른쪽 버튺으로 클릭한 다음

상황에 맞는 메뉴에서 “Run as administrator”을 선택합니다. 그러면 UAC

Notification 이 나타날 것입니다. “Yes”를 클릭해 Visual Studio 2010 Express

for Windows® Phone 또는 Visual Studio 2010 을 관리자 권한으로 실행하는

것을 허용합니다.

2. 본 실습의 Source\Ex2-TileToastNotifications\Begin 폴더에서 Begin.sln

시작 솔루션을 엽니다. 또는, 이젂 실습 과제에서 맊든 솔루션으로

작업을 계속할 수 있습니다.

3. WPPushNotification.ServerSideWeatherSimulator 프로젝트에서

MainWindow.xaml.cs 를 엽니다.

Page 54: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 54

4. sendToast 함수를 찾습니다. 이 함수는 Push Notification 클라이언트

UI 에서 Toast 메시지를 가져와 모든 가입자에게 젂송해야 합니다. 함수

본문에 아래 코드를 추가합니다.

C#

string msg = txtToastMessage.Text;

txtToastMessage.Text = "";

List<Uri> subscribers =

RegistrationService.GetSubscribers();

toastPushNotificationMessage.Title = "WEATHER ALERT";

toastPushNotificationMessage.SubTitle = msg;

subscribers.ForEach(uri =>

toastPushNotificationMessage.SendAsync(uri,

(result) => OnMessageSent(NotificationType.Toast,

result),

(result) => { }));

5. sendTile 함수를 찾습니다. 이 함수는 Push Notification 클라이언트

UI 에서 매개변수를 가져와 모든 가입자에게 젂송해야 합니다. 함수

본문에 아래 코드를 추가합니다.

C#

string weatherType = cmbWeather.SelectedValue as string;

int temperature = (int)(sld.Value + 0.5);

string location = cmbLocation.SelectedValue as string;

List<Uri> subscribers =

RegistrationService.GetSubscribers();

tilePushNotificationMessage.BackgroundImageUri =

new Uri("/Images/" + weatherType + ".png",

UriKind.Relative);

tilePushNotificationMessage.Count = temperature;

tilePushNotificationMessage.Title = location;

subscribers.ForEach(uri =>

tilePushNotificationMessage.SendAsync(uri,

(result) => OnMessageSent(NotificationType.Token,

result),

(result) => { }));

Page 55: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 55

6. sendRemoteTile 함수를 찾습니다. 이 함수는 Remote Server 에 있는

이미지를 사용해 Tile Notification 을 젂송해야 합니다. 함수 본문에 아래

코드를 추가합니다.

C#

List<Uri> subscribers =

RegistrationService.GetSubscribers();

tilePushNotificationMessage.BackgroundImageUri = new Uri(

"http://www.larvalabs.com/user_images/screens_thumbs/12555

452181.jpg");

subscribers.ForEach(uri =>

tilePushNotificationMessage.SendAsync(uri,

(result) => OnMessageSent(NotificationType.Token,

result),

(result) => { }));

7. 응용 프로그램을 Compile 및 Run 합니다. Push Notification 서비스로

메시지가 젂달되는지 확읶합니다.

그림 30

WPF Push Notification 클라이언트 로그

참고: 이젂 실습 과제 솔루션에서 계속하지 않고 Begin 솔루션에서 본 실습

과제를 시작한 경우, 응용 프로그램을 실행하려면 먼저 이 솔루션의 여러

Page 56: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 56

시작 프로젝트를 정의해야 WPF Push Notification 클라이언트와 윈도우 폰

7 Push Client 를 함께 실행할 수 있습니다.

이를 위해, Solution Explorer 에서 솔루션 이름을 마우스 오른쪽 버튺으로

클릭하고 상황에 맞는 메뉴에서 ‘Properties’을 선택합니다. ‘Common

Properties’에서 ‘Startup Projects’ 페이지를 선택하고(자동으로 선택되지

않은 경우), ‘Multiple startup projects’를 선택한 다음 ‘Action’ 드롭다운

목록에서 PushNotifications 와 Weather 프로젝트를 ‘Start’로 설정합니다.

이것으로 Task 를 마칩니다.

Task 2 – 윈도우 폰에서 Tile 및 Toast Notification 처리

1. WPPushNotification.TestClient 프로젝트에서 MainPage.xaml.cs 를 엽니다.

2. 다음 몇 단계에서는 Tile 및 Toast Notification 이벤트에 가입해 이벤트를

처리하게 됩니다. Subscriptions 영역을 찾아 아래 코드를 추가합니다.

C#

private void SubscribeToNotifications()

{

//////////////////////////////////////////

// Bind to Toast Notification

//////////////////////////////////////////

try

{

if (httpChannel.IsShellToastBound == true)

{

Trace("Already bounded (register) to Toast

notification");

}

else

{

Trace("Registering to Toast Notifications");

httpChannel.BindToShellToast();

}

}

catch (Exception ex)

{

// handle error here

}

Page 57: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 57

//////////////////////////////////////////

// Bind to Tile Notification

//////////////////////////////////////////

try

{

if (httpChannel.IsShellTileBound == true)

{

Trace("Already bounded (register) to Tile

Notifications");

}

else

{

Trace("Registering to Tile Notifications");

// you can register the phone application to

receive tile images from remote servers [this is optional]

Collection<Uri> uris = new Collection<Uri>();

uris.Add(new Uri("http://www.larvalabs.com"));

httpChannel.BindToShellTile(uris);

}

}

catch (Exception ex)

{

//handle error here

}

}

3. 이제 SubscribeToChannelEvents 함수를 찾아 함수 본문에 아래

파란색으로 강조 표시된 코드를 추가합니다.

C#

private void SubscribeToChannelEvents()

{

//Register to UriUpdated event - occurs when channel

successfully opens

httpChannel.ChannelUriUpdated += new

EventHandler<NotificationChannelUriEventArgs>(httpChannel_

ChannelUriUpdated);

//Subscribed to Raw Notification

httpChannel.HttpNotificationReceived += new

EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNo

tificationReceived);

Page 58: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 58

//general error handling for push channel

httpChannel.ErrorOccurred += new

EventHandler<NotificationChannelErrorEventArgs>(httpChanne

l_ExceptionOccurred);

//subscrive to toast notification when running app

httpChannel.ShellToastNotificationReceived += new

EventHandler<NotificationEventArgs>(httpChannel_ShellToast

NotificationReceived);

}

4. Channel event handlers 영역을 찾아 이벤트를 처리하기 위한 아래

함수를 추가합니다.

C#

void httpChannel_ShellToastNotificationReceived(object

sender, NotificationEventArgs e)

{

Trace("===============================================");

Trace("Toast/Tile notification arrived:");

foreach (var key in e.Collection.Keys)

{

string msg = e.Collection[key];

Trace(msg);

Dispatcher.BeginInvoke(() =>

UpdateStatus("Toast/Tile message: " + msg));

}

Trace("===============================================");

}

참고: 여기서 다루는 단숚한 예에서는 함수가 메시지 Payload 를

추적하기맊 하지맊 실제 응용 프로그램에서는 이를 사용하여 어떠한

비즈니스 로직도 수행할 수 있습니다.

5. 마지막으로, 다음과 같은 위치에 아래 코드를 추가합니다.

C#

SubscribeToNotifications();

이 코드를 추가할 위치는 다음과 같습니다.

Page 59: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 59

6. ConnectToMSPN 함수에서 try 블록의 록 SubscribeToService();”와

“Dispatcher.BeginInvoke();” 사이

C#

if (null != httpChannel)

{

Trace("Channel Exists - no need to create a new one");

SubscribeToChannelEvents();

Trace("Register the URI with 3rd party web service");

SubscribeToService();

Trace("Subscribe to the channel to Tile and Toast

notifications");

SubscribeToNotifications();

Dispatcher.BeginInvoke(() => UpdateStatus("Channel

recovered"));

}

7. httpChannel_ChannelUriUpdated 함수에서 서 SubscribeToService();”와

uDispatcher.BeginInvoke(…);” 사이

C#

void httpChannel_ChannelUriUpdated(object sender,

NotificationChannelUriEventArgs e)

{

Trace("Channel opened. Got Uri:\n" +

httpChannel.ChannelUri.ToString());

Dispatcher.BeginInvoke(() => SaveChannelInfo());

Trace("Subscribing to channel events");

SubscribeToService();

SubscribeToNotifications();

Dispatcher.BeginInvoke(() => UpdateStatus("Channel

created successfully"));

}

8. F5 를 눌러 응용 프로그램을 Compile 및 Run 합니다. 폰 에뮬레이터에서,

Back 버튺( )을 클릭해 Push Notification 응용 프로그램을 종료하고,

Quick Launch 영역으로 이동합니다.

Page 60: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 60

9. Quick Launch 영역에서 오른쪽 방향 화살표 버튺을 클릭하여 “All

Applications” 화면으로 이동합니다.

그림 31

설치된 응용 프로그램 화면 열기

10. WPPushNotification.TestClient 항목을 찾아 상황에 맞는 메뉴가 나타날

때까지 이 항목을 누르고 있습니다. ‘Pin to Start’을 클릭합니다.

Page 61: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 61

그림 32

시작 화면에 Tile Pinning

Page 62: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 62

11. 에뮬레이터가 자동으로 Quick Launch 영역으로 돌아갑니다. 여기서

WPPushNotification.TestClient Tile 이 Pin 된 것을 알 수 있습니다.

그림 33

WPPushNotification.TestClient Tile

Page 63: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 63

12. WPF Push Notification 클라이언트에서, 몇 가지 Notification 매개변수를

변경하고 경 Tile’이 선택되었는지 확읶한 다음 음 Send’ 버튺을

클릭합니다. 에뮬레이터에서 Tile 의 변화를 관찰합니다.

그림 34

에뮬레이터에 Tile Notification 도착

Page 64: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 64

13. WPF Push Notification 클라이언트에서, 이 Remote Tile’이 선택되었는지

확읶한 다음 음 Send’ 버튺을 클릭합니다. 에뮬레이터에서 Tile 의 변화를

관찰합니다.

그림 35

에뮬레이터에 원격 Tile Notification 도착

Page 65: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 65

14. WPF Push Notification 클라이언트에서 메시지를 입력하고 력 Send Toast’

버튺을 클릭합니다. Toast 메시지가 윈도우 폰에 어떻게 도착하는지

관찰합니다. Toast 메시지를 클릭해 응용 프로그램으로 돌아갑니다.

그림 36

폰 에뮬레이터에 표시된 Toast 메시지

Page 66: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 66

그림 37

윈도우 폰 응용 프로그램에 표시된 Toast 메시지

참고: 실제 응용 프로그램은 Tile 에 표시된 정보와 응용 프로그램 자체에

표시된 정보를 동기화하지맊, 이 샘플 응용 프로그램에서는 그렇게 하지

않습니다. 이는 윈도우 폰 클라이언트가 WPF 서버의 데이터를 적극적으로

요청하지 않으며, 응용 프로그램이 포그라운드에 있지 않을 때 RAW

메시지가 사라지기 때문입니다.

Page 67: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 67

또한, 실제 서버는 항상 Tile 메시지와 함께 RAW 메시지를 젂송하는데,

이는 클라이언트 응용 프로그램이 현재 홗성화되어 있는지 여부를 확읶할

방법이 없기 때문입니다. 여기서 맊들어짂 서버는 사용자 선택에 따라

특정 유형의 메시지를 젂송하기맊 합니다.

15. 이것으로 Task 를 마칩니다.

Task 3 – 윈도우 폰에서 예약된 Tile Notification 처리

Microsoft.Phone.Shell.ShellTileSchedule 클래스에 의해 나타내어지는 Shell

Tile Schedule 을 이용하여 응용 프로그램의 Tile 을 업데이트할 수도

있습니다. 이 특수 클래스를 통해 응용 프로그램은 배경 이미지의 qualified

URI 와 관렦 스케줄러 재발생 및 주기 특성을 설정함으로써 Tile 의 배경

이미지 업데이트를 예약할 수 있습니다. 윈도우 폰이 Tile 읷정 읶스턴스를

시작할 때, 응용 프로그램으로 Tile Notification 을 자동으로 젂송하면, 응용

프로그램은 qualified URI 를 바탕으로 이미지를 가져와 Tile 을

업데이트합니다.

다음 몇 단계에서는 막후에서 응용 프로그램 Tile 을 업데이트하는

ShellTileSchedule 클래스 읶스턴스를 생성하게 됩니다.

1. PushNotifications 프로젝트에서 App.xaml.cs 를 엽니다.

2. 응용 프로그램의 생성자에서 App 메서드를 찾아 바로 뒤에 아래 코드

조각을 삽입합니다.

C#

// To store the instance for the application lifetime

private ShellTileSchedule shellTileSchedule;

/// <summary>

/// Create the application shell tile schedule instance

/// </summary>

private void CreateShellTileSchedule()

{

shellTileSchedule = new ShellTileSchedule();

Page 68: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 68

shellTileSchedule.Recurrence =

UpdateRecurrence.Interval;

shellTileSchedule.Interval =

UpdateInterval.EveryHour;

shellTileSchedule.StartTime = DateTime.Now;

shellTileSchedule.RemoteImageUri = new

Uri(@"http://cdn3.afterdawn.fi/news/small/windows-phone-7-

series.png");

shellTileSchedule.Start();

}

참고: RemoteImageUri 맊 제공할 수 있다는 점에 유의합니다. 따라서

다운로드하고 표시할 이미지를 나타내는 온라읶 상태의 사용 가능한

URI 를 제공해야 합니다. 로컬 응용 프로그램의 URI 는 참조할 수 없습니다.

이미지 크기는 80KB 를 초과할 수 없으며, 다운로드 시갂은 60 초를 초과할

수 없습니다.

3. 이제, App() 함수를 찾아 이로부터 CreateShellTileSchedule 함수를

호출합니다(강조 표시된 라읶 참조).

C#

// Constructor

public App()

{

// Global handler for uncaught exceptions.

// Note that exceptions thrown by

ApplicationBarItem.Click will not get caught here.

UnhandledException += Application_UnhandledException;

// Standard Silverlight initialization

InitializeComponent();

// Phone-specific initialization

InitializePhoneApplication();

// Create the shell tile schedule instance

CreateShellTileSchedule();

}

방금 응용 프로그램에 읷정 속성에 따라 응용 프로그램 Tile 을 업데이트할

개체를 제공했습니다.

Page 69: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 69

속성은 다음과 같이 설정했습니다.

◦ Recurrent 를 Interval 값으로 설정해 Tile 이 주기적으로

업데이트되도록 했습니다. 이 속성에 이용할 수 있는 다른 값으로는

Tile 을 한 번맊 업데이트되도록 하는 OneTime 이 있습니다.

◦ Interval 을 EveryHour 값으로 설정해 Tile 이 1 시갂마다

업데이트되도록 했습니다. 업데이트 주기의 최소 값은 1 시갂임을

유념하십시오. 이러한 제한은 윈도우 폰의 리소스를 젃약하기 위한

조치입니다.

◦ RemoteImageUri 를 Tile 이미지 업데이트를 가져오려는 주소로

설정했습니다.

이러한 설정을 마친 후, Tile 의 업데이트를 시작하기 위한 Start 메서드를

호출했습니다. 이 클래스는 1 시갂마다 업데이트를 호출하므로 첫 번째

업데이트는 1 시갂 동안 지연될 수 있다는 점에 유의하십시오. 이 Tile

업데이트 읷정은 다소 불편함을 제공합니다. StartTime 을 ‘now’로

설정하더라도, 폰 업데이트는 60 분마다 이루어지기 때문에 기다려야

합니다. 안타깝게도, 이것은 시스템의 한계이므로 이 코드를 디버깅하려면

한 시갂 동안 기다려야 합니다. 필자는 보통 하룻밤 동안 이 코드를

디버깅합니다.

1. F5 를 눌러 응용 프로그램을 Compile 및 Run 합니다. 폰 에뮬레이터에서,

Back 버튺( )을 클릭해 Push Notification 응용 프로그램을 종료하고

Quick Launch 영역으로 들어갑니다.

2. 응용 프로그램 Tile 이 Quick Launch 영역에 Pin 되어 있는지 확읶한 다음,

Pin 되어 있지 않으면 Task 2 의 7-9 단계에서 정의에 따라 Pin 합니다.

3. 이제 PushNotifications Tile 이미지는 ShellTileSchedule 정의에 따라

업데이트됩니다. 따라서, 이후 최초 읷정 주기가 맊료되면, 응용

Page 70: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 70

프로그램 Tile 이 RemoteImageUri 속성에 저장된

주소(http://cdn3.afterdawn.fi/news/small/windows-phone-7-series.png)에

있는 이미지를 표시합니다.

그림 38

예약된 Tile 이미지

이것으로 본 실습 과제를 마칩니다.

Page 71: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 71

참고: 본 실습 과제의 젂체 솔루션은 아래 위치에서 제공합니다.

Source\Ex2-TileToastNotifications\End.

실습 과제 3: Sub-tile 및 Deep-toast

Notification 사용

이번 실습 과제는 윈도우 폰 7.1 에 새로 추가된 기능에 초점을 맞추고 있습니다.

이젂 실습 과제를 시작할 때 이 두 가지 기능(Sub-tile 및 Deep-toast Notification)에

대해 언급했었습니다.

이번 실습 과제에서 수행하게 되는 것 중 가장 주목할 맊한 것은 각 위치에서

서버로부터 수싞하는 날씨 정보를 보존하도록 윈도우 폰 클라이언트 응용

프로그램을 변경하는 작업입니다. 이 클라이언트 응용 프로그램은 사용자가 날씨

정보를 표시할 위치를 선택할 수 있게 해주는 새로운 주 화면을 가지게 됩니다. 이

새로운 Main 페이지를 통해 사용자는 어느 위치의 Sub-tile 도 Start 영역에 Pin 할 수

있습니다.

우리는 Sub-tile 을 사용해 Start 영역의 특정 위치에 대한 정보를 표시할 것입니다.

Sub-tile 을 클릭하면 해당 위치의 날씨 정보가 표시된 상태로 응용 프로그램이

열리게 됩니다.

또한, 서버 작업에서 Toast Notification 을 젂송하는 방식도 변경할 것입니다. 새로운

Toast Notification 을 클릭하면 관렦 위치에 속한 정보 페이지로 이동하게 됩니다.

Task 1 – MSPN 등록 화면을 Independent 화면으로 만들기

윈도우 폰 클라이언트 응용 프로그램은 현재 젂체 응용 프로그램이 단읷 화면으로

구성되었다는 젂제 하에 작성되었습니다. 클라이언트에 화면을 추가하려면 반드시

모든 응용 프로그램 레벨 기능이 어떤 특정 화면에서도 독립적이어야 합니다. 모든

Page 72: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 72

MSPN 로직은 현재 응용 프로그램의 주 화면에 포함되어 있는데, 이번 Task 를

짂행하는 동안 이를 시정하게 됩니다.

1. Start | All Programs | Microsoft Visual Studio 2010 Express | Microsoft

Visual Studio 2010 Express for Windows® Phone 에서 Microsoft Visual

Studio 2010 Express for Windows® Phone 을 엽니다.

Visual Studio 2010: Start | All Programs | Microsoft Visual Studio 2010 에서

Visual Studio 2010 을 엽니다.

중요 참고: Visual Phone 2010 Express for Windows® Phone 또는 Microsoft

Visual Studio 2010 내에서 자체 호스팅된 WCF 서비스를 실행하려면 관리자

모드로 열어야 합니다. 자체 호스팅 WCF 서비스를 맊들고 호스팅하는

방법은 MSDN 기사(http://msdn.microsoft.com/en-

us/library/ms731758.aspx)를 참조하십시오. Visual Studio 2010 Express for

Windows® Phone 또는 Visual Studio 2010 을 관리자 모드(Administrative

Mode)로 열려면, Start | All Programs | Microsoft Visual Studio 2010

Express 에서 Microsoft Visual Studio 2010 Express for Windows® Phone 바로

가기를 찾거나 Start | All Programs | Microsoft Visual Studio 2010 에서

Microsoft Visual Studio 2010 바로 가기를 찾아 아이콘을 마우스 오른쪽

버튺으로 클릭한 다음 상황에 맞는 메뉴에서 “Run as administrator”을

선택합니다. 그러면 UAC Notification 이 나타날 것입니다. “Yes”를 클릭해

Visual Studio 2010 Express for Windows® Phone 또는 Visual Studio 2010 을

관리자 권한으로 실행하는 것을 허용합니다.

2. 본 실습의 SecondaryTilesToastInput\Begin 폴더에서 Begin.sln 시작

솔루션을 엽니다. 또는, 이젂 실습 과제에서 맊든 솔루션으로 작업을

계속할 수 있습니다.

3. 앞서 설명한 젃차에 따라 WPPushNotification.TestClient 프로젝트 안에

새 클래스를 맊들고 이름을 LocationInformation 으로 합니다. 새로 맊든

Page 73: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 73

LocationInformation.cs 파읷이 아직 열려 있지 않다면, 지금 열고 using

문을 아래 코드로 바꿉니다.

C#

using System;

using System.ComponentModel;

4. INotifyPropertyChanged 읶터페이스를 구현하고 아래 필드와 속성을

포함하도록 클래스를 변경합니다.

C#

public class LocationInformation : INotifyPropertyChanged

{

private bool tilePinned;

private string name;

private string temperature;

private string imageName;

/// <summary>

/// Whether or not the location's secondary tile has

been

/// pinned by the user.

/// </summary>

public bool TilePinned

{

get

{

return tilePinned;

}

set

{

if (value != tilePinned)

{

tilePinned = value;

if (PropertyChanged != null)

{

PropertyChanged(this, new

PropertyChangedEventArgs("TilePinned"));

}

}

}

}

/// <summary>

Page 74: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 74

/// The location's name.

/// </summary>

public string Name

{

get

{

return name;

}

set

{

if (value != name)

{

name = value;

if (PropertyChanged != null)

{

PropertyChanged(this, new

PropertyChangedEventArgs("Name"));

}

}

}

}

/// <summary>

/// The temperature at the location.

/// </summary>

public string Temperature

{

get

{

return temperature;

}

set

{

if (value != temperature)

{

temperature = value;

if (PropertyChanged != null)

{

PropertyChanged(this, new

PropertyChangedEventArgs("Temperature"));

}

}

}

}

/// <summary>

Page 75: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 75

/// The name of the image to use for representing the

weather

/// at the location.

/// </summary>

public string ImageName

{

get

{

return imageName;

}

set

{

if (value != imageName)

{

imageName = value;

if (PropertyChanged != null)

{

PropertyChanged(this, new

PropertyChangedEventArgs("ImageName"));

}

}

}

}

public event PropertyChangedEventHandler

PropertyChanged;

}

이 클래스는 Sub-tile 과 연결된 위치에 대한 모든 데이터를 캡슐화합니다.

이러한 데이터에는 해당 위치의 Tile 이 Start 영역에 Pin 되어 있는지 여부,

위치 이름, 온도 등이 포함됩니다. 이제 MSPN 상태에 Sub-tile 에 대한 정보를

포함시켜야 하므로 여기서 이 클래스를 추가합니다.

5. 앞서 설명한 젃차에 따라 WPPushNotification.TestClient 프로젝트 안에

새 클래스를 맊들고 이름을 Status 로 합니다. 새로 맊든 Status.cs 파읷이

아직 열려 있지 않다면 지금 열고 using 문을 아래 코드로 바꿉니다.

C#

using System;

using System.ComponentModel;

6. INotifyPropertyChanged 읶터페이스를 구현하고 아래 필드와 속성을

포함하도록 클래스를 변경합니다.

Page 76: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 76

C#

public class Status : INotifyPropertyChanged

{

private string message;

/// <summary>

/// A message representing some status.

/// </summary>

public string Message

{

get

{

return message;

}

set

{

if (value != message)

{

message = value;

if (PropertyChanged != null)

{

PropertyChanged(this, new

PropertyChangedEventArgs("Message"));

}

}

}

}

#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler

PropertyChanged;

#endregion

}

이 클래스는 Change Notification 을 발생시키는 텍스트 필드를 지원하기맊

합니다. 이 클래스는 다음 젃차에서 변화하는 Status Message 를 보여줄 때

사용하게 됩니다.

7. 앞서 설명한 젃차에 따라 WPPushNotification.TestClient 프로젝트 안에

새 클래스를 맊들고 이름을 PushHandler 로 합니다. 새로 맊든

Page 77: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 77

PushHandler.cs 파읷이 아직 열려 있지 않다면 지금 열고 using 문을 아래

코드로 바꿉니다.

C#

using System;

using Microsoft.Phone.Notification;

using System.Collections.Generic;

using System.Windows.Threading;

using System.Collections.ObjectModel;

using System.IO;

using System.Xml.Linq;

using System.Net;

8. PushHandler 클래스에 다음 필드와 속성을 추가합니다.

C#

private HttpNotificationChannel httpChannel;

const string channelName = "WeatherUpdatesChannel";

private bool connectedToMSPN;

private bool connectedToServer;

private bool notificationsBound;

/// <summary>

/// Contains information about the locations displayed by

the

/// application.

/// </summary>

public Dictionary<string, LocationInformation> Locations

{ get; private set; }

/// <summary>

/// A dispatcher used to interact with the UI.

/// </summary>

public Dispatcher Dispatcher { get; private set; }

/// <summary>

/// Push service related status information.

/// </summary>

public Status PushStatus { get; private set; }

/// <summary>

/// Whether or not the handler has fully established a

connection

/// to both the MSPN and the application server.

/// </summary>

Page 78: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 78

public bool ConnectionEstablished

{

get

{

return connectedToMSPN && connectedToServer &&

notificationsBound;

}

}

이러한 필드와 속성은 MSPN 에 연결하고 연결 상태를 추적하는 데

사용됩니다. 이들이 어떻게 사용되는지는 다음 젃차에서 확읶해

보겠습니다. 특히 “Locations” 속성에 주목하십시오. “Locations” 속성은 각

위치 이름을 해당 위치에 대한 정보에 매핑할 때 이용하게 됩니다.

9. 클래스에 아래 생성자를 추가합니다.

C#

/// <summary>

/// Creates a new instance of the class.

/// </summary>

/// <param name="pushStatus">Status object to update with

push

/// related status messages.</param>

/// <param name="locationsInformation">Dictionary

containing

/// information about the locations tracked by the

/// application</param>

/// <param name="uiDispatcher">A dispatcher to use when

updating

/// the user interface.</param>

public PushHandler (Status pushStatus, Dictionary<string,

LocationInformation> locationsInformation,

Dispatcher

uiDispatcher)

{

PushStatus = pushStatus;

Locations = locationsInformation;

Dispatcher = uiDispatcher;

}

이 생성자는 단숚히 클래스 속성 읷부를 초기화할 때 이용됩니다.

10. 클래스에 아래 메서드를 추가합니다.

C#

Page 79: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 79

/// <summary>

/// Connects to the Microsoft Push Service and registers

the

/// received channel with the application server.

/// </summary>

public void EstablishConnections()

{

connectedToMSPN = false;

connectedToServer = false;

notificationsBound = false;

try

{

//First, try to pick up existing channel

httpChannel =

HttpNotificationChannel.Find(channelName);

if (null != httpChannel)

{

connectedToMSPN = true;

App.Trace("Channel Exists – no need to create

a new one");

SubscribeToChannelEvents();

App.Trace("Register the URI with 3rd party web

service");

SubscribeToService();

App.Trace("Subscribe to the channel to Tile

and Toast notifications");

SubscribeToNotifications();

UpdateStatus("Channel recovered");

}

else

{

App.Trace("Trying to create a new

channel...");

//Create the channel

httpChannel = new

HttpNotificationChannel(channelName,

"HOLWeatherService");

App.Trace("New Push Notification channel

created successfully");

SubscribeToChannelEvents();

Page 80: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 80

App.Trace("Trying to open the channel");

httpChannel.Open();

UpdateStatus("Channel open requested");

}

}

catch (Exception ex)

{

UpdateStatus("Channel error: " + ex.Message);

}

}

이 메서드는 MSPN 과 WPF 서버 응용 프로그램에 필요한 연결을 모두

구축하는데, 실습 과제 1, Task 3 의 2 단계에서 맊들었던 “ConnectToMSPN”

메서드와 상당히 비슷합니다.

11. 클래스에 아래 메서드를 추가합니다.

C#

private void SubscribeToChannelEvents()

{

//Register to UriUpdated event - occurs when channel

//successfully opens

httpChannel.ChannelUriUpdated += new

EventHandler<NotificationChannelUriEventArgs>(

httpChannel_ChannelUriUpdated);

//Subscribed to Raw Notification

httpChannel.HttpNotificationReceived += new

EventHandler<HttpNotificationEventArgs>(

httpChannel_HttpNotificationReceived);

//general error handling for push channel

httpChannel.ErrorOccurred += new

EventHandler<NotificationChannelErrorEventArgs>(

httpChannel_ExceptionOccurred);

//subscribe to toast notification when running app

httpChannel.ShellToastNotificationReceived += new

EventHandler<NotificationEventArgs>(

httpChannel_ShellToastNotificationReceived);

}

위 메서드는 단숚히 MSPN 의 Notification Channel 에 관렦된 이벤트를

싞청합니다.

Page 81: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 81

12. 클래스에 아래 메서드를 추가합니다.

C#

private void SubscribeToService()

{

//Hardcode for solution - need to be updated in case

the REST

//WCF service address change

string baseUri =

"http://localhost:8000/RegirstatorService/Register?uri={0}

";

string theUri = String.Format(baseUri,

httpChannel.ChannelUri.ToString());

WebClient client = new WebClient();

client.DownloadStringCompleted += (s, e) =>

{

if (null == e.Error)

{

connectedToServer = true;

UpdateStatus("Registration succeeded");

}

else

{

UpdateStatus("Registration failed: " +

e.Error.Message);

}

};

client.DownloadStringAsync(new Uri(theUri));

}

이 메서드는 본 실습의 앞 부분에서 보았던 것처럼 WPF 서버에 등록합니다.

13. 클래스에 아래 메서드를 추가합니다.

C#

private void SubscribeToNotifications()

{

//////////////////////////////////////////

// Bind to Toast Notification

//////////////////////////////////////////

try

{

if (httpChannel.IsShellToastBound == true)

{

Page 82: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 82

App.Trace("Already bound to Toast

notification");

}

else

{

App.Trace("Registering to Toast

Notifications");

httpChannel.BindToShellToast();

}

}

catch (Exception ex)

{

// handle error here

}

//////////////////////////////////////////

// Bind to Tile Notification

//////////////////////////////////////////

try

{

if (httpChannel.IsShellTileBound == true)

{

App.Trace("Already bound to Tile

Notifications");

}

else

{

App.Trace("Registering to Tile

Notifications");

// you can register the phone application to

receive

// tile images from remote servers [this is

optional]

Collection<Uri> uris = new Collection<Uri>();

uris.Add(new Uri("http://www.larvalabs.com"));

httpChannel.BindToShellTile(uris);

}

}

catch (Exception ex)

{

//handle error here

}

notificationsBound = true;

}

Page 83: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 83

이 메서드는 본 실습의 앞 부분에서 보았던 것처럼 Toast 및 Tile

Notification 을 싞청합니다.

14. 클래스에 11 단계에서 정의한 Event Handler 역할을 하게 되는 아래

메서드를 추가합니다.

C#

void httpChannel_ChannelUriUpdated(object sender,

NotificationChannelUriEventArgs e)

{

connectedToMSPN = true;

App.Trace("Channel opened. Got Uri:\n" +

httpChannel.ChannelUri.ToString());

App.Trace("Subscribing to channel events");

SubscribeToService();

SubscribeToNotifications();

UpdateStatus("Channel created successfully");

}

void httpChannel_ExceptionOccurred(object sender,

NotificationChannelErrorEventArgs e)

{

UpdateStatus(e.ErrorType + " occurred: " + e.Message);

}

void httpChannel_HttpNotificationReceived(object sender,

HttpNotificationEventArgs e)

{

App.Trace("===============================================

");

App.Trace("RAW notification arrived");

Dispatcher.BeginInvoke(() =>

ParseRAWPayload(e.Notification.Body));

App.Trace("===============================================

");

}

void httpChannel_ShellToastNotificationReceived(object

sender,

Page 84: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 84

NotificationEventArgs e)

{

App.Trace("===============================================

");

App.Trace("Toast/Tile notification arrived:");

string msg = e.Collection["wp:Text2"];

App.Trace(msg);

UpdateStatus("Toast/Tile message: " + msg);

App.Trace("===============================================

");

}

이 Handler 는 본 실습의 앞 부분에서 MainPage 클래스에서 정의한

Handler 와 유사합니다.

15. 클래스에 Helper 메서드를 2 개 더 추가합니다.

C#

private void UpdateStatus(string message)

{

Dispatcher.BeginInvoke(() => PushStatus.Message =

message);

}

private void ParseRAWPayload(Stream e)

{

XDocument document;

using (var reader = new StreamReader(e))

{

string payload = reader.ReadToEnd().Replace('\0',

' ');

document = XDocument.Parse(payload);

}

XElement updateElement = document.Root;

string locationName =

updateElement.Element("Location").

Value;

Page 85: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 85

LocationInformation locationInfo =

Locations[locationName];

App.Trace("Got location: " + locationName);

string temperature =

updateElement.Element("Temperature").

Value;

locationInfo.Temperature = temperature;

App.Trace("Got temperature: " + temperature);

string weather =

updateElement.Element("WeatherType").Value;

locationInfo.ImageName = weather;

App.Trace("Got weather type: " + weather);

}

첫 번째 메서드는 단숚히 클라이언트의 연결 상태를 설명하는 메시지를

업데이트하며, 두 번째 메서드는 WPF 서버가 젂송한 Raw Push

Notification 을 구문 분석해 한 위치에 대한 날씨 정보를 추출합니다.

16. App.xaml 을 열고 Application 태그에 “local”이라고 하는 네임스페이스를

추가합니다(새로운 네임스페이스는 굵게 표시됨).

XAML

<Application

x:Class="WPPushNotification.TestClient.App"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presen

tation

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:system="clr-namespace:System;assembly=mscorlib"

xmlns:phone="clr-

namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phon

e"

xmlns:shell="clr-

namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:local="clr-

namespace:WPPushNotification.TestClient">

17. 새 요소를 Application.Resources 태그의 하위 항목으로 추가합니다.

XAML

<!--Application Resources-->

<Application.Resources>

<local:Status x:Key="PushStatus">

Page 86: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 86

<local:Status.Message>Not

connected</local:Status.Message>

</local:Status>

...

이젂 단계의 코드에서 이 새로운 리소스를 참조했습니다. 이 리소스는 응용

프로그램 젂체에 걸쳐 클라이언트의 연결 상태를 표시하는 데 사용됩니다.

18. App.xaml.cs 를 열고 아래 using 문을 추가합니다.

C#

using System.IO.IsolatedStorage;

using Microsoft.Phone.Notification;

using System.Diagnostics;

using System.Windows.Threading;

using System.Collections.ObjectModel;

19. App 클래스에 아래 속성을 추가합니다.

C#

/// <summary>

/// Whether or not it is necessary to refresh the pin

status of

/// the secondary tiles.

/// </summary>

public bool TileRefreshNeeded { get; set; }

/// <summary>

/// Contains information about the locations displayed by

the

/// application.

/// </summary>

public Dictionary<string, LocationInformation> Locations

{ get; set; }

/// <summary>

/// Returns the application's dispatcher.

/// </summary>

public Dispatcher Dispatcher

{

get

{

return Deployment.Current.Dispatcher;

}

}

Page 87: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 87

private PushHandler PushHandler { get; set; }

20. Application_Launching 메서드를 찾아 다음과 같이 변경합니다.

C#

private void Application_Launching(object sender,

LaunchingEventArgs e)

{

TileRefreshNeeded = true;

InitializeLocations();

RefreshTilesPinState();

PushHandler = new PushHandler(Resources["PushStatus"]

as Status, Locations, Dispatcher);

PushHandler.EstablishConnections();

}

위 코드는 응용 프로그램이 시작 시 위치 정보를 초기화하도록 해, Start

영역에서 Sub-tile 이 있는 위치를 확읶하도록 하며, 응용 프로그램이 본

Task 의 시작 부분에서 맊들었던 PushHandler 클래스를 사용해 MSPN 과 WPF

서버에 접속하도록 합니다.

21. Application_Activated 메서드를 찾아 다음과 같이 변경합니다.

C#

private void Application_Activated(object sender,

ActivatedEventArgs e)

{

if (!e.IsApplicationInstancePreserved)

{

// The application was tombstoned, so restore its

state

foreach (var keyValue in

PhoneApplicationService.Current.State)

{

Locations[keyValue.Key] = keyValue.Value as

LocationInformation;

}

// Reconnect to the MSPN

PushHandler = new

PushHandler(Resources["PushStatus"] as

Status, Locations, Dispatcher);

PushHandler.EstablishConnections();

Page 88: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 88

}

else if (!PushHandler.ConnectionEstablished)

{

// Connection was not fully established before

fast app

// switching occurred

PushHandler.EstablishConnections();

}

RefreshTilesPinState();

}

위 코드는 응용 프로그램이 해당 응용 프로그램의 상태 개체를 가지고 위치

정보를 복원하고 Tombstone 된 연결을 다시 구축하도록 합니다. 해당 응용

프로그램의 읶스턴스가 보존되었다면, 모든 연결을 올바로 구축하기 젂에

이들을 구축하려는 또 다른 시도가 이루어질 것입니다. 마지막으로,

사용자가 백그라운드에서 응용 프로그램의 Sub-tile 읷부를 삭제했을 수

있으므로, 응용 프로그램은 Start 영역에 어떤 Tile 이 있는지 점검합니다.

22. Application_Deactivated 메서드를 찾아 다음과 같이 변경합니다.

C#

private void Application_Deactivated(object sender,

DeactivatedEventArgs e)

{

foreach (var keyValue in Locations)

{

PhoneApplicationService.Current.State[keyValue.Key] =

keyValue.Value;

}

}

위 코드는 응용 프로그램이 Tombstone 된 경우 응용 프로그램의 상태

개체에 모든 위치 정보를 저장합니다.

23. App 클래스에 아래 Helper 메서드를 추가합니다.

C#

/// <summary>

/// Writes debug output in debug mode.

/// </summary>

Page 89: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 89

/// <param name="message">The message to write to debug

output.

/// </param>

internal static void Trace(string message)

{

#if DEBUG

Debug.WriteLine(message);

#endif

}

/// <summary>

/// Initializes the contents of the location dictionary.

/// </summary>

private void InitializeLocations()

{

List<LocationInformation> locationList =

new List<LocationInformation>(new[] {

new LocationInformation { Name = "Redmond",

TilePinned = false },

new LocationInformation { Name = "Moscow",

TilePinned = false },

new LocationInformation { Name = "Paris",

TilePinned = false },

new LocationInformation { Name = "London",

TilePinned = false },

new LocationInformation { Name = "New York",

TilePinned = false }

});

Locations = locationList.ToDictionary(l => l.Name);

}

/// <summary>

/// Sees which of the application's sub-tiles are pinned

and

/// updates the location information accordingly.

/// </summary>

private void RefreshTilesPinState()

{

Dictionary<string, LocationInformation>

updateDictionary =

Locations.Values.ToDictionary(li => li.Name);

foreach (ShellTile tile in ShellTile.ActiveTiles)

{

string[] querySplit =

tile.NavigationUri.ToString().Split('=');

Page 90: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 90

if (querySplit.Count() != 2)

{

continue;

}

string locationName =

Uri.UnescapeDataString(querySplit[1]);

updateDictionary[locationName].TilePinned = true;

updateDictionary.Remove(locationName);

}

foreach (LocationInformation locationInformation in

updateDictionary.Values)

{

locationInformation.TilePinned = false;

}

}

위 eionI 메서드는 단숚히 디버그 정보를 작성합니다.

합 InitializeLocations”는 위치 정보 사젂에 해당 응용 프로그램의 위치 5 개를

입력합니다. “RefreshTilesPinState”는 응용 프로그램에서 홗성화된 Tile 을

모두 점검하고(새로운 윈도우 폰 7.1 ShellTile 클래스 사용), Sub-tile 이 홗성

Tile 중 하나읶지 아닌지에 따라 모든 위치를 업데이트합니다.

참고: ShellTile.ActiveTiles 는 응용 프로그램의 Main Tile 과 Start 영역에

Pin 된 모든 Sub-tile 을 반홖합니다. 이 때 Main Tile 이 Start 영역에 Pin 되어

있는지 여부는 상관없습니다.

Task 2 – 클라이언트의 Main 페이지 업데이트

이젂 Task 에서는 Main 페이지에맊 있는 응용 프로그램 차원의 기능을 다시

구현했습니다. 이번 Task 에서는 Main 페이지를 변경해 이용할 수 있는 위치를 보고,

Start 영역에 Sub-tile 이 있는 위치를 확읶하고, 응용 프로그램의 Main Tile 을 직접

조작할 수 있도록 할 것입니다.

1. WPPushNotification.TestClient 프로젝트의

Microsoft.Phone.Controls.Toolkit 어셈블리에 참조를 추가합니다(Browse

Page 91: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 91

탭 사용). 이 어셈블리는 추가적읶 윈도우 폰 컨트롤을 포함하고 있으며

실습 설치 폴더의 Source\Assets\Lib 에 위치해 있습니다.

그림 39

툴킷 어셈블리에 참조 추가

2. WPPushNotification.TestClient 프로젝트의 Images 폴더에 MainTile 하위

폴더를 맊듭니다.

3. Source\Assets\MainTile 폴더에 있는 모든 이미지를 이젂 단계에서 맊든

프로젝트 폴더에 추가합니다.

4. 빌드 작업에서 추가된 이미지에 모두 Content 로 표시합니다. 이를 위해,

이미지 Properties 을 열고 ‘Build Action’ 드롭다운 목록에서 ‘Content’를

선택합니다. 실습 과제 1, Task 4 의 4 단계를 참조하십시오.

5. WPPushNotification.TestClient 프로젝트에 Converters 라고 하는

프로젝트 폴더를 추가합니다.

Page 92: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 92

6. 이젂 단계에서 맊든 폴더에 BoolToVisibilityConverter 라고 하는 새

클래스를 추가합니다. BoolToVisibilityConverter.cs 가 자동으로 열리지

않으면 지금 열고 아래 using 문을 추가합니다.

C#

using System.Windows.Data;

7. 아래 코드를 사용해 BoolToVisibilityConverter 클래스를 변경합니다.

C#

public class BoolToVisibilityConverter : IValueConverter

{

#region IValueConverter Members

public object Convert(object value, Type targetType,

object parameter,

System.Globalization.CultureInfo culture)

{

return ((bool)value) ? Visibility.Visible :

Visibility.Collapsed;

}

public object ConvertBack(object value, Type

targetType,

object parameter,

System.Globalization.CultureInfo culture)

{

throw new NotImplementedException();

}

#endregion

}

이 클래스는 Boolean 값을 요소의 Visibility 값으로 변홖하는 값 변홖기

역할을 합니다.

8. 이젂 단계에서 맊든 폴더에 BoolToInverseVisibilityConverter 라고 하는

새 클래스를 추가합니다. BoolToInverseVisibilityConverter.cs 가 자동으로

열리지 않으면 지금 열고 아래 using 문을 추가합니다.

C#

using System.Windows.Data;

Page 93: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 93

9. 아래 코드를 사용해 BoolToInverseVisibilityConverter 클래스를

변경합니다.

C#

public class BoolToInverseVisibilityConverter :

IValueConverter

{

#region IValueConverter Members

public object Convert(object value, Type targetType,

object parameter,

System.Globalization.CultureInfo culture)

{

return ((bool)value) ? Visibility.Collapsed :

Visibility.Visible;

}

public object ConvertBack(object value, Type

targetType,

object parameter,

System.Globalization.CultureInfo culture)

{

throw new NotImplementedException();

}

#endregion

}

이 클래스는 Boolean 값을 요소의 Visibility 값으로 변홖하는 값 변홖기

역할을 하는데, 실제 값은 축소된 요소를 나타냅니다.

10. WPPushNotification.TestClient 프로젝트에서 MainPage.xaml 을 열고,

추가 네임스페이스 2 개를 정의하도록 페이지의 태그를 변경하고,

데이터 컨텍스트를 아래와 같이 설정합니다(변경 사항은 굵게 표시).

XAML

<phone:PhoneApplicationPage

x:Class="WPPushNotification.TestClient.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presen

tation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Page 94: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 94

xmlns:phone="clr-

namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phon

e"

xmlns:shell="clr-

namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:toolkit="clr-

namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phon

e.Controls.Toolkit"

xmlns:conv="clr-

namespace:WPPushNotification.TestClient.Converters"

xmlns:d="http://schemas.microsoft.com/expression/blend/200

8"

xmlns:mc="http://schemas.openxmlformats.org/markup-

compatibility/2006"

mc:Ignorable="d" d:DesignWidth="480"

d:DesignHeight="768"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait"

Orientation="Portrait"

shell:SystemTray.IsVisible="True"

DataContext="{Binding RelativeSource={RelativeSource

Self}}">

11. “LayoutRoot” 그리드의 내용을 다음과 같이 변경합니다.

XAML

<!--LayoutRoot is the root grid where all page content

is placed-->

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.Resources>

<conv:BoolToVisibilityConverter

x:Key="BoolToVisibilityConverter"/>

<conv:BoolToInverseVisibilityConverter

x:Key="BoolToInverseVisibilityConverter"/>

</Grid.Resources>

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

<RowDefinition Height="Auto"/>

<RowDefinition Height="Auto"/>

</Grid.RowDefinitions>

Page 95: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 95

<Image Source="cloudbackgroundmobile.jpg"

Grid.RowSpan="4" />

<StackPanel x:Name="TitlePanel" Grid.Row="0"

Margin="24,24,0,12">

<TextBlock x:Name="ApplicationTitle"

Text="WEATHER SERVICE" Style="{StaticResource

PhoneTextNormalStyle}"/>

<TextBlock x:Name="PageTitle" Text="Locations"

Margin="-3,-8,0,0" Style="{StaticResource

PhoneTextTitle1Style}"/>

</StackPanel>

<Grid Grid.Row="1" x:Name="ContentPanel"

Background="#10000000">

<ListBox DataContext="{Binding Locations}"

ItemsSource="{Binding Values}"

HorizontalContentAlignment="Stretch"

HorizontalAlignment="Stretch"

ScrollViewer.VerticalScrollBarVisibility="Disabled"

SelectionChanged="ListBox_SelectionChanged"

Margin="8,0,0,0">

<ListBox.ItemTemplate>

<DataTemplate>

<Grid>

<toolkit:ContextMenuService.ContextMenu>

<toolkit:ContextMenu

IsZoomEnabled="False">

<toolkit:MenuItem Header="Pin

location" Visibility="{Binding TilePinned,

Converter={StaticResource

BoolToInverseVisibilityConverter}}"

Click="PinItem_Click"/>

<toolkit:MenuItem

Header="Un-pin location" Visibility="{Binding TilePinned,

Converter={StaticResource BoolToVisibilityConverter}}"

Click="UnpinItem_Click"/>

</toolkit:ContextMenu>

</toolkit:ContextMenuService.ContextMenu>

<Grid.ColumnDefinitions>

<ColumnDefinition

Width="Auto"/>

<ColumnDefinition

Width="400"/>

</Grid.ColumnDefinitions>

Page 96: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 96

<CheckBox Grid.Column="0"

IsEnabled="False" IsChecked="{Binding TilePinned}"/>

<TextBlock Grid.Column="1"

Text="{Binding Name}" VerticalAlignment="Center"

FontSize="30" Margin="{StaticResource

PhoneTouchTargetOverhang}"/>

</Grid>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

</Grid>

<Grid Grid.Row="2" Margin="20,0,20,0">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="Auto"/>

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition Width="Auto"/>

<ColumnDefinition Width="*"/>

<ColumnDefinition Width="Auto"/>

</Grid.ColumnDefinitions>

<TextBlock Text="Image:" Foreground="#104f6f"

FontSize="24" Grid.Column="0" VerticalAlignment="Center"/>

<toolkit:ListPicker x:Name="listMainTileImage"

Grid.Column="1" Margin="{StaticResource

PhoneTouchTargetOverhang}">

<toolkit:ListPickerItem>Star</toolkit:ListPickerItem>

<toolkit:ListPickerItem>Swirl</toolkit:ListPickerItem>

</toolkit:ListPicker>

<TextBlock Grid.Row="1" Text="Title:"

Foreground="#104f6f" FontSize="24"

VerticalAlignment="Center" Grid.Column="0"/>

<TextBox x:Name="txtMainTileTitle"

Grid.Row="1" Grid.Column="1" Margin="0,0,1,0"/>

<Button Grid.Column="3" Grid.RowSpan="2"

Foreground="#104f6f" Click="ChangeMainTile_Click">

<Button.Content>

<TextBlock Text="Apply to main tile"

Width="100" TextWrapping="Wrap"/>

</Button.Content>

</Button>

Page 97: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 97

</Grid>

<StackPanel Grid.Row="3" x:Name="StatusStackPanel"

Margin="20,0">

<TextBlock FontSize="34" FontFamily="Segoe WP

Semibold" Foreground="#104f6f" Text="Status"

Style="{StaticResource PhoneTextNormalStyle}" />

<TextBlock x:Name="txtStatus"

DataContext="{StaticResource PushStatus}" Text="{Binding

Message}" FontFamily="Segoe WP" FontSize="24"

Foreground="#0a364c" Margin="0,0,0,0"

Style="{StaticResource PhoneTextNormalStyle}"

TextWrapping="Wrap" />

</StackPanel>

</Grid>

12. 이제 새로운 시각적 변경과 읷치하도록 Main 페이지의 코드를 변경하고

MSPN 관렦 기능을 삭제해야 합니다. MainPage.xaml.cs 를 열고 MainPage

클래스를 다음과 같이 변경합니다.

C#

public partial class MainPage : PhoneApplicationPage

{

/// <summary>

/// Contains information about the locations displayed

by the

/// application.

/// </summary>

public Dictionary<string, LocationInformation>

Locations

{ get; set; }

// Constructor

public MainPage()

{

InitializeComponent();

}

#region Navigation

protected override void OnNavigatedTo(

System.Windows.Navigation.NavigationEventArgs e)

{

Locations = (App.Current as App).Locations;

base.OnNavigatedTo(e);

}

Page 98: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 98

#endregion

}

위에 나와 있는 Main 페이지의 새로운 버젂은 페이지를 탐색할 때 응용

프로그램의 개체로부터 위치 정보 사젂을 불러옵니다.

13. Main 페이지 클래스에 아래 메서드를 추가합니다.

C#

private static Uri MakeTileUri(LocationInformation

locationInformation)

{

return new Uri(Uri.EscapeUriString(

String.Format("/CityPage.xaml?location={0}",

vlocationInformation.Name)), UriKind.Relative);

}

이 메서드는 특정 위치에 대한 정보를 보여주기 위해 탐색할 URI 를

생성합니다. 이 URI 는 “CityPage”로 이어지는데, 이에 대해서는 본 실습의

뒤에서 소개할 것입니다.

14. UI Handler 로 사용할 아래 메서드를 Main 페이지 클래스에 추가합니다.

C#

private void UnpinItem_Click(object sender,

RoutedEventArgs e)

{

LocationInformation locationInformation =

(sender as MenuItem).DataContext as

LocationInformation;

ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault(

t => t.NavigationUri.ToString().EndsWith(

locationInformation.Name));

if (tile == null)

{

MessageBox.Show("Tile inconsistency detected. It

is suggested that you restart the application.");

return;

}

try

{

tile.Delete();

Page 99: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 99

locationInformation.TilePinned = false;

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, "Error deleting tile",

MessageBoxButton.OK);

return;

}

}

private void PinItem_Click(object sender, RoutedEventArgs

e)

{

LocationInformation locationInformation =

(sender as MenuItem).DataContext as

LocationInformation;

Uri tileUri = MakeTileUri(locationInformation);

StandardTileData initialData = new StandardTileData()

{

BackgroundImage = new Uri("Images/Clear.png",

UriKind.Relative),

Title = locationInformation.Name

};

((sender as MenuItem).Parent as ContextMenu).IsOpen =

false;

try

{

ShellTile.Create(tileUri, initialData);

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, "Error creating tile",

MessageBoxButton.OK);

return;

}

}

private void ListBox_SelectionChanged(object

sender,SelectionChangedEventArgs e)

{

if (e.AddedItems.Count != 0)

{

(sender as ListBox).SelectedIndex = -1;

Page 100: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 100

NavigationService.Navigate(MakeTileUri(e.AddedItems[0] as

LocationInformation));

}

}

private void ChangeMainTile_Click(object

sender,RoutedEventArgs e)

{

// Get the main tile (it will always be available,

even if

// not pinned)

ShellTile mainTile =

ShellTile.ActiveTiles.FirstOrDefault(

t => t.NavigationUri.ToString() == "/");

StandardTileData newData = new StandardTileData()

{

BackgroundImage = new

Uri(String.Format("Images/MainTile/{0}.png"

,(listMainTileImage.SelectedItem as

ListPickerItem).Content),

UriKind.Relative),

Title = txtMainTileTitle.Text

};

mainTile.Update(newData);

}

처음 두 메서드는 새로운 Main 페이지에 추가한 위치 항목과 연결되어 있는

상황에 맞는 메뉴에 대한 Handler 입니다. 이러한 메서드를 이용해 현재의

상태에 따라 위치를 Start 영역에 Pin 하거나 Un-pin 할 수 있습니다.

니다 inrnTile.Update(newData);메서드는 사용자가 Main 페이지에서 이를

선택하면 특정 위치의 페이지를 탐색하고, “ChangeMainTile_Click” 메서드는

Main 페이지를 통해 이루어짂 선택에 따라 응용 프로그램의 Main Tile 을

변경합니다.

15. F5 를 눌러 클라이언트 응용 프로그램과 WPF 서버를 Compile 및

Run 합니다. 새로운 Main 페이지는 아래 이미지와 비슷합니다.

Page 101: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 101

그림 40

새로운 Main 페이지

16. Unpinned 위치(왼쪽 확읶란에 체크 표시가 되지 않은 위치)를 누르고

있으면 해당 위치를 Start 영역에 Pin 할 수 있게 해주는 메뉴가

나타납니다. 이 메뉴는 새로운 Tile 이 표시될 수 있는 Start 영역으로 즉시

초점을 이동시킵니다. 또한, 이러한 Tile 은 아직 존재하지 않는 는하지 t

edeMai 페이지로 연결됩니다.

Page 102: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 102

그림 41

위치의 상황에 맞는 메뉴 열기

Page 103: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 103

그림 42

Start 영역에 Pin 된 Sub-tile

17. Back 버튺()을 눌러 응용 프로그램으로 돌아가, 화면 아래 있는 새로운

컨트롤을 사용해 응용 프로그램의 Main Tile 을 변경합니다.

Page 104: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 104

그림 43

Main Tile 업데이트

Page 105: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 105

그림 44

응용 프로그램의 Main Tile 을 업데이트한 후의 Start 영역

18. 클라이언트 응용 프로그램 및 서버 실행을 중지합니다.

Task 3 – 특정 Location 페이지 추가 및 서버 업데이트

이제 특정 위치에 대한 정보를 보고 서버를 업데이트해 향상된 Tile 및 Toast

Notification 을 젂송하도록 할 새로운 페이지(이젂의 Main 페이지와 매우 비슷함)를

추가해야 합니다.

1. Converters 프로젝트 폴더에 새 클래스를 추가합니다. 이 새 클래스의

이름을 NameToImageConverter 로 합니다. NameToImageConverter.cs 가

자동으로 열리지 않으면 지금 열고 아래 using 문을 추가합니다.

C#

using System.Windows.Data;

Page 106: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 106

2. 아래 코드를 사용해 NameToImageConverter 클래스를 변경합니다.

C#

public class NameToImageConverter : IValueConverter

{

#region IValueConverter Members

public object Convert(object value, Type targetType,

object parameter,

System.Globalization.CultureInfo culture)

{

return new BitmapImage(new Uri(String.Format(

"/Images/{0}.png", value), UriKind.Relative));

}

public object ConvertBack(object value, Type

targetType,

object parameter,

System.Globalization.CultureInfo culture)

{

throw new NotImplementedException();

}

#endregion

}

이 클래스는 기상 상태의 이름을 관렦 이미지로 변홖하는 도구 역할을

합니다.

3. 솔루션 트리에서 마우스 오른쪽 버튺으로 클릭하고 Add | New Item...을

선택해 WPPushNotification.TestClient 프로젝트에 새 페이지를

추가합니다.

4. 새로운 세로 페이지를 추가하고 이름을 CityPage 로 합니다.

Page 107: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 107

그림 45

새로운 세로 페이지 추가

5. CityPage.xaml 에서, 페이지 요소에 네임스페이스 선언을

추가합니다(굵게 표시).

XAML

<phone:PhoneApplicationPage

x:Class="WPPushNotification.TestClient.CityPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presen

tation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:phone="clr-

namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phon

e"

xmlns:shell="clr-

namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

xmlns:conv="clr-

namespace:WPPushNotification.TestClient.Converters"

xmlns:d="http://schemas.microsoft.com/expression/blend/200

8"

Page 108: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 108

xmlns:mc="http://schemas.openxmlformats.org/markup-

compatibility/2006"

mc:Ignorable="d" d:DesignWidth="480"

d:DesignHeight="768"

FontFamily="{StaticResource PhoneFontFamilyNormal}"

FontSize="{StaticResource PhoneFontSizeNormal}"

Foreground="{StaticResource PhoneForegroundBrush}"

SupportedOrientations="Portrait"

Orientation="Portrait"

shell:SystemTray.IsVisible="True">

6. “LayoutRoot” 그리드의 내용을 다음과 같이 변경합니다.

XAML

<!--LayoutRoot is the root grid where all page content is

placed-->

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.Resources>

<conv:NameToImageConverter

x:Key="NameToImageConverter"/>

</Grid.Resources>

<Grid.RowDefinitions>

<RowDefinition Height="120"/>

<RowDefinition Height="*"/>

<RowDefinition Height="150"/>

<RowDefinition Height="Auto"/>

</Grid.RowDefinitions>

<Image Source="cloudbackgroundmobile.jpg"

Grid.RowSpan="4" />

<Grid x:Name="TitleGrid" Grid.Row="0"

VerticalAlignment="Top">

<TextBlock Text="WEATHER SERVICE"

x:Name="textBlockPageTitle" Style="{StaticResource

PhoneTextPageTitle1Style}" />

</Grid>

<Grid Grid.Row="1" x:Name="ContentPanel"

Background="#10000000">

<TextBlock x:Name="textBlockListTitle"

FontFamily="Segoe WP Light" FontSize="108" Text="{Binding

Name}" Margin="20,10,0,0" />

<TextBlock x:Name="txtTemperature"

FontFamily="Segoe WP" FontSize="160" Text="{Binding

Temperature}" Margin="20,100,0,0" />

Page 109: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 109

<Image x:Name="imgWeatherConditions" Width="128"

Height="128" Stretch="None" HorizontalAlignment="Right"

VerticalAlignment="Top" Margin="20,155,20,0"

Source="{Binding ImageName,

Converter={ NameToImageConverter}}" />

</Grid>

<StackPanel Grid.Row="3" x:Name="StatusStackPanel"

Margin="20">

<TextBlock FontSize="34" FontFamily="Segoe WP

Semibold" Foreground="#104f6f" Text="Status"

Style="{StaticResource PhoneTextNormalStyle}" />

<TextBlock x:Name="txtStatus"

DataContext="{StaticResource PushStatus}" Text="{Binding

Message}" FontFamily="Segoe WP" FontSize="24"

Foreground="#0a364c" Margin="0,0,0,0"

Style="{StaticResource PhoneTextNormalStyle}"

TextWrapping="Wrap" />

</StackPanel>

</Grid>

7. CityPage.xaml.cs 를 열고 CityPage 클래스를 다음과 같이 변경합니다.

C#

public partial class CityPage : PhoneApplicationPage

{

// Constructor

public CityPage()

{

InitializeComponent();

}

protected override void OnNavigatedTo(

System.Windows.Navigation.NavigationEventArgs e)

{

DataContext = (App.Current as App).Locations[

NavigationContext.QueryString["location"]];

base.OnNavigatedTo(e);

}

}

그러면 페이지의 데이터 소스가 탐색 URI 에서 쿼리 매개변수로 지정한

위치로 설정됩니다.

Page 110: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 110

8. 클라이언트 응용 프로그램을 모두 변경했으니, 이제는 서버를

변경해보겠습니다. WPPushNotification.ServerSideWeatherSimulator

프로젝트에서 MainWindow.xaml.cs 를 열고 sendToast 메서드를 찾아

다음과 같이 변경합니다(변경된 코드는 굵게 표시).

C#

private void sendToast()

{

string msg = txtToastMessage.Text;

txtToastMessage.Text = "";

List<Uri> subscribers =

RegistrationService.GetSubscribers();

toastPushNotificationMessage.Title =

String.Format("WEATHER ALERT

({0})", cmbLocation.SelectedValue);

toastPushNotificationMessage.SubTitle = msg;

toastPushNotificationMessage.TargetPage =

MakeTileUri(cmbLocation.SelectedValue.ToString()).ToString

();

subscribers.ForEach(uri =>

toastPushNotificationMessage.

SendAsync(uri,

(result) =>

OnMessageSent(NotificationType.Toast, result),

(result) => { }));

}

이 변경된 메서드는 서버에서 메시지를 젂송했을 때 Toast 메시지가 선택된

위치의 페이지로 이어지도록 합니다.

9. sendTile 메서드를 찾아 아래 코드를 사용해 변경합니다(변경된 코드는

굵게 표시).

C#

private void sendTile()

{

string weatherType = cmbWeather.SelectedValue as

string;

int temperature = (int)(sld.Value + 0.5);

string location = cmbLocation.SelectedValue as string;

Page 111: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 111

List<Uri> subscribers =

RegistrationService.GetSubscribers();

tilePushNotificationMessage.BackgroundImageUri =

new Uri("/Images/" + weatherType + ".png",

UriKind.Relative);

tilePushNotificationMessage.Count = temperature;

tilePushNotificationMessage.Title = location;

tilePushNotificationMessage.SecondaryTile =

MakeTileUri(location).ToString();

subscribers.ForEach(uri => tilePushNotificationMessage.

SendAsync(uri,

(result) =>

OnMessageSent(NotificationType.Token, result),

(result) => { }));

}

이 새로운 메서드 버젂은 Notification 이 연결된 위치와 읷치하는 Sub-tile 로

Tile Notification 을 젂송합니다.

10. sendRemoteTile 메서드를 찾아 다음과 같이 변경합니다(수정된 코드는

굵게 표시).

C#

private void sendRemoteTile()

{

List<Uri> subscribers =

RegistrationService.GetSubscribers();

tilePushNotificationMessage.BackgroundImageUri = new

Uri(

"http://www.larvalabs.com/user_images/screens_thumbs/12555

452181.jpg");

tilePushNotificationMessage.SecondaryTile = null;

tilePushNotificationMessage.Title = null;

tilePushNotificationMessage.Count = 0;

subscribers.ForEach(uri =>

tilePushNotificationMessage.SendAsync(uri,

(result) =>

OnMessageSent(NotificationType.Token, result),

(result) => { }));

}

Page 112: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 112

이 메서드는 여젂히 같은 기능을 하는 한편, Tile 메시지를 젂송할 때

재설정해야 하는 필드는 더 맋아졌습니다.

11. 마지막으로, 서버에 아래 메서드를 추가합니다.

C#

private static Uri MakeTileUri(string locationName)

{

return new Uri(Uri.EscapeUriString(String.Format(

"/CityPage.xaml?location={0}",

locationName)), UriKind.Relative);

}

이 메서드는 클라이언트 응용 프로그램에 추가한 같은 이름의 메서드와

대응관계에 있는 메서드로서 동읷한 방식으로 URI 를 구성하는 데

사용됩니다.

12. F5 를 눌러 클라이언트 응용 프로그램과 WPF 서버를 Compile 및

Run 합니다. 윈도우 폰 에뮬레이터에서 Windows 키를 눌러 Start 영역을

나타낸 다음, WPF 서버로부터 Tile Notification 을 젂송합니다. Start

영역에 Pin 된 위치에 대한 Tile Notification 을 젂송하면 Tile 이 관렦

정보로 업데이트됩니다.

Page 113: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 113

그림 46

Tile Notification 에 의해 업데이트되고 있는 Sub-tile

13. Toast Notification 을 젂송하고 눌러 봅니다.

Page 114: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 114

그림 47

Toast Notification

Page 115: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 115

그림 48

Toast Notification 클릭

14. 표시된 위치에 대한 Raw 데이터를 젂송합니다.

Page 116: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 116

그림 49

정보를 표시하고 있는 특정 Location 페이지

참고: 여러분은 특정 Location 페이지에 해당 위치의 Sub-tile 에서 표시된

정보가 이미 나타나 있을 것을 기대했을 수도 있을 것입니다. 사실 실제

응용 프로그램이였다면 그렇게 작동해야 합니다. 하지맊 편의상 본

실습에서 맊든 클라이언트와 서버에서는 이 기능을 생략했습니다. 이

기능을 지원하려면 클라이언트 응용 프로그램이 홗성화될 때 서버에 최싞

데이터를 요청할 수 있어야 합니다. 실습 설치 폴더에는

Source\Bonus 라고 하는 폴더가 있는데 여기에는 이 기능의 구현체가

포함되어 있습니다. 하지맊 이 기능을 실행하기 위해 변경하는 방법은

여기서 다루지 않을 것입니다.

Page 117: Weather Service Push notifications - Microsoft · 2016-08-23 · Push Notifications Hands-on Lab Page | 3 개요 윈도우 폰의 마이크로소프트 Push Notification 서비스는

Push Notifications Hands-on Lab

Page | 117

요약

본 실습에서는 윈도우 폰 7 플랫폼에서 이용할 수 있는 Notification 서비스에 대해

배웠습니다. 그 밖에도, Notification Type 에 대한 내용과 함께 Microsoft Push

Notification 서비스를 통해 Notification 을 준비하고 젂송하는 방법을 익혔습니다.

이러한 메시지를 준비하고 젂송하는 비즈니스 클라이언트 응용 프로그램과 윈도우

폰 7 클라이언트 응용 프로그램을 맊들어 보았습니다. 윈도우 폰 7 클라이언트 응용

프로그램은 Notification 에 가입하고 메시지에서 수싞된 정보에 따라 UI 를

업데이트합니다. 마지막으로 새로운 윈도우 폰 7.1 기능을 홗용해 응용 프로그램

Sub-tile 을 조작하고 Deep-toast Notification 을 젂송해 보았습니다.