Я добился успеха с Push Notification в Windows Phone 8.1/Windows Apps (Universal Apps). Я реализовал отправку push-уведомлений на устройства из нашей собственной веб-службы.
Шаг 1. Получите Client Secret и SID пакета на сайте dev.windows.com >> Services >> Live Services. Они понадобятся вам позже в веб-службе.
Шаг 2. В приложении для Windows вы должны связать свое приложение с Магазином. Для этого щелкните правой кнопкой мыши проект >> Магазин >> Связать приложение с Магазином. Войдите в свою учетную запись Dev и свяжите свое приложение. ![Связывание вашего приложения с Магазином](https://i.stack.imgur.com/hlvxa.png)
Шаг 3. Вам понадобится Uri канала. В MainPage.xaml добавьте кнопку и текстовый блок, чтобы получить Uri канала. Код XAML выглядит так:
<Page
x:Class="FinalPushNotificationTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:FinalPushNotificationTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Push Notification" Margin="20,48,10,0" Style="{StaticResource HeaderTextBlockStyle}" TextWrapping="Wrap" />
<ScrollViewer Grid.Row="1" Margin="20,10,10,0">
<StackPanel x:Name="resultsPanel">
<Button x:Name="PushChannelBtn" Content="Get Channel Uri" Click="PushChannelBtn_Click" />
<ProgressBar x:Name="ChannelProgress" IsIndeterminate="False" Visibility="Collapsed" />
<TextBlock x:Name="ChannelText" FontSize="22" />
</StackPanel>
</ScrollViewer>
</Grid>
Step 4:
In the MainPage.xaml.cs page, Add the following code snippet i.e. for the Button Click Event. When you run your app, you'll get the Channel Uri in the Console Window. Note down this Channel Uri, you'll need that in Web Service.
private async void PushChannelBtn_Click(object sender, RoutedEventArgs e)
{
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
ChannelText.Text = channel.Uri.ToString();
Debug.WriteLine(channel.Uri);
}
![URI канала](https://i.stack.imgur.com/EAd56.png)
Шаг 5. Теперь вам нужна веб-служба для отправки push-уведомлений на ваше устройство. Для этого щелкните правой кнопкой мыши свой проект в обозревателе решений. Добавить >> Новый проект >> Visual C# >> Интернет >> Веб-приложение ASP.NET. Нажмите «ОК», в шаблоне выберите «Пустой». После этого добавьте новую веб-форму в свое веб-приложение. Назовите его SendToast. ![Добавление нового веб-проекта в ваш проект](https://i.stack.imgur.com/0zxAp.png)
![Добавление веб-формы в ваше веб-приложение](https://i.stack.imgur.com/qdj8p.png)
Шаг 6. Теперь в файле SendToast.aspx.cs вам необходимо реализовать методы и функции для получения маркера доступа с помощью SID пакета, клиента Секрет и канал Ури. Добавьте SID пакета, Cleint Secret и Channel Uriin в соответствующие места. Полный код выглядит следующим образом:
using Microsoft.ServiceBus.Notifications;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SendToast
{
public partial class SendToast : System.Web.UI.Page
{
private string sid = "Your Package SID";
private string secret = "Your Client Secret";
private string accessToken = "";
[DataContract]
public class OAuthToken
{
[DataMember(Name = "access_token")]
public string AccessToken { get; set; }
[DataMember(Name = "token_type")]
public string TokenType { get; set; }
}
OAuthToken GetOAuthTokenFromJson(string jsonString)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
var ser = new DataContractJsonSerializer(typeof(OAuthToken));
var oAuthToken = (OAuthToken)ser.ReadObject(ms);
return oAuthToken;
}
}
public void getAccessToken()
{
var urlEncodedSid = HttpUtility.UrlEncode(String.Format("{0}", this.sid));
var urlEncodedSecret = HttpUtility.UrlEncode(this.secret);
var body =
String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", urlEncodedSid, urlEncodedSecret);
var client = new WebClient();
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string response = client.UploadString("https://login.live.com/accesstoken.srf", body);
var oAuthToken = GetOAuthTokenFromJson(response);
this.accessToken = oAuthToken.AccessToken;
}
protected string PostToCloud(string uri, string xml, string type = "wns/toast")
{
try
{
if (accessToken == "")
{
getAccessToken();
}
byte[] contentInBytes = Encoding.UTF8.GetBytes(xml);
WebRequest webRequest = HttpWebRequest.Create(uri);
HttpWebRequest request = webRequest as HttpWebRequest;
webRequest.Method = "POST";
webRequest.Headers.Add("X-WNS-Type", type);
webRequest.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(contentInBytes, 0, contentInBytes.Length);
requestStream.Close();
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
return webResponse.StatusCode.ToString();
}
catch (WebException webException)
{
string exceptionDetails = webException.Response.Headers["WWW-Authenticate"];
if ((exceptionDetails != null) && exceptionDetails.Contains("Token expired"))
{
getAccessToken();
return PostToCloud(uri, xml, type);
}
else
{
return "EXCEPTION: " + webException.Message;
}
}
catch (Exception ex)
{
return "EXCEPTION: " + ex.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
string channelUri = "Your Channel Uri";
if (Application["channelUri"] != null)
{
Application["channelUri"] = channelUri;
}
else
{
Application.Add("channelUri", channelUri);
}
if (Application["channelUri"] != null)
{
string aStrReq = Application["channelUri"] as string;
string toast1 = "<?xml version=\"1.0\" encoding=\"utf-8\"?> ";
string toast2 = @"<toast>
<visual>
<binding template=""ToastText01"">
<text id=""1"">Hello Push Notification!!</text>
</binding>
</visual>
</toast>";
string xml = toast1 + toast2;
Response.Write("Result: " + PostToCloud(aStrReq, xml));
}
else
{
Response.Write("Application 'channelUri=' has not been set yet");
}
Response.End();
}
}
}
Запустите свое веб-приложение, вы получите ответ Результат OK, если оно успешно отправит push-уведомление.
Дайте мне знать, если вам нужен рабочий образец проекта. Надеюсь это поможет. Спасибо!
person
Kishor Bikram Oli
schedule
12.07.2015