向特定用户或设备推送通知

时间:2018-10-30 23:22:35

标签: javascript push-notification notifications signalr sqldependency

我有一个WEB MVC 5系统,在其中我使用signalR和SqlDependency进行实时操作,但是我不需要实现的是在感兴趣的更改时向系统管理员推送通知。具体来说,我需要的是一种向特定用户发送推播通知的机制,即使没有连接,也就是即使他们没有使用系统,也可以向他们发送推播通知。

我搜索了很多东西,我正在使用push.js库,但这不允许我这样做或我认为是这样。

任何可以提供满足我的需求或类似要求的机制。

1 个答案:

答案 0 :(得分:1)

我编写了一个存储过程(SP),该存储过程根据用户返回事件详细信息。您可以创建一个表,该表保留要发送通知的ID,此表的每次插入都会通知用户。

我有三个表,分别是“用户”,“事件”和“用户事件”。 在UserEvents表中,有userID作为来自用户表的外键,还有eventID作为来自事件表的外键。在我的系统中,当事件插入到上面的表中时,signalR会执行其工作。 UserEvents表具有如下列:

   [Uev_ID]
  ,[Uev_UserID]
  ,[Uev_EventID]
  ,[Uev_IsRead]
  ,[Uev_ReadDate]
  ,[GuID]
  ,[Deleted]

我的事件模型如下:

    public class EventList
    {
    public Int64 EventID { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime Date { get; set; }
    public string Color { get; set; }
    }

应该有一个消息存储库与数据库和模型进行交互和通信。该存储库将处理dependency_OnChange方法。

    public class MessagesRepository
    {
    internal static SqlCommand command = null;
    internal static SqlCommand command2 = null;
    internal static SqlDependency dependency = null;
    internal static SqlDependency dependency2 = null;
    readonly string _connString = 
                  ConfigurationManager.ConnectionStrings["signalr"].ConnectionString;
    private Int64 user { get; set; }
    public MessagesRepository(Int64 userID)
    {
        user = userID;
    }

    public IEnumerable<EventList> GetAllMessages()
    {
        var messages = new List<EventList>();
        using (var connection = new SqlConnection(_connString))
        {
            connection.Open();
            using (command = new SqlCommand("[sp_SysEvent]", connection))
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@user", user);
                command.Notification = null;

                if (dependency == null)
                {
                    dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                }
                if (connection.State == ConnectionState.Closed)
                    connection.Open();

                var reader = command.ExecuteReader();

                while (reader.Read())
                {
                    messages.Add(item: new EventList { EventID = (Int64)reader["Evt_ID"], Description = (string)reader["Evt_Description"], Title = (string)reader["Evg_Title"], Date = (DateTime)reader["Evt_Date"], Color = (string)reader["Clr_Color"] });
                }
            }
        }
        return messages;
    }

    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (dependency != null)
        {
            dependency.OnChange -= dependency_OnChange;
            dependency = null;
        }
        if (e.Info == SqlNotificationInfo.Insert)
        {

            TestHub.SendUser(user);
        }
    }
}

我需要一个“连接映射”文档,用于将通知发送给已连接的用户。当用户连接时,我将其ID放在HashSet中,并在用户断开连接时从HashSet中删除。您可以使用它来检测连接了哪个用户。 这是连接映射:         公共类ConnectionMapping         {         私人词典> _connections =新词典>();

    public int Count
    {
        get
        {
            return _connections.Count;
        }
    }


    public void Add(T key, string connectionId)
    {
        lock (_connections)
        {
            HashSet<string> connections;
            if (!_connections.TryGetValue(key, out connections))
            {
                connections = new HashSet<string>();
                _connections.Add(key, connections);
            }

            lock (connections)
            {
                connections.Add(connectionId);
            }
        }
    }

    public IEnumerable<string> GetConnections(T key)
    {
        HashSet<string> connections;
        if (_connections.TryGetValue(key, out connections))
        {
            return connections;
        }

        return Enumerable.Empty<string>();
    }
    //public IEnumerable<string> GetConnections2(T key)
    //{
    //    List<HashSet<string>> connections;
    //    if (_connections.Any(x => x.Key.ToString().Contains(key.ToString())))
    //    {
    //        connections = _connections.Where(x => x.Key.ToString().StartsWith(key.ToString() + "_")).Select(x => x.Value);
    //    }

    //    return Enumerable.Empty<string>();
    //}
    public void Remove(T key, string connectionId)
    {
        lock (_connections)
        {
            HashSet<string> connections;
            if (!_connections.TryGetValue(key, out connections))
            {
                return;
            }

            lock (connections)
            {
                connections.Remove(connectionId);

                if (connections.Count == 0)
                {
                    _connections.Remove(key);
                }
            }
        }
    }
}

Hub文档为:

public class TestHub : Hub
{
    private readonly static ConnectionMapping<string> _connections = new ConnectionMapping<string>();
    public string GetUserGroup()
    {
        string abc = "";
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["signalr"].ConnectionString))
        {
            connection.Open();
            string sqltheme = "Select Usr_GroupID from SysUser where ID=" + Convert.ToInt32(HttpContext.Current.User.Identity.Name.Split('_')[1]) + "";
            using (SqlCommand command = new SqlCommand(sqltheme, connection))
            {
                abc = command.ExecuteScalar().ToString();
            }
        }
        return abc;
    }
    public override Task OnConnected()
    {
        string name = "";
        try
        {
            name = HttpContext.Current.User.Identity.Name.Split('_')[1];
            Groups.Add(Context.ConnectionId, GetUserGroup());
        }catch(Exception ex)
        {
            name = Context.ConnectionId;
        }
        if (_connections.GetConnections(name).Count() > 0)
        {
            _connections.Remove(name, _connections.GetConnections(name).ToString());
        }
        _connections.Add(name, Context.ConnectionId);
        return base.OnConnected();
    }
    [HubMethodName("send")]
    public void Send(string mes)
    {
        Clients.All.send(mes); // if you want to send all user use this.
    }
    [HubMethodName("sendUser")]
    public void SendUser(string[] who, int id, string title)
    {
        string name = Context.User.Identity.Name;
        foreach (var user in who)
        {
            foreach (var connectionId in _connections.GetConnections(user))
            {
                Clients.Client(connectionId).sendUser(id, title);
            }
        }
    }
    }

最后,用于调用中心函数的javascript代码:

var myhub = $.connection.testHub;
        $(function () {
            $.connection.hub.start();
            chat.client.sendUser = function (id, title) {
                var count = parseFloat($("#header_notification_bar > a > span").text()) + 1;
                $("#header_notification_bar > a > span").text(count);
                toastr.info('Bir Yeni Bildiriminiz Var.Görüntülemek İçin Tıklayınız.', 'Bildirim', {
                    closeButton: true, timeOut: 20000, onclick: function () {
                        window.location.href = '/tr/Notification/List';
                    }
                });
                $("#notification_list").prepend("<li><a href='javascript:;' style='background-color:#e6e6e6' class='okunmadi' id='" + id + "'><span class='time' style='min-width:100px;'>şimdi</span><span class='details'><span class='label label-sm label-icon label-success'><i class='fa fa-bullhorn'></i></span>" + title + "</span></a></li>");
            };

我希望它也对您有用。