• 1402/01/10

کارنکردن agenthub :

سلام استاد

agenthub اصلا کار نمیکنه چند باری هم چک کردم کد های من با شما هیچ فرقی نداره

فقط سایت من بخش login داشت من دیگه نذاشتم

 

Uncaught (in promise) Error: Cannot send data if the connection is not in the 'Connected' State.
    at HttpConnection.send (HttpConnection.ts:85:19)
    at HubConnection.ts:199:29
    at new Promise (<anonymous>)
    at HubConnection.invoke (HubConnection.ts:179:19)
    at sendMessage (agent.js:47:25)
    at HTMLFormElement.<anonymous> (agent.js:61:9)
  • 1402/01/14
  • ساعت 10:29

سلام دوست من وقتتون  بخیر

دوست  عزیزم   لطفا کدهایی  که  نوشتید  رو برای من  ارسال کنید

با تشکر


  • 1402/01/15
  • ساعت 23:49

ChatHub

 

    public class ChatHub : Hub
    {
        private readonly IChatRoomService _chatRoomService;
        private readonly IHubContext<AgentHub> _agentHub;

        public ChatHub(IChatRoomService chatRoomService, IHubContext<AgentHub> agentHub)
        {
            _chatRoomService = chatRoomService;
            _agentHub = agentHub;
        }
        public override async Task OnConnectedAsync()
        {
            if (Context.User.Identity.IsAuthenticated)
            {
                await base.OnConnectedAsync();
                return;
            }

            var roomId = await _chatRoomService.CreateRoom(Context.ConnectionId);
            await Groups.AddToGroupAsync(Context.ConnectionId, roomId.ToString());

            await Clients.Caller.SendAsync("ReciveMessage",
                "TopLearn Support",
                DateTimeOffset.UtcNow,
                "Hello ! What can we help you with today ?");

            await base.OnConnectedAsync();
        }

        public async Task SendMessage(string name, string text)
        {
            var roomId = await _chatRoomService.GetRoomForConnectionId(Context.ConnectionId);
            var message = new ChatMessage
            {
                SenderName = name,
                Text = text,
                SendAt = DateTimeOffset.Now
            };

            await _chatRoomService.AddMessage(roomId, message);


            await Clients.Group(roomId.ToString()).SendAsync("ReceiveMessage", message.SenderName, message.SendAt, message.Text);
        }

        public async Task SetName(string visitorName)
        {
            var roomName = $"Chat With {visitorName} from the web .";

            var roomId = await _chatRoomService.GetRoomForConnectionId(Context.ConnectionId);

            await _chatRoomService.SetRoomName(roomId, roomName);
            await _agentHub.Clients.All.SendAsync("ActiveRooms", await _chatRoomService.GetAllRooms());
        }

        [Authorize]
        public async Task JoinRoom(Guid roomId)
        {
            if (roomId == Guid.Empty)
            {
                throw new ArgumentException("Invalid Room ID");
            }

            await Groups.AddToGroupAsync(Context.ConnectionId, roomId.ToString());
        }

        [Authorize]
        public async Task LeaveRoom(Guid roomId)
        {
            if (roomId == Guid.Empty)
            {
                throw new ArgumentException("Invalid Room ID");
            }

            await Groups.RemoveFromGroupAsync(Context.ConnectionId, roomId.ToString());
        }
    }

 agenthub

[Authorize]
    public class AgentHub : Hub
    {
        private readonly IChatRoomService _chatRoomService;
        private readonly IHubContext<ChatHub> _chatHub;

        public AgentHub(IChatRoomService chatRoomService, IHubContext<ChatHub> chatHub)
        {
            _chatRoomService = chatRoomService;
            _chatHub = chatHub;
        }

        public override async Task OnConnectedAsync()
        {
            await Clients.Caller.SendAsync("ActiveRooms", await _chatRoomService.GetAllRooms());
            await base.OnConnectedAsync();
        }

        public async Task SendAgentMessage(Guid roomId, string text)
        {
            var message = new ChatMessage
            {
                SendAt = DateTimeOffset.UtcNow,
                SenderName = Context.User.Identity.Name,
                Text = text
            };
            await _chatRoomService.AddMessage(roomId, message);

            await _chatHub.Clients.Group(roomId.ToString())
                .SendAsync("ReceiveMessage", message.SenderName, message.SendAt, message.Text);
        }

        public async Task LoadHistory(Guid roomId)
        {
            var history = await _chatRoomService.GetMessageHistory(roomId);
            await Clients.Caller.SendAsync("ReceiveMessages", history);
        }

    }

