是否有代码可以自动更新数据库中的聊天页面

时间:2019-04-15 09:57:54

标签: c# sql asp.net chat

我在ASP.NET网站上有一个聊天页面,我希望有一个代码可以在新消息到达数据库时自动更新聊天。我正在使用SQL,ASP.NET和C#。

我尝试了一些代码,但由于需要而无法正常运行

    <%@ Page Language="C#" AutoEventWireup="true" 
CodeFile="allchats.aspx.cs" MaintainScrollPositionOnPostback="true" 
Inherits="chat_allchats" %>

 <link 
href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" 
rel="stylesheet" id="bootstrap-css">
<script 
src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!------ Include the above in your HEAD tag ---------->

<!DOCTYPE html>
<html>
    <head>
        <title>Chat</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.js"></script>
    <style>
        body,html{
            height: 100%;
            margin: 0;
            background: #7F7FD5;
           background: -webkit-linear-gradient(to right, #91EAE4, #86A8E7, #7F7FD5);
            background: linear-gradient(to right, #91EAE4, #86A8E7, #7F7FD5);
        }

        .chat{
            margin-top: auto;
            margin-bottom: auto;
        }
        .card{
            height: 500px;
            border-radius: 15px !important;
            background-color: rgba(0,0,0,0.4) !important;
        }
        .contacts_body{
            padding:  0.75rem 0 !important;
            overflow-y: auto;
            white-space: nowrap;
        }
        .msg_card_body{
            overflow-y: auto;
        }
        .card-header{
            border-radius: 15px 15px 0 0 !important;
            border-bottom: 0 !important;
        }
     .card-footer{
        border-radius: 0 0 15px 15px !important;
            border-top: 0 !important;
    }
        .container{
            align-content: center;
        }
        .search{
            border-radius: 15px 0 0 15px !important;
            background-color: rgba(0,0,0,0.3) !important;
            border:0 !important;
            color:white !important;
        }
        .search:focus{
             box-shadow:none !important;
           outline:0px !important;
        }
        .type_msg{
            background-color: rgba(0,0,0,0.3) !important;
            border:0 !important;
            color:white !important;
            height: 60px !important;
            overflow-y: auto;
        }
            .type_msg:focus{
             box-shadow:none !important;
           outline:0px !important;
        }
        .attach_btn{
    border-radius: 15px 0 0 15px !important;
    background-color: rgba(0,0,0,0.3) !important;
            border:0 !important;
            color: white !important;
            cursor: pointer;
        }
        .send_btn{
    border-radius: 0 15px 15px 0 !important;
    background-color: rgba(0,0,0,0.3) !important;
            border:0 !important;
            color: white !important;
            cursor: pointer;
        }
        .search_btn{
            border-radius: 0 15px 15px 0 !important;
            background-color: rgba(0,0,0,0.3) !important;
            border:0 !important;
            color: white !important;
            cursor: pointer;
        }
        .contacts{
            list-style: none;
            padding: 0;
        }
        .contacts li{
            width: 100% !important;
            padding: 5px 10px;
            margin-bottom: 15px !important;
        }
    .active{
            background-color: rgba(0,0,0,0.3);
    }
        .user_img{
            height: 70px;
            width: 70px;
            border:1.5px solid #f5f6fa;

        }
        .user_img_msg{
            height: 40px;
            width: 40px;
            border:1.5px solid #f5f6fa;

        }
    .img_cont{
            position: relative;
            height: 70px;
            width: 70px;
    }
    .img_cont_msg{
            height: 40px;
            width: 40px;
    }
    .online_icon{
        position: absolute;
        height: 15px;
        width:15px;
        background-color: #4cd137;
        border-radius: 50%;
        bottom: 0.2em;
        right: 0.4em;
        border:1.5px solid white;
    }
    .offline{
        background-color: #c23616 !important;
    }
    .user_info{
        margin-top: auto;
        margin-bottom: auto;
        margin-left: 15px;
    }
    .user_info span{
        font-size: 20px;
        color: white;
    }
    .user_info p{
    font-size: 10px;
    color: rgba(255,255,255,0.6);
    }
    .video_cam{
        margin-left: 50px;
        margin-top: 5px;
    }
    .video_cam span{
        color: white;
        font-size: 20px;
        cursor: pointer;
        margin-right: 20px;
    }
    .msg_cotainer{
        margin-top: auto;
        margin-bottom: auto;
        margin-left: 10px;
        border-radius: 25px;
        background-color: #82ccdd;
        padding: 10px;
        position: relative;
    }
    .msg_cotainer_send{
        margin-top: auto;
        margin-bottom: auto;
        margin-right: 10px;
        border-radius: 25px;
        background-color: #78e08f;
        padding: 10px;
        position: relative;
    }
    .msg_time{
        position: absolute;
        left: 0;
        bottom: -15px;
        color: rgba(255,255,255,0.5);
        font-size: 10px;
    }
    .msg_time_send{
        position: absolute;
        right:0;
        bottom: -15px;
        color: rgba(255,255,255,0.5);
        font-size: 10px;
    }
    .msg_head{
        position: relative;
    }
    #action_menu_btn{
        position: absolute;
        right: 10px;
        top: 10px;
        color: white;
        cursor: pointer;
        font-size: 20px;
    }
    .action_menu{
        z-index: 1;
        position: absolute;
        padding: 15px 0;
        background-color: rgba(0,0,0,0.5);
        color: white;
        border-radius: 15px;
        top: 30px;
        right: 15px;
        display: none;
    }
    .action_menu ul{
        list-style: none;
        padding: 0;
    margin: 0;
    }
    .action_menu ul li{
        width: 100%;
        padding: 10px 15px;
        margin-bottom: 5px;
    }
    .action_menu ul li i{
        padding-right: 10px;

    }
    .action_menu ul li:hover{
        cursor: pointer;
        background-color: rgba(0,0,0,0.2);
    }
    @media(max-width: 576px){
    .contacts_card{
        margin-bottom: 15px !important;
    }
    }
    </style>
    </head>
    <body>
         <form runat="server">


    <% EccoSchoolEntities db = new EccoSchoolEntities();
                    string r = "",u="",n="",f="";
                    if(Session["role"]!=null && Session["user_id"]!=null )

                    {
                        r = Session["role"].ToString();
                        u = Session["user_id"].ToString();


                        if(r=="student" || r=="Teacher")
                        {




                        }else {
                        Response.Redirect("/login.aspx");
                    }


                    }
                    else
                    {
                        Response.Redirect("/login.aspx");
                    }
                    int uu = int.Parse(u);
                    // var j = db.messages.Any(a => a.reciever_id == uu);
                  //  var x = (from s in db.messages where s.del == false && s.reciever_id == uu select new { s}).Count();

                  //  var num = x.ToString();




                     %>

        <div class="container-fluid h-100">
            <div class="row justify-content-center h-100">
                <div class="col-md-4 col-xl-3 chat">
                    <div class="card mb-sm-3 mb-md-0 contacts_card">
                    <div class="card-header">
                        <div class="input-group">
                            <%--<input type="text" placeholder="Search..." name="" onkeyup="myFunction1()" id="s1" class="form-control search">--%>
                            <%--<div class="input-group-prepend">
                                <span class="input-group-text search_btn"><i class="fas fa-search"></i></span>
                            </div>--%>
                        </div>
                    </div>
                       <% 
               var xx = (from s in db.chat where s.del == false && (s.reciever_id == uu ||s.sender_id==uu) select new { s}).ToList();
               if (xx != null)
               {
                   foreach (var item in xx)
                   {
                       DateTime d = DateTime.Parse(item.s.date.ToString());

                                 %>
                    <div class="card-body contacts_body" id="mytable">
                        <ui class="contacts">
                        <li class="active">
                            <div class="d-flex bd-highlight">
                                <div class="img_cont">
                                                                        <a href="allchats.aspx?s_id=<%=item.s.sender_id %>&&r_id=<%=item.s.reciever_id %>"><img src="../assets/img/1.png" class="rounded-circle user_img"/></a>
    <span class="online_icon"></span>
                                </div>
                                <div class="user_info">
                                       <%if (uu == item.s.reciever_id)
                                            { %>
                                    <span><%=item.s.sender_name %></span>
                                     <%}%>
                                    <%else if (uu == item.s.sender_id)
                                            { %>
                                    <span><%=item.s.reciever_name %></span>
                                    <%} %>
                                    <p> online</p>
                                </div>
                                <%}
                            } %>
                            </div>
                        </li>

                        </ui>
                    </div>
                    <div class="card-footer"></div>
                </div></div>
                 <% 
                     if (!String.IsNullOrEmpty(Convert.ToString(Request.QueryString["s_id"])) && !String.IsNullOrEmpty(Convert.ToString(Request.QueryString["r_id"])))
                     {
                         int s_id = int.Parse(Request.QueryString["s_id"].ToString());
                         int r_id = int.Parse(Request.QueryString["r_id"].ToString());

                         var xxc = (from s in db.messages where s.del == false && ((s.reciever_id == r_id && s.sender_id == s_id) ||(s.reciever_id == s_id && s.sender_id == r_id) ) select new { s }).Count();
                         var xx2 = (from s in db.chat where s.del == false && (s.reciever_id == r_id && s.sender_id == s_id) select s.reciever_name).FirstOrDefault();
                         var xx22 = (from s in db.chat where s.del == false && (s.reciever_id == r_id && s.sender_id == s_id) select s.sender_name).FirstOrDefault();


                                 %>
                <div class="col-md-8 col-xl-6 chat">
                    <div class="card">
                        <div class="card-header msg_head">
                            <div class="d-flex bd-highlight">
                                <div class="img_cont">
                                    <img src="../assets/img/1.png" class="rounded-circle user_img">
                                    <span class="online_icon"></span>
                                </div>
                                <div class="user_info">
                                     <% if (uu == s_id)
    {
                                        %>
                                    <span>Chat with <%=xx2.ToString() %></span>
                                    <%}
    else if (uu == r_id)
    { %>
                                   <span>Chat with <%=xx22.ToString() %></span>
                                    <%} %>
                                    <p><%=xxc%></p>
                                </div>
                                <div class="video_cam">
                                    <%--<span><i class="fas fa-video"></i></span>
                                    <span><i class="fas fa-phone"></i></span>--%>
                                </div>
                            </div>
                        <%--    <span id="action_menu_btn"><i class="fas fa-ellipsis-v"></i></span>
                            <div class="action_menu">
                                <ul>
                                    <li><i class="fas fa-user-circle"></i> View profile</li>
                                    <li><i class="fas fa-users"></i> Add to close friends</li>
                                    <li><i class="fas fa-plus"></i> Add to group</li>
                                    <li><i class="fas fa-ban"></i> Block</li>
                                </ul>
                            </div>--%>
                        </div>

                        <div class="card-body msg_card_body">
                                                    <%   var xx3 = (from s in db.messages where s.del == false && ((s.reciever_id == r_id && s.sender_id == s_id) || (s.reciever_id == s_id && s.sender_id == r_id)) select s).OrderBy(a => a.date).ToList();
                           if (xx3 != null)
                           {
                               foreach (var item3 in xx3)
                               {
                                   DateTime d = DateTime.Parse(item3.date.ToString());
                                   if (item3.reciever_id == r_id && item3.sender_id == s_id)
                                   {
 %>
                            <div class="d-flex justify-content-start mb-4">
                                <div class="img_cont_msg">
                                    <img src="../assets/img/1.png" class="rounded-circle user_img_msg">
                                </div>
                                <div class="msg_cotainer">
                                        <%=item3.message %>
                                    <span class="msg_time"><%=d.ToShortTimeString() %></span>
                                </div>
                            </div>
                                <%


                                }
                                else if (item3.reciever_id == s_id && item3.sender_id == r_id)
                                { %>
                            <div class="d-flex justify-content-end mb-4">
                                <div class="msg_cotainer_send">
                                        <%=item3.message %>
                                    <span class="msg_time_send"><%=d.ToShortTimeString() %></span>
                                </div>
                                <div class="img_cont_msg">
                            <img src="../assets/img/2.png" class="rounded-circle user_img_msg">
                                </div>
                            </div>
                            <%}}}} %>

                        </div>
                        <div class="card-footer">
                            <div class="input-group">
                                <%--<div class="input-group-append">--%>
                                    <%--<span class="input-group-text attach_btn"><i class="fas fa-paperclip"></i></span>--%>
                            <%--<asp:FileUpload ID="FileUpload1"  class="input-group-text attach_btn" placeholder="upload" runat="server" />--%><%--<i class="fas fa-paperclip"></i>--%>

                                <%--</div>--%>
                                <textarea name="" runat="server"  id="message" class="form-control type_msg" placeholder="Type your message..."></textarea>
                                <div class="input-group-append">
                                    <%--<span class="input-group-text send_btn"><i class="fas fa-location-arrow"></i></span>--%>
                    <asp:Button OnClick="btn_add_Click"  CssClass="btn btn-primary"  ValidationGroup="b" ID="btn_add" runat="server" Text="send" /><%--<i class="fas fa-location-arrow"></i>--%>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>


    <!--Coded With Love By Mutiullah Samim-->

        </form>
        <script>
            $(document).ready(function () {
                $('#action_menu_btn').click(function () {
                    $('.action_menu').toggle();
                });
            });
        </script>
           <script>

        function myFunction1() {
            var input, filter, div, ul, li, i;
            input = document.getElementById("s1");
            filter = input.value.toUpperCase();
            div = document.getElementById("mytable");
            ul = table.getElementsByTagName("ul");
            for (i = 0; i < tr.length; i++) {
                li = tr[i].getElementsByTagName("li")[1];
                if (li) {
                    if (li.innerHTML.toUpperCase().indexOf(filter) > -1) {
                        ul[i].style.display = "";
                    } else {
                        ul[i].style.display = "none";
                    }
                }
            }
        }
    </script>
    </body>
</html>

C#代码:

     using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public partial class chat_allchats : System.Web.UI.Page
    {
        EccoSchoolEntities db = new EccoSchoolEntities();

       protected void Page_Load(object sender, EventArgs e)
{

}
//protected void reload_Click(object sender, EventArgs e)
//{
//    if (!String.IsNullOrEmpty(Convert.ToString(Request.QueryString["s_id"])) && !String.IsNullOrEmpty(Convert.ToString(Request.QueryString["r_id"])))
//    {
//        int s_id = int.Parse(Request.QueryString["s_id"].ToString());
//        int r_id = int.Parse(Request.QueryString["r_id"].ToString());

//        Response.Redirect("allchats.aspx?s_id=" +s_id+"&&r_id="+r_id);

//    }


//}


protected void btn_add_Click(object sender, EventArgs e)
{
    if (!String.IsNullOrEmpty(Convert.ToString(Request.QueryString["s_id"])) && !String.IsNullOrEmpty(Convert.ToString(Request.QueryString["r_id"])))
    {
        if (message.Value != "")
        {

            string n = "", u = "";
            if (Session["user_id"] != null && Session["name"] != null)
            {
                n = Session["name"].ToString();
                u = Session["user_id"].ToString();

                int uu = int.Parse(u);
                int user_id = (from s in db.users where s.id == uu select s.id).FirstOrDefault();
                // int yy = Convert.ToInt32(year1.Text);
                string user_name = (from s in db.users where s.id == uu select s.name).FirstOrDefault();

                DateTime dt = DateTime.Now;


                int s_id = int.Parse(Request.QueryString["s_id"].ToString());
                int r_id = int.Parse(Request.QueryString["r_id"].ToString());



                chat f = db.chat.FirstOrDefault(a => a.del == false && a.sender_id == s_id && a.reciever_id == r_id);
                int chat_id, sender_id, reciever_id;
                string r_name, s_name;
                if (f != null)
                {
                    chat_id = int.Parse(f.id.ToString());
                    sender_id = int.Parse(f.sender_id.ToString());
                    reciever_id = int.Parse(f.reciever_id.ToString());

                    r_name = f.reciever_name.ToString();
                    s_name = f.sender_name.ToString();

                    if ( uu ==r_id)
                    {
                        messages st2 = new messages
                        {
                            sender_id = user_id,
                            sender_name = user_name,
                            reciever_id = s_id,
                            reciever_name = s_name,
                            date = dt,
                            chat_id = chat_id,
                            message = message.Value,
                            // subject = subj.Text,
                            del = false

                        };

                        db.messages.Add(st2);
                        db.SaveChanges();
                    }
                    else if ( uu == s_id)
                    {
                        messages st2 = new messages
                        {
                            sender_id = user_id,
                            sender_name = user_name,
                            reciever_id = r_id,
                            reciever_name = r_name,
                            date = dt,
                            chat_id = chat_id,
                            message = message.Value,
                            // subject = subj.Text,
                            del = false

                        };

                        db.messages.Add(st2);
                        db.SaveChanges();
                    }
                }
                Response.Redirect("allchats.aspx?s_id=" + s_id + "&&r_id=" + r_id);


            }
        }
    }
}

}

that is what i did 

如何从数据库自动更新消息框

该做什么?

谢谢

1 个答案:

答案 0 :(得分:-1)

如果您只想创建非实时聊天。 我认为有两种方法可以做到这一点。

  1. 您可以轻松编写数据库触发器并使用.NET CLR触发器进行捕获 On table update, trigger an action in my .NET code

  2. 或者您可以触发重复的Ajax请求并检查表中是否有新消息。

但是我应该说这两种方法都非常老旧。 我猜您在寻找SignalR。

https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?tabs=visual-studio&view=aspnetcore-2.2