Configuring WNS service for Windows 8 phone gets error after adding <Identity> tag

I am setting up Windows phone 8.1 push notification using urbanairship. I have a SID and a secret key for my application. But when I do the next step mentioned in dev.windows WNS -> Live Service Site:

To manually set the App ID values, open the AppManifest.xml in a text editor and set these attributes on the element using the values ​​shown here.

my application stops working. anyone give me steps to set up WNS in Windows Phone 8.1 then it helps me a lot, I spend a week on it and am really frustrating right now.

0


source to share


1 answer


I had success with Push Notification on Windows Phone 8.1 / Windows Apps (Universal Apps). I've implemented Push Notification transmission to devices from our own web service.

Step 1 . Get Client Secret and SID Package from dev.windows.com → Services → Live Services. You will need this information later in the web service.

Step 2 . In a Windows app, you need to link the app to the Store. To do this, right-click on the project -> Store -> Link Application to Store. Login to your Dev account and link the app. Associating your app with the Store

Step 3 You need the Uri channel. In MainPage.xaml add a button and a text block to get your Uri channel. The XAML looks like this:

<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 : On the MainPage.xaml.cs page, add the following piece of code, for example, for the Click Button event. When you run the application, you will get the Channel Uri in the console window. Record this Uri feed, you need it in the 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);
    }

      

Channel uri

Step 5: You now need a web service to send push notification to your device. To do this, right click on your project in the Solution Explorer. Add -> New Project -> Visual C # -> Web -> ASP.NET Web Application. Click "OK", "In step" select "Empty". After that add a new web forminto the web application. Name it SendToast . Adding a new Web project to your projectSelecting Empty Template for your Web ProjectAdding Web Form in your Web Application

Step 6: Now in SendToast.aspx.cs you need to implement the methods and functions to get the access token using the package SID, Client Secret and Channel Uri. Add your SID, Cleint Secret and Channel Uriin package to their respective locations. The complete code looks like this:

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

      

Run the web app, you will get a response Result OK if it sends the push notification successfully.

Let me know if you need a working sample project. Hope this helps. Thank!

+1


source







All Articles