IChatRoomService

public interface IChatRoomService
    {
        Task<Guid> CreateRoom(string connectionId);
        Task<Guid> GetRoomForConnectionId(string connectionId);

        Task SetRoomName(Guid roomId, string name);

        Task AddMessage(Guid roomId, ChatMessage message);
        Task<IEnumerable<ChatMessage>> GetMessageHistory(Guid roomId);

        Task<IReadOnlyDictionary<Guid, ChatRoom>> GetAllRooms();
    }

InMemoryChatRoomService

public class InMemoryChatRoomService : IChatRoomService
    {
        private readonly Dictionary<Guid, ChatRoom> _roomInfo = new Dictionary<Guid, ChatRoom>();
        private readonly Dictionary<Guid, List<ChatMessage>> _messageHistory = new Dictionary<Guid, List<ChatMessage>>();
        public Task<Guid> CreateRoom(string connectionId)
        {
            var id = Guid.NewGuid();
            _roomInfo[id] = new ChatRoom()
            {
                OwerConnectionId = connectionId
            };

            return Task.FromResult(id);
        }

        public Task<Guid> GetRoomForConnectionId(string connectionId)
        {
            var foundRoom = _roomInfo.FirstOrDefault(x => x.Value.OwerConnectionId == connectionId);

            if (foundRoom.Key == Guid.Empty)
            {
                throw new ArgumentException("Invalid Connection ID");
            }

            return Task.FromResult(foundRoom.Key);
        }

        public Task SetRoomName(Guid roomId, string name)
        {
            if (!_roomInfo.ContainsKey(roomId))
            {
                throw new ArgumentException("Invalid Room ID");
            }

            _roomInfo[roomId].Name = name;

            return Task.CompletedTask;
        }

        public Task AddMessage(Guid roomId, ChatMessage message)
        {
            if (!_messageHistory.ContainsKey(roomId))
            {
                _messageHistory[roomId] = new List<ChatMessage>();
            }
            _messageHistory[roomId].Add(message);

            return Task.CompletedTask;
        }

        public Task<IEnumerable<ChatMessage>> GetMessageHistory(Guid roomId)
        {
            _messageHistory.TryGetValue(roomId, out var messages);

            messages = messages ?? new List<ChatMessage>();
            var sortedMessages = messages.OrderBy(x => x.SendAt)
                .AsEnumerable();

            return Task.FromResult(sortedMessages);
        }

        public Task<IReadOnlyDictionary<Guid, ChatRoom>> GetAllRooms()
        {
            return Task.FromResult(_roomInfo as IReadOnlyDictionary<Guid, ChatRoom>);
        }
    }

agent.js

var activeRoomId = '';

var agentConnection = new signalR.HubConnectionBuilder()
    .withUrl('/agentHub')
    .build();

agentConnection.on('ActiveRooms', loadRooms);

agentConnection.onclose(function () {
    handleDisconnected(startAgentConnection);
});

function startAgentConnection() {
    agentConnection
        .start()
        .catch(function (err) {
            console.error(err);
        });
}

var chatConnection = new signalR.HubConnectionBuilder()
    .withUrl('/chatHub')
    .build();

chatConnection.onclose(function () {
    handleDisconnected(startChatConnection);
});

chatConnection.on('ReceiveMessage', addMessage);
agentConnection.on('ReceiveMessages', addMessages);

function startChatConnection() {
    chatConnection
        .start()
        .catch(function (err) {
            console.error(err);
        });
}

function handleDisconnected(retryFunc) {
    console.log('Reconnecting in 5 seconds...');
    setTimeout(retryFunc, 5000);
}

function sendMessage(text) {
    if (text && text.length) {
        agentConnection.invoke('SendAgentMessage', activeRoomId, text);
    }
}

function ready() {
    startAgentConnection();
    startChatConnection();

    var chatFormEl = document.getElementById('chatForm');
    chatFormEl.addEventListener('submit', function (e) {
        e.preventDefault();

        var text = e.target[0].value;
        e.target[0].value = '';
        sendMessage(text);
    });
}

function switchActiveRoomTo(id) {
    if (id === activeRoomId) return;

    if (activeRoomId) {
        chatConnection.invoke('LeaveRoom', activeRoomId);
    }

    activeRoomId = id;
    removeAllChildren(roomHistoryEl);

    if (!id) return;

    chatConnection.invoke('JoinRoom', activeRoomId);
    agentConnection.invoke('LoadHistory', activeRoomId);
}


var roomListEl = document.getElementById('roomList');
var roomHistoryEl = document.getElementById('chatHistory');

roomListEl.addEventListener('click', function (e) {
    roomHistoryEl.style.display = 'block';

    setActiveRoomButton(e.target);

    var roomId = e.target.getAttribute('data-id');
    switchActiveRoomTo(roomId);
});

function setActiveRoomButton(el) {
    var allButtons = roomListEl.querySelectorAll('a.list-group-item');

    allButtons.forEach(function (btn) {
        btn.classList.remove('active');
    });

    el.classList.add('active');
}

function loadRooms(rooms) {
    if (!rooms) return;

    var roomIds = Object.keys(rooms);
    if (!roomIds.length) return;

    switchActiveRoomTo(null);
    removeAllChildren(roomListEl);

    roomIds.forEach(function (id) {
        var roomInfo = rooms[id];
        if (!roomInfo.name) return;

        var roomButton = createRoomButton(id, roomInfo);
        roomListEl.appendChild(roomButton);
    });
}

function createRoomButton(id, roomInfo) {
    var anchorEl = document.createElement('a');
    anchorEl.className = 'list-group-item list-group-item-action d-flex justify-content-between align-items-center';
    anchorEl.setAttribute('data-id', id);
    anchorEl.textContent = roomInfo.name;
    anchorEl.href = '#';

    return anchorEl;
}

function addMessages(messages) {
    if (!messages) return;

    messages.forEach(function (m) {
        addMessage(m.senderName, m.sentAt, m.text);
    });
}

function addMessage(name, time, message) {
    var nameSpan = document.createElement('span');
    nameSpan.className = 'name';
    nameSpan.textContent = name;

    var timeSpan = document.createElement('span');
    timeSpan.className = 'time';
    var friendlyTime = moment(time).format('H:mm');
    timeSpan.textContent = friendlyTime;

    var headerDiv = document.createElement('div');
    headerDiv.appendChild(nameSpan);
    headerDiv.appendChild(timeSpan);

    var messageDiv = document.createElement('div');
    messageDiv.className = 'message';
    messageDiv.textContent = message;

    var newItem = document.createElement('li');
    newItem.appendChild(headerDiv);
    newItem.appendChild(messageDiv);

    roomHistoryEl.appendChild(newItem);
    roomHistoryEl.scrollTop = roomHistoryEl.scrollHeight - roomHistoryEl.clientHeight;
}

function removeAllChildren(node) {
    if (!node) return;

    while (node.lastChild) {
        node.removeChild(node.lastChild);
    }
}

document.addEventListener('DOMContentLoaded', ready);

Chat.js

var chatterName = "Visitor";


var dialogEL = document.getElementById('chatDialog');

//Initialize SignalR
var connection = new signalR.HubConnectionBuilder()
    .withUrl('/chatHub')
    .build();

connection.on('ReceiveMessage', renderMessage);

connection.onclose(function() {
    onDisconnected();
    console.log('ReConnecting in 5 Second ...');
    setTimeout(startConnection, 5000);
});

function startConnection() {
    connection.start().then(onConnected).catch(function(err) {
        console.log(err);
    });
}

function onDisconnected() {
    dialogEL.classList.add('disconnected');
}

function onConnected() {
    dialogEL.classList.remove('disconnected');

    var messageTextBox = document.getElementById('messageTextBox');
    messageTextBox.focus();

    connection.invoke('SetName', chatterName);

}

function ready() {
    var chatForm = document.getElementById('chatForm');
    chatForm.addEventListener('submit',
        function(e) {
            e.preventDefault();
            var text = e.target[0].value;
            e.target[0].value = '';
            sendMessage(text);
        });

    var welcomePanelFormEL = document.getElementById('chatWelcomePanel');
    welcomePanelFormEL.addEventListener('submit', function(e) {
        e.preventDefault();

        var name = e.target[0].value;
        if (name && name.length) {
            welcomePanelFormEL.style.display = 'none';
            chatterName = name;
            startConnection();
        }
    });

}

function sendMessage(text) {
    if (text && text.length) {
        connection.invoke('SendMessage', chatterName, text);
    }
}

function renderMessage(name,time,message) {
    var nameSpan = document.createElement('span');
    nameSpan.className = 'name';
    nameSpan.textContent = name;

    var timeSpan = document.createElement('span');
    timeSpan.className = 'time';
    var timeFriendly = moment(time).format('H:mm');
    timeSpan.textContent = timeFriendly;

    var headerDiv = document.createElement('div');
    headerDiv.appendChild(nameSpan);
    headerDiv.appendChild(timeSpan);

    var messageDiv = document.createElement('div');
    messageDiv.className = 'message';
    messageDiv.textContent = message;

    var newItem = document.createElement('li');
    newItem.appendChild(headerDiv);
    newItem.appendChild(messageDiv);

    var chatHistory = document.getElementById('chatHistory');
    chatHistory.appendChild(newItem);
    chatHistory.scrollTop = chatHistory.scrollHeight - chatHistory.clientHeight;
}


document.addEventListener('DOMContentLoaded',ready);

ChatMessage

 public string SenderName { get; set; }
        public string Text { get; set; }
        public DateTimeOffset SendAt { get; set; }

ChatRoom

 public string OwerConnectionId { get; set; }
        public string Name { get; set; }

startup

app.UseSignalR(route =>
            {
                route.MapHub<ChatHub>("/chatHub");
                route.MapHub<AgentHub>("/agentHub");
            });

ChatOnline

<link href="~/css/chat.css" rel="stylesheet" />
@section Scripts
{
    <script src="~/js/Chat.js"></script>
}

<div id="chatDialog" title="Chat With Support" class="disconnected">
    <div id="chatWelcomePanel">
        <h3>Have a question ?</h3>
        <form id="chatConnectForm">
            <input class="form-control" type="text" placeholder="Enter Your Name" />
            <input type="submit" class="btn btn-info" value="Connect" />
        </form>
    </div>
    <div id="chatConnectingInfo">
        <strong>Connecting ...</strong>
    </div>
    <div id="chatMainPanel">
        <ul id="chatHistory"></ul>
        <div id="bottomPanel">
            <div class="row">
                <form id="chatForm">
                    <div class="col-md-8">
                        <input id="messageTextBox" class="form-control" type="text" placeholder="Type a Message" />
                    </div>
                    <div class="col-md-2">
                        <input type="submit" class="btn btn-success" value="Send" />
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

Supportagent

@section Scripts {
    <script src="~/js/agent.js"></script>
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<link rel="stylesheet" href="~/css/agent.css" />

<div class="jumbotron">
    <h1 class="display-4">@ViewData["Title"]</h1>
    <p class="lead">@ViewData["Subtitle"]</p>
</div>

<div class="container">
    <div class="row">
        <div class="col-md-4">
            <div id="roomList" class="list-group">
            </div>
        </div>
        <div class="col-md-8">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <ul id="chatHistory" class="card-body"></ul>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <form id="chatForm" class="form-inline mt-2">
                        <input id="messageTextbox" type="text" placeholder="Type a message" class="form-control mr-sm-2 flex-grow-1" />
                        <button type="submit" class="btn btn-primary">Send</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

 

 


  • 1402/01/18
  • ساعت 17:38

آیا کدام مشکلی داره؟


logo-samandehi