Azure的通知枢纽标签没有创造,也不更新 - 针对特定的用户 [英] Azure notification hub tags not creating nor updating - to target specific user

查看:277
本文介绍了Azure的通知枢纽标签没有创造,也不更新 - 针对特定的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页API工作作为后端服务,而我使用的Azure通知中心。我需要根据条件的商业逻辑在用户通知记录的,总之目标特定用户。我提取code <一个href=\"https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-aspnet-backend-windows-dotnet-notify-users/\"相对=nofollow>这个文章。一切工作正常,但标签也没有创造,也不更新即可。我需要帮助。这里是我的code段

  //它返回registrationId
公共异步任务&LT; OperationResult&LT;串GT;&GT; GetRegistrationIdAsync(字符串句柄)
{
      ........
}//实际设备注册和标签更新
公共异步任务&LT; OperationResult&LT; RegistrationOutput&GT;&GT; RegisterDeviceAsync(用户名字符串,字符串registrationId,平台平台,字符串处理)
{
      ...........
registration.Tags.Add(的String.Format(用户名:{0},用户名)); //这个标签没有创造
等待_hub.CreateOrUpdateRegistrationAsync(注册);
      ...........
}//发送通知 - 目标特定用户
公共异步任务&LT; OperationResult&LT;布尔&GT;&GT;发送(平台平台,用户名字符串,INotificationMessage消息)
{
      ...........
}


解决方案

下面是的完整的工作实施。根据你的需要修改

 公共类MyAzureNotificationHubManager
{
    私人Microsoft.ServiceBus.Notifications.NotificationHubClient _hub;    公共MyAzureNotificationHubManager()
    {
        _hub = MyAzureNotificationClient.Instance.Hub;
    }    私人常量字符串TAGFORMAT =用户名:{0};    公共异步任务&LT;串GT; GetRegistrationIdAsync(字符串句柄)
    {        如果(string.IsNullOrEmpty(句柄))
            抛出新的ArgumentNullException(处理不能为空或为空);        //这是科目编号 - 使统一格式处理,否则可能有一些问题。
        处理= handle.ToUpper();        字符串newRegistrationId = NULL;        //确保有此推柄(用于iOS和Android)没有现有注册
        VAR注册=等待_hub.GetRegistrationsByChannelAsync(手柄,100);
        的foreach(在登记注册RegistrationDescription)
        {
            如果(newRegistrationId == NULL)
            {
                newRegistrationId = registration.RegistrationId;
            }
            其他
            {
                等待_hub.DeleteRegistrationAsync(注册);
            }
        }
        如果(newRegistrationId == NULL)
            newRegistrationId =等待_hub.CreateRegistrationIdAsync();
        返回newRegistrationId;
    }    公共异步任务UnRegisterDeviceAsync(字符串句柄)
    {
        如果(string.IsNullOrEmpty(句柄))
            抛出新的ArgumentNullException(处理不能为空或为空);
        //这是科目编号 - 使统一格式处理,否则可能有一些问题。
        处理= handle.ToUpper();
        //通过手柄删除所有登记
        VAR注册=等待_hub.GetRegistrationsByChannelAsync(手柄,100);
        的foreach(在登记注册RegistrationDescription)
        {
            等待_hub.DeleteRegistrationAsync(注册);
        }
    }    公共异步任务RegisterDeviceAsync(用户名字符串,字符串registrationId,平台平台,字符串处理)
    {        如果(string.IsNullOrEmpty(句柄))
            抛出新的ArgumentNullException(处理不能为空或为空);        //这是科目编号 - 使统一格式处理,否则可能有一些问题。
        处理= handle.ToUpper();        RegistrationDescription注册= NULL;
        开关(平台)
        {
            案例Platforms.MPNS:
                注册=新MpnsRegistrationDescription(句柄);
                打破;
            案例Platforms.WNS:
                注册=新WindowsRegistrationDescription(句柄);
                打破;
            案例Platforms.APNS:
                注册=新AppleRegistrationDescription(句柄);
                打破;
            案例Platforms.GCM:
                注册=新GcmRegistrationDescription(句柄);
                打破;
            默认:
                抛出新的ArgumentException(无效的设备平台,它应该是'MPNS','WNS','APNS或GCM中的一个。);
        }        registration.RegistrationId = registrationId;
        //如果用户被允许添加这些标记添加检查
        registration.Tags =新的HashSet&LT;串GT;();
        registration.Tags.Add(的String.Format(TAGFORMAT,用户名));        //收集最终注册
        VAR的结果=等待_hub.CreateOrUpdateRegistrationAsync(注册);
        无功输出=新RegistrationOutput()
        {
            平台=平台,
            手柄=手柄,
            ExpirationTime = result.ExpirationTime,
            RegistrationId = result.RegistrationId
        };
        如果(result.Tags!= NULL)
        {
            output.Tags = result.Tags.ToList();
        }
    }    公共异步任务&LT;布尔&GT;发送(平台平台,串receiverUserName,INotificationMessage消息)
    {        字符串[] =标签新[] {的String.Format(TAGFORMAT,receiverUserName)};        NotificationOutcome结果= NULL;
        开关(平台)
        {
            // Windows 8.1中/的Windows Phone 8.1
            案例Platforms.WNS:
                结果=等待_hub.SendWindowsNativeNotificationAsync(message.GetWindowsMessage(),标签);
                打破;
            案例Platforms.APNS:
                结果=等待_hub.SendAppleNativeNotificationAsync(message.GetAppleMessage(),标签);
                打破;
            案例Platforms.GCM:
                结果=等待_hub.SendGcmNativeNotificationAsync(message.GetAndroidMessage(),标签);
                打破;
        }        如果(结果!= NULL)
        {
            如果(!((outcome.State == NotificationOutcomeState.Abandoned)||(outcome.State == NotificationOutcomeState.Unknown)))
            {
                返回true;
            }
        }        返回false;
    }}公共类MyAzureNotificationClient
{
    //锁定同步对象
    私人静态对象SYNCLOCK =新的对象();
    私有静态MyAzureNotificationClient _instance {搞定;组; }    //辛格尔顿inistance
    公共静态MyAzureNotificationClient实例
    {
        得到
        {
            如果(_instance == NULL)
            {
                锁定(SYNCLOCK)
                {
                    如果(_instance == NULL)
                    {
                        _instance =新MyAzureNotificationClient();
                    }
                }
            }
            返回_instance;
        }
    }    公共NotificationHubClient中心{搞定;私人集; }    私人MyAzureNotificationClient()
    {
        集线器= Microsoft.ServiceBus.Notifications.NotificationHubClient.CreateClientFromConnectionString(&LT;充分获得通知的连接字符串&gt;中,&LT;通知中心名称&gt;);
    }
}公共接口INotificationMessage
{
   串GetAppleMessage();
   串GetAndroidMessage();
   串GetWindowsMessage();} 公共类SampleMessage:INotificationMessage
{
    公共字符串消息{搞定;组; }
    公共字符串GetAndroidMessage()
    {
        VAR notif = JsonObject.Create()
             .AddProperty(数据,数据= GT;
             {
                 data.AddProperty(信息,this.Message);
             });
        返回notif.ToJson();
    }    公共字符串GetAppleMessage()
    {
        //参见 - https://github.com/paultyng/FluentJson.NET
        VAR警报= JsonObject.Create()
             .AddProperty(APS,APS =&GT;
             {
                 aps.AddProperty(警报,this.Message?您的资料);
             });
        返回alert.ToJson();
    }    公共字符串GetWindowsMessage()
    {
        //参见 - http://improve.dk/xmldocument-fluent-interface/
        VAR味精=新的XmlObject()
                    .XmlDeclaration()
                    .Node(土司)。在()
                        .Node(视觉)。在()
                            .Node(绑定)。属性(模板,ToastText01)。在()
                                .Node(文本)的InnerText(消息在这里);
        返回msg.GetOuterXml();
    }
}

Hi I am working on web api as back-end service where I am using Azure notification hub. I need to notify logged in user according to conditional business logic, in short target specific user. I extract code from this article. Everything works fine but tags is not creating nor updating. I need help. Here is my code snippet

// It returns registrationId
public async Task<OperationResult<string>> GetRegistrationIdAsync(string handle)
{
      ........
}

// actual device registration and tag update 
public async Task<OperationResult<RegistrationOutput>> RegisterDeviceAsync(string userName, string registrationId, Platforms platform, string handle)
{
      ...........
registration.Tags.Add(string.Format("username : {0}", userName)); // THIS TAG IS NOT CREATING
await _hub.CreateOrUpdateRegistrationAsync(registration);
      ...........
}

// Send notification - target specific user
public async Task<OperationResult<bool>> Send(Platforms platform, string userName, INotificationMessage message)
{
      ...........
}

解决方案

Here is complete working implementation. Modify according to your need

 public class MyAzureNotificationHubManager
{
    private Microsoft.ServiceBus.Notifications.NotificationHubClient _hub;

    public MyAzureNotificationHubManager()
    {
        _hub = MyAzureNotificationClient.Instance.Hub;
    }

    private const string TAGFORMAT = "username:{0}";

    public async Task<string> GetRegistrationIdAsync(string handle)
    {

        if (string.IsNullOrEmpty(handle))
            throw new ArgumentNullException("handle could not be empty or null");

        // This is requied - to make uniform handle format, otherwise could have some issue.  
        handle = handle.ToUpper();

        string newRegistrationId = null;

        // make sure there are no existing registrations for this push handle (used for iOS and Android)
        var registrations = await _hub.GetRegistrationsByChannelAsync(handle, 100);
        foreach (RegistrationDescription registration in registrations)
        {
            if (newRegistrationId == null)
            {
                newRegistrationId = registration.RegistrationId;
            }
            else
            {
                await _hub.DeleteRegistrationAsync(registration);
            }
        }


        if (newRegistrationId == null)
            newRegistrationId = await _hub.CreateRegistrationIdAsync();
        return newRegistrationId;
    }

    public async Task UnRegisterDeviceAsync(string handle)
    {
        if (string.IsNullOrEmpty(handle))
            throw new ArgumentNullException("handle could not be empty or null");
        // This is requied - to make uniform handle format, otherwise could have some issue.  
        handle = handle.ToUpper();
        // remove all registration by that handle
        var registrations = await _hub.GetRegistrationsByChannelAsync(handle, 100);
        foreach (RegistrationDescription registration in registrations)
        {
            await _hub.DeleteRegistrationAsync(registration);
        }
    }

    public async Task RegisterDeviceAsync(string userName, string registrationId, Platforms platform, string handle)
    {

        if (string.IsNullOrEmpty(handle))
            throw new ArgumentNullException("handle could not be empty or null");

        // This is requied - to make uniform handle format, otherwise could have some issue.  
        handle = handle.ToUpper();

        RegistrationDescription registration = null;
        switch (platform)
        {
            case Platforms.MPNS:
                registration = new MpnsRegistrationDescription(handle);
                break;
            case Platforms.WNS:
                registration = new WindowsRegistrationDescription(handle);
                break;
            case Platforms.APNS:
                registration = new AppleRegistrationDescription(handle);
                break;
            case Platforms.GCM:
                registration = new GcmRegistrationDescription(handle);
                break;
            default:
                throw new ArgumentException("Invalid device platform. It should be one of 'mpns', 'wns', 'apns' or 'gcm'");
        }

        registration.RegistrationId = registrationId;


        // add check if user is allowed to add these tags
        registration.Tags = new HashSet<string>();
        registration.Tags.Add(string.Format(TAGFORMAT, userName));

        // collect final registration 
        var result = await _hub.CreateOrUpdateRegistrationAsync(registration);
        var output = new RegistrationOutput()
        {
            Platform = platform,
            Handle = handle,
            ExpirationTime = result.ExpirationTime,
            RegistrationId = result.RegistrationId
        };
        if (result.Tags != null)
        {
            output.Tags = result.Tags.ToList();
        }


    }

    public async Task<bool> Send(Platforms platform, string receiverUserName, INotificationMessage message)
    {

        string[] tags = new[] { string.Format(TAGFORMAT, receiverUserName) };

        NotificationOutcome outcome = null;
        switch (platform)
        {
            // Windows 8.1 / Windows Phone 8.1
            case Platforms.WNS:
                outcome = await _hub.SendWindowsNativeNotificationAsync(message.GetWindowsMessage(), tags);
                break;
            case Platforms.APNS:
                outcome = await _hub.SendAppleNativeNotificationAsync(message.GetAppleMessage(), tags);
                break;
            case Platforms.GCM:
                outcome = await _hub.SendGcmNativeNotificationAsync(message.GetAndroidMessage(), tags);
                break;
        }

        if (outcome != null)
        {
            if (!((outcome.State == NotificationOutcomeState.Abandoned) || (outcome.State == NotificationOutcomeState.Unknown)))
            {
                return true;
            }
        }

        return false;
    }

}

public class MyAzureNotificationClient
{
    // Lock synchronization object
    private static object syncLock = new object();
    private static MyAzureNotificationClient _instance { get; set; }

    // Singleton inistance
    public static MyAzureNotificationClient Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (syncLock)
                {
                    if (_instance == null)
                    {
                        _instance = new MyAzureNotificationClient();
                    }
                }
            }
            return _instance;
        }
    }

    public NotificationHubClient Hub { get; private set; }

    private MyAzureNotificationClient()
    {
        Hub = Microsoft.ServiceBus.Notifications.NotificationHubClient.CreateClientFromConnectionString("<full access notification connection string>", "<notification hub name>");
    }
}

public interface INotificationMessage
{
   string GetAppleMessage();
   string GetAndroidMessage();
   string GetWindowsMessage();

}

 public class SampleMessage : INotificationMessage
{
    public string Message { get; set; }
    public string GetAndroidMessage()
    {
        var notif = JsonObject.Create()
             .AddProperty("data", data =>
             {
                 data.AddProperty("message", this.Message);
             });
        return notif.ToJson();
    }

    public string GetAppleMessage()
    {
        // Refer -  https://github.com/paultyng/FluentJson.NET
        var alert = JsonObject.Create()
             .AddProperty("aps", aps =>
             {
                 aps.AddProperty("alert", this.Message ?? "Your information");
             });


        return alert.ToJson();
    }

    public string GetWindowsMessage()
    {
        // Refer - http://improve.dk/xmldocument-fluent-interface/
        var msg = new XmlObject()
                    .XmlDeclaration()
                    .Node("toast").Within()
                        .Node("visual").Within()
                            .Node("binding").Attribute("template", "ToastText01").Within()
                                .Node("text").InnerText("Message here");
        return msg.GetOuterXml();
    }
}

这篇关于Azure的通知枢纽标签没有创造,也不更新 - 针对特定的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