Chat application using signalr as wcf service - asp.net

i have done the chat application using signalr client and chatsever implemented as class. Now i want to implement chat server as wcf service.
<link rel="stylesheet" href="Styles/jquery-ui.css" />
<script src="Scripts/jquery-1.8.2.js"></script>
<script src="Scripts/jquery-ui.js"></script>
<script type="text/javascript" src="Scripts/jquery.dialogextend.1_0_1.js"></script>
<script type="text/javascript" src="Scripts/jquery.signalR.js"></script>
<script type="text/javascript" src="Scripts/jQuery.tmpl.js"></script>
<script type="text/javascript" src="signalr/hubs"></script>
<script id="new-online-contacts" type="text/x-jquery-tmpl">
<div>
<ul>
{{each messageRecipients}}
<li id="chatLink${messageRecipientId}">${messageRecipientName}</li>
{{/each}}
</ul>
</div>
</script>
<script id="new-chatroom-template" type="text/x-jquery-tmpl">
<div id="chatRoom${chatRoomId}" class="chatRoom">
<ul id="messages${chatRoomId}" class="chatMessages">
</ul>
<form id="sendmessage${chatRoomId}" action="#">
<input type="text" id="newmessage${chatRoomId}" class="chatNewMessage"/>
<div class="clear"></div>
<input type="button" id="chatsend${chatRoomId}" value="Send" class="chatSend" OnClick="javascript:SRChat.sendChatMessage('${chatRoomId}')" />
<input type="button" id="chatend${chatRoomId}" value="End Chat" class="chatSend" OnClick="javascript:SRChat.endChat('${chatRoomId}')" />
</form>
</div>
</script>
<script id="new-chat-header" type="text/x-jquery-tmpl">
<div id="chatRoomHeader${chatRoomId}">
{{each messageRecipients}}
{{if $index == 0}}
${messageRecipientName}
{{else}}
, ${messageRecipientName}
{{/if}}
{{/each}}
<div>
</script>
<script id="new-message-template" type="text/x-jquery-tmpl">
<li class="message" id="m-${chatMessageId}">
<strong>${displayPrefix}</strong>
{{html messageText}}
</li>
</script>
<script id="new-notify-message-template" type="text/x-jquery-tmpl">
<li class="message" id="m-${chatMessageId}">
<strong>{{html messageText}}</strong>
</li>
</script>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
SRChat.attachEvents();
});
SRChat = new function () {
var Username = GetParameterValues('Username');
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
var chatRooms = 0;
var numRand = Username;
var senderId = numRand;
var senderName = 'User :' + numRand;
var sRChatServer;
window.onbeforeunload = function () {
if (chatRooms > 0)
return "All chat instances will be ended!";
};
this.attachEvents = function () {
$("#userNameLabel").html(senderName);
if ($.connection != null) {
jQuery.support.cors = true;
$.connection.hub.url = 'signalr/hubs';
sRChatServer = $.connection.sRChatServer;
$.connection.hub.start({ transport: 'auto' }, function () {
sRChatServer.server.connect(senderId, senderName).fail(function (e) {
alert(e);
});
});
sRChatServer.client.initiateChatUI = function (chatRoom) {
var chatRoomDiv = $('#chatRoom' + chatRoom.chatRoomId);
if (($(chatRoomDiv).length > 0)) {
var chatRoomText = $('#newmessage' + chatRoom.chatRoomId);
var chatRoomSend = $('#chatsend' + chatRoom.chatRoomId);
var chatRoomEndChat = $('#chatend' + chatRoom.chatRoomId);
chatRoomText.show();
chatRoomSend.show();
chatRoomEndChat.show();
}
else {
var e = $('#new-chatroom-template').tmpl(chatRoom);
var c = $('#new-chat-header').tmpl(chatRoom);
chatRooms++;
//dialog options
var dialogOptions = {
"id": '#messages' + chatRoom.chatRoomId,
"title": c,
"width": 360,
"height": 365,
"modal": false,
"resizable": false,
"close": function () { javascript: SRChat.endChat('' + chatRoom.chatRoomId + ''); $(this).remove(); }
};
// dialog-extend options
var dialogExtendOptions = {
"close": true,
"maximize": false,
"minimize": true,
"dblclick": 'minimize',
"titlebar": 'transparent'
};
e.dialog(dialogOptions).dialogExtend(dialogExtendOptions);
$('#sendmessage' + chatRoom.chatRoomId).keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('#chatsend' + chatRoom.chatRoomId).click();
return false;
}
});
}
};
sRChatServer.client.updateChatUI = function (chatRoom) {
var chatRoomHeader = $('#chatRoomHeader' + chatRoom.chatRoomId);
var c = $('#new-chat-header').tmpl(chatRoom);
chatRoomHeader.html(c);
};
sRChatServer.client.receiveChatMessage = function (chatMessage, chatRoom) {
sRChatServer.client.initiateChatUI(chatRoom);
var chatRoom = $('#chatRoom' + chatMessage.conversationId);
var chatRoomMessages = $('#messages' + chatMessage.conversationId);
var e = $('#new-message-template').tmpl(chatMessage).appendTo(chatRoomMessages);
e[0].scrollIntoView();
chatRoom.scrollIntoView();
};
sRChatServer.client.receiveLeftChatMessage = function (chatMessage) {
var chatRoom = $('#chatRoom' + chatMessage.conversationId);
var chatRoomMessages = $('#messages' + chatMessage.conversationId);
var e = $('#new-notify-message-template').tmpl(chatMessage).appendTo(chatRoomMessages);
e[0].scrollIntoView();
chatRoom.scrollIntoView();
};
sRChatServer.client.receiveEndChatMessage = function (chatMessage) {
var chatRoom = $('#chatRoom' + chatMessage.conversationId);
var chatRoomMessages = $('#messages' + chatMessage.conversationId);
var chatRoomText = $('#newmessage' + chatMessage.conversationId);
var chatRoomSend = $('#chatsend' + chatMessage.conversationId);
var chatRoomEndChat = $('#chatend' + chatMessage.conversationId);
chatRooms--;
var e = $('#new-notify-message-template').tmpl(chatMessage).appendTo(chatRoomMessages);
chatRoomText.hide();
chatRoomSend.hide();
chatRoomEndChat.hide();
e[0].scrollIntoView();
chatRoom.scrollIntoView();
};
sRChatServer.client.onGetOnlineContacts = function (chatUsers) {
var e = $('#new-online-contacts').tmpl(chatUsers);
var chatLink = $('#chatLink' + senderId);
e.find("#chatLink" + senderId).remove();
$("#chatOnlineContacts").html("");
$("#chatOnlineContacts").html(e);
};
}
};
this.sendChatMessage = function (chatRoomId) {
var chatRoomNewMessage = $('#newmessage' + chatRoomId);
if (chatRoomNewMessage.val() == null || chatRoomNewMessage.val() == "")
return;
var chatMessage = {
senderId: senderId,
senderName: senderName,
conversationId: chatRoomId,
messageText: chatRoomNewMessage.val()
};
chatRoomNewMessage.val('');
chatRoomNewMessage.focus();
sRChatServer.server.sendChatMessage(chatMessage).fail(function (e) {
alert(e);
});
return false;
};
this.endChat = function (chatRoomId) {
var chatRoomNewMessage = $('#newmessage' + chatRoomId);
var chatMessage = {
senderId: senderId,
senderName: senderName,
conversationId: chatRoomId,
messageText: chatRoomNewMessage.val()
};
chatRoomNewMessage.val('');
chatRoomNewMessage.focus();
sRChatServer.server.endChat(chatMessage).fail(function (e) {
//alert(e);
});
};
this.initiateChat = function (toUserId, toUserName) {
if (sRChatServer == null) {
alert("Problem in connecting to Chat Server. Please Contact Administrator!");
return;
}
sRChatServer.server.initiateChat(senderId, senderName, toUserId, toUserName).fail(function (e) {
alert(e);
});
};
};
//]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="userNameLabel">
</div>
<br />
<br />
<div id="chatRooms">
</div>
<div id="chatOnlineContacts">
</div>
</div>
</form>
</body>
My server side code is
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using SignalR.Hubs;
namespace SRChat
{
[HubName("sRChatServer")]
public class SRChatServer:Hub
{
#region Private Variables
private static readonly ConcurrentDictionary<string, MessageRecipient> _chatUsers = new ConcurrentDictionary<string, MessageRecipient>(StringComparer.OrdinalIgnoreCase);
private static readonly ConcurrentDictionary<string, ChatRoom> _chatRooms = new ConcurrentDictionary<string, ChatRoom>(StringComparer.OrdinalIgnoreCase);
#endregion
#region Public Methods
public bool Connect(string userId, string userName)
{
try
{
if (string.IsNullOrEmpty(userId) | string.IsNullOrEmpty(userName))
{
return false;
}
if (GetChatUserByUserId(userId) == null)
{
AddUser(userId, userName);
}
else
{
ModifyUser(userId, userName);
}
SendOnlineContacts();
return true;
}
catch (Exception ex)
{
throw new InvalidOperationException("Problem in connecting to chat server!");
}
}
public override Task Disconnect()
{
try
{
DeleteUser(Context.ConnectionId);
return null;
}
catch (Exception ex)
{
throw new InvalidOperationException("Problem in disconnecting from chat server!");
}
}
public bool InitiateChat(string fromUserId, string fromUserName, string toUserId, string toUserName)
{
try
{
if (string.IsNullOrEmpty(fromUserId) || string.IsNullOrEmpty(fromUserName) || string.IsNullOrEmpty(toUserId) || string.IsNullOrEmpty(toUserName))
{
return false;
}
var fromUser = GetChatUserByUserId(fromUserId);
var toUser = GetChatUserByUserId(toUserId);
if (fromUser != null && toUser != null)
{
if (!CheckIfRoomExists(fromUser, toUser))
{
//Create New Chat Room
ChatRoom chatRoom = new ChatRoom();
chatRoom.chatRoomInitiatedBy = fromUser.messageRecipientId;
chatRoom.chatRoomInitiatedTo = toUser.messageRecipientId;
chatRoom.messageRecipients.Add(fromUser);
chatRoom.messageRecipients.Add(toUser);
//create and save blank message to get new conversation id
ChatMessage chatMessage = new ChatMessage();
chatMessage.messageText = "Chat Initiated";
chatMessage.senderId = fromUser.messageRecipientId;
chatMessage.senderName = fromUser.messageRecipientName;
fromUser.chatRoomIds.Add(chatRoom.chatRoomId);
toUser.chatRoomIds.Add(chatRoom.chatRoomId);
//Create SignalR Group for this chat room and add users connection to it
Groups.Add(fromUser.connectionId, chatRoom.chatRoomId);
Groups.Add(toUser.connectionId, chatRoom.chatRoomId);
//Add Chat room object to collection
if (_chatRooms.TryAdd(chatRoom.chatRoomId, chatRoom))
{
//Generate Client UI for this room
Clients[fromUser.connectionId].initiateChatUI(chatRoom);
}
}
}
return true;
}
catch (Exception ex)
{
throw new InvalidOperationException("Problem in starting chat!");
}
}
public bool EndChat(ChatMessage chatMessage)
{
try
{
ChatRoom chatRoom;
if (_chatRooms.TryGetValue(chatMessage.conversationId, out chatRoom))
{
if (_chatRooms[chatRoom.chatRoomId].chatRoomInitiatedBy == chatMessage.senderId)
{
chatMessage.messageText = string.Format("{0} left the chat. Chat Ended!", chatMessage.senderName);
if (_chatRooms.TryRemove(chatRoom.chatRoomId, out chatRoom))
{
Clients[chatRoom.chatRoomId].receiveEndChatMessage(chatMessage);
foreach (MessageRecipient messageReceipient in chatRoom.messageRecipients)
{
if (messageReceipient.chatRoomIds.Contains(chatRoom.chatRoomId))
{
messageReceipient.chatRoomIds.Remove(chatRoom.chatRoomId);
Groups.Remove(messageReceipient.connectionId, chatRoom.chatRoomId);
}
}
}
}
else
{
MessageRecipient messageRecipient = GetChatUserByUserId(chatMessage.senderId);
if (messageRecipient != null && messageRecipient.chatRoomIds.Contains(chatRoom.chatRoomId))
{
chatRoom.messageRecipients.Remove(messageRecipient);
messageRecipient.chatRoomIds.Remove(chatRoom.chatRoomId);
if (chatRoom.messageRecipients.Count < 2)
{
chatMessage.messageText = string.Format("{0} left the chat. Chat Ended!", chatMessage.senderName);
if (_chatRooms.TryRemove(chatRoom.chatRoomId, out chatRoom))
{
Clients[chatRoom.chatRoomId].receiveEndChatMessage(chatMessage);
foreach (MessageRecipient messageReceipient in chatRoom.messageRecipients)
{
if (messageReceipient.chatRoomIds.Contains(chatRoom.chatRoomId))
{
messageReceipient.chatRoomIds.Remove(chatRoom.chatRoomId);
Groups.Remove(messageReceipient.connectionId, chatRoom.chatRoomId);
}
}
}
}
else
{
chatMessage.messageText = string.Format("{0} left the chat.", chatMessage.senderName);
Groups.Remove(messageRecipient.connectionId, chatRoom.chatRoomId);
Clients[messageRecipient.connectionId].receiveEndChatMessage(chatMessage);
Clients[chatRoom.chatRoomId].receiveLeftChatMessage(chatMessage);
Clients[chatRoom.chatRoomId].updateChatUI(chatRoom);
}
}
}
}
else
{
throw new InvalidOperationException("Problem in ending chat!");
}
return true;
}
catch (Exception ex)
{
throw new InvalidOperationException("Problem in ending chat!");
}
}
public bool SendChatMessage(ChatMessage chatMessage)
{
try
{
ChatRoom chatRoom;
if (_chatRooms.TryGetValue(chatMessage.conversationId, out chatRoom))
{
chatMessage.chatMessageId = Guid.NewGuid().ToString();
chatMessage.timestamp = DateTime.Now;
Clients[chatMessage.conversationId].receiveChatMessage(chatMessage, chatRoom);
return true;
}
else
{
throw new InvalidOperationException("Problem in sending message!");
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Problem in sending message!");
}
}
private bool SendOnlineContacts()
{
try
{
OnlineContacts onlineContacts = new OnlineContacts();
foreach (var item in _chatUsers)
{
onlineContacts.messageRecipients.Add(item.Value);
}
Clients.onGetOnlineContacts(onlineContacts);
return false;
}
catch (Exception ex)
{
throw new InvalidOperationException("Problem in getting contacts!");
}
}
#endregion
#region Private Methods
private Boolean CheckIfRoomExists(MessageRecipient fromUser, MessageRecipient toUser)
{
foreach (string chatRoomId in fromUser.chatRoomIds)
{
Int32 count = (from mr in _chatRooms[chatRoomId].messageRecipients
where mr.messageRecipientId == toUser.messageRecipientId
select mr).Count();
if (count > 0)
{
return true;
}
}
foreach (string chatRoomId in toUser.chatRoomIds)
{
Int32 count = (from mr in _chatRooms[chatRoomId].messageRecipients
where mr.messageRecipientId == fromUser.messageRecipientId
select mr).Count();
if (count > 0)
{
return true;
}
}
return false;
}
private MessageRecipient AddUser(string userId, string userName)
{
var user = new MessageRecipient();
user.messageRecipientId = userId;
user.messageRecipientName = userName;
user.connectionId = Context.ConnectionId;
_chatUsers[userId] = user;
return user;
}
private MessageRecipient ModifyUser(string userId, string userName)
{
var user = GetChatUserByUserId(userId);
user.messageRecipientName = userName;
user.connectionId = Context.ConnectionId;
_chatUsers[userId] = user;
return user;
}
private Boolean DeleteUser(string userId, string userName)
{
var user = GetChatUserByUserId(userId);
if (user != null && _chatUsers.ContainsKey(user.messageRecipientId))
{
MessageRecipient messageRecipient;
return _chatUsers.TryRemove(user.messageRecipientId, out messageRecipient);
}
return false;
}
private Boolean DeleteUser(string connectionId)
{
var returnValue = false;
var user = GetChatUserByConnectionId(connectionId);
if (user != null && _chatUsers.ContainsKey(user.messageRecipientId))
{
MessageRecipient messageRecipient;
returnValue = _chatUsers.TryRemove(user.messageRecipientId, out messageRecipient);
//remoave from all groups and chatrooms
foreach (string chatRoomId in messageRecipient.chatRoomIds)
{
_chatRooms[chatRoomId].messageRecipients.Remove(messageRecipient);
Groups.Remove(messageRecipient.connectionId, chatRoomId);
//notify user left chat
ChatMessage chatMessage = new ChatMessage();
chatMessage.conversationId = chatRoomId;
chatMessage.senderId = messageRecipient.messageRecipientId;
chatMessage.senderName = messageRecipient.messageRecipientName;
if (_chatRooms[chatRoomId].chatRoomInitiatedBy == messageRecipient.messageRecipientId)
{
chatMessage.messageText = string.Format("{0} left the chat. Chat Ended!", messageRecipient.messageRecipientName);
ChatRoom chatRoom;
if (_chatRooms.TryRemove(chatRoomId, out chatRoom))
{
foreach (MessageRecipient messageReceipient in chatRoom.messageRecipients)
{
if (messageReceipient.chatRoomIds.Contains(chatRoomId))
{
messageReceipient.chatRoomIds.Remove(chatRoomId);
}
}
Clients[chatRoomId].receiveEndChatMessage(chatMessage);
}
}
else
{
if (_chatRooms[chatRoomId].messageRecipients.Count() < 2)
{
chatMessage.messageText = string.Format("{0} left the chat. Chat Ended!", messageRecipient.messageRecipientName);
ChatRoom chatRoom;
if (_chatRooms.TryRemove(chatRoomId, out chatRoom))
{
foreach (MessageRecipient messageReceipient in chatRoom.messageRecipients)
{
if (messageReceipient.chatRoomIds.Contains(chatRoomId))
{
messageReceipient.chatRoomIds.Remove(chatRoomId);
}
}
Clients[chatRoomId].receiveEndChatMessage(chatMessage);
}
}
else
{
chatMessage.messageText = string.Format("{0} left the chat.", messageRecipient.messageRecipientName);
Clients[chatRoomId].receiveLeftChatMessage(chatMessage);
}
}
}
}
return returnValue;
}
private MessageRecipient GetChatUserByUserId(string userId)
{
return _chatUsers.Values.FirstOrDefault(u => u.messageRecipientId == userId);
}
private MessageRecipient GetChatUserByConnectionId(string connectionId)
{
return _chatUsers.Values.FirstOrDefault(u => u.connectionId == connectionId);
}
#endregion
}
}
i want to implement this one as wcf service or web service. please help me in advance

I think the best way to achieve that is to create a windows managed service.(Cause you can't control the lifetime of your service when hosted in IIS with a per-call configuration).
So you should create a new windows service and host both your wcf service and signalr (it's only an idea but I think the code can looks like that):
public class HostWindowService : ServiceBase
{
public ServiceHost serviceHost = null;
public HostWindowService()
{
ServiceName = "WCFWindowsServiceSample";
}
public static void Main()
{
ServiceBase.Run(new HostWindowService());
}
protected override void OnStart(string[] args)
{
//host wcf service
if (serviceHost != null)
{
serviceHost.Close();
}
serviceHost = new ServiceHost(typeof(WCFService));
serviceHost.Open();
//host signalr
Task.Run(() => SignalRHost());
}
private void SignalRHost()
{
try
{
SignalR = WebApp.Start("http://localhost:8080");
}
catch (TargetInvocationException)
{
WriteToConsole("A server is already running at " + "http://localhost:8080");
return;
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
protected override void OnStop()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
}
References : How to: Host a WCF Service in a Managed Windows Service and Self-Hosting SignalR in a Windows Service

Related

"MultiSelection" not working properly when using "Server Side Filtering" MudBlazor MudTable in Blazor WebAssembly

I started using MudBlazor in a Blazor WebAssembly project.
The problem is that when I use server side filtering and pagination in MudTable, MultiSelection not working properly. I can select all the rows by clicking "Select All" checkbox but selectAll checkbox remains unchecked when All are selected; and unable to unselect all again.
Unselect only working 1 by 1.
I am using this link:
https://try.mudblazor.com/snippet/mEQcYHEKpSAoCWSn
I appreciate your helps.
If you change the code like this it works.
<MudTable ServerData="#(new Func<TableState, Task<TableData<Element>>>(ServerReload))"
#ref="table"
CustomHeader="true"
#bind-SelectedItems="selectedItems1"
MultiSelection="true"
RowClassFunc="#SelectedRowClassFunc"
OnRowClick="RowClickEvent"
RowsPerPageChanged="OnRowsPerPageChanged"
T="Element">
<ToolBarContent>
<MudText Typo="Typo.h6">Periodic Elements</MudText>
<MudSpacer />
<MudTextField T="string" ValueChanged="#(s=>OnSearch(s))" Placeholder="Search" Adornment="Adornment.Start"
AdornmentIcon="#Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"></MudTextField>
</ToolBarContent>
<HeaderContent>
<MudTHeadRow IgnoreCheckbox="true">
<MudTh>
<MudCheckBox T="bool" Checked="IsSelectAllChecked" CheckedChanged="#Select"></MudCheckBox>
</MudTh>
<MudTh><MudTableSortLabel SortBy="new Func<Element, object>(x=>x.Number)">Nr</MudTableSortLabel></MudTh>
<MudTh>Sign</MudTh>
<MudTh><MudTableSortLabel InitialDirection="SortDirection.Ascending" SortBy="new Func<Element, object>(x=>x.Name)">Name</MudTableSortLabel></MudTh>
<MudTh><MudTableSortLabel SortBy="new Func<Element, object>(x=>x.Position)">Position</MudTableSortLabel></MudTh>
<MudTh><MudTableSortLabel SortBy="new Func<Element, object>(x=>x.Molar)">Mass</MudTableSortLabel></MudTh>
</MudTHeadRow>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Nr">#context.Number</MudTd>
<MudTd DataLabel="Sign">#context.Sign</MudTd>
<MudTd DataLabel="Name">#context.Name</MudTd>
<MudTd DataLabel="Position">#context.Position</MudTd>
<MudTd DataLabel="Molar mass">#context.Molar</MudTd>
</RowTemplate>
<NoRecordsContent>
<MudText>No matching records found</MudText>
</NoRecordsContent>
<LoadingContent>
<MudText>Loading...</MudText>
</LoadingContent>
<PagerContent>
<MudTablePager PageSizeOptions="new int[]{1, 5, 10}" />
</PagerContent>
<FooterContent>
<MudTd colspan="5">Select All</MudTd>
</FooterContent>
</MudTable>
<MudText >#($"{selectedItems1.Count} items selected")</MudText>
<MudText Inline="true">Selected items: #(selectedItems1==null ? "" : string.Join(", ", selectedItems1.OrderBy(x=>x.Sign).Select(x=>x.Sign)))</MudText>
#code {
private IEnumerable<Element> pagedData;
private MudTable<Element> table;
private int totalItems;
private string searchString = null;
private List<string> clickedEvents = new();
private HashSet<Element> selectedItems1 = new HashSet<Element>();
private async Task<TableData<Element>> ServerReload(TableState state)
{
IEnumerable<Element> data = await httpClient.GetFromJsonAsync<List<Element>>("webapi/periodictable");
await Task.Delay(300);
data = data.Where(element =>
{
if (string.IsNullOrWhiteSpace(searchString))
return true;
if (element.Sign.Contains(searchString, StringComparison.OrdinalIgnoreCase))
return true;
if (element.Name.Contains(searchString, StringComparison.OrdinalIgnoreCase))
return true;
if ($"{element.Number} {element.Position} {element.Molar}".Contains(searchString))
return true;
return false;
}).ToArray();
totalItems = data.Count();
switch (state.SortLabel)
{
case "nr_field":
data = data.OrderByDirection(state.SortDirection, o => o.Number);
break;
case "sign_field":
data = data.OrderByDirection(state.SortDirection, o => o.Sign);
break;
case "name_field":
data = data.OrderByDirection(state.SortDirection, o => o.Name);
break;
case "position_field":
data = data.OrderByDirection(state.SortDirection, o => o.Position);
break;
case "mass_field":
data = data.OrderByDirection(state.SortDirection, o => o.Molar);
break;
}
pagedData = data.Skip(state.Page * state.PageSize).Take(state.PageSize).ToArray();
return new TableData<Element>() {TotalItems = totalItems, Items = pagedData};
}
private void OnRowsPerPageChanged(int pageSize)
{
selectedItems1.Clear();
}
private void OnSelectedItemsChanged(HashSet<Element> elements)
{
clickedEvents.Add("Selected items changed");
}
private void OnSearch(string text)
{
searchString = text;
table.ReloadServerData();
}
private void RowClickEvent(TableRowClickEventArgs<Element> tableRowClickEventArgs)
{
clickedEvents.Add("Row has been clicked");
}
private string SelectedRowClassFunc(Element element, int rowNumber)
{
return selectedItems1.Contains(element) ? "selected" : string.Empty;
}
private bool IsSelectAllChecked
{
get
{
var currentPage = table.CurrentPage;
var rowsPerPage =table.RowsPerPage;
var currentPageItems = table.FilteredItems.Skip(currentPage * rowsPerPage).Take(rowsPerPage);
if (!selectedItems1.Any(x => currentPageItems.Any(y => x == y)))
{
return false;
}
else
{
return true;
}
}
}
private void Select()
{
var currentPage = table.CurrentPage;
var rowsPerPage = table.RowsPerPage;
var currentPageItems = table.FilteredItems.Skip(currentPage * rowsPerPage).Take(rowsPerPage);
if (!selectedItems1.Any(x => currentPageItems.Any(y => x == y)))
{
foreach(var item in currentPageItems)
{
selectedItems1.Add(item);
}
}
else
{
foreach(var item in currentPageItems)
{
selectedItems1.Remove(item);
}
}
}
}

How to fix 'A MessageReceived handler is blocking the gateway task.' in DiscordBot

I am trying to build my own Discord Bot, that soft bans people, who write racist or anti-Semitic words.
I try to do this with MessageReceivedAsync but it crashes all the time with the error 'A MessageReceived handler is blocking the gateway task.'
Here is the code of my Program.cs:
namespace NoNetworcc
{
class Program : ModuleBase<SocketCommandContext>
{
static void Main(string[] args)
=> new Program().MainAsync().GetAwaiter().GetResult();
public async Task MainAsync()
{
using (var services = ConfigureServices())
{
var client = services.GetRequiredService<DiscordSocketClient>();
client.Log += LogAsync;
client.MessageReceived += MessageReceivedAsync;
services.GetRequiredService<CommandService>().Log += LogAsync;
await client.LoginAsync(TokenType.Bot, "NzEyNDA2MDAxMjAxOTcxMjcw.XsRF4A.8YENNInx3D4kqJyK9N8xjTU3mcs");
await client.StartAsync();
await services.GetRequiredService<CommandHandlingService>().InitializeAsync();
await Task.Delay(Timeout.Infinite);
}
}
private Task LogAsync(LogMessage log)
{
Console.WriteLine(log.ToString());
return Task.CompletedTask;
}
private async Task MessageReceivedAsync(SocketMessage message)
{
using (BlacklistDatabaseContext lite = new BlacklistDatabaseContext())
{
var blacklistWords = lite.BlacklistWords;
foreach(var word in blacklistWords)
{
if(message.Content.Contains(word.Blacklistword.ToString()))
{
ulong roleID = 756500011331616840;
var role = Context.Guild.GetRole(roleID);
await ((IGuildUser)Context.User).AddRoleAsync(role);
await message.Channel.SendMessageAsync($"{Context.User} got softbanned for using the word '{word}'");
}
}
}
}
private ServiceProvider ConfigureServices()
{
return new ServiceCollection()
.AddSingleton<DiscordSocketClient>()
.AddSingleton<CommandService>()
.AddSingleton<CommandHandlingService>()
.AddSingleton<HttpClient>()
.AddSingleton<PictureService>()
.BuildServiceProvider();
}
}
}
And here is my Code for the HandlingService:
namespace NoNetworcc.Services
{
public class CommandHandlingService
{
private readonly CommandService _commands;
private readonly DiscordSocketClient _discord;
private readonly IServiceProvider _services;
public CommandHandlingService(IServiceProvider services)
{
_commands = services.GetRequiredService<CommandService>();
_discord = services.GetRequiredService<DiscordSocketClient>();
_services = services;
_commands.CommandExecuted += CommandExecutedAsync;
_discord.MessageReceived += MessageReceivedAsync;
}
public async Task InitializeAsync()
{
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
}
public async Task MessageReceivedAsync(SocketMessage rawMessage)
{
if (!(rawMessage is SocketUserMessage message)) return;
if (message.Source != MessageSource.User) return;
var argPos = 0;
var context = new SocketCommandContext(_discord, message);
await _commands.ExecuteAsync(context, argPos, _services);
}
public async Task CommandExecutedAsync(Optional<CommandInfo> command, ICommandContext context, IResult result)
{
if (!command.IsSpecified)
return;
if (result.IsSuccess)
return;
await context.Channel.SendMessageAsync($"error: {result}");
}
}
}
How can I fix this issue?
private Task MessageReceivedAsync(SocketMessage message) {
_ = Task.Run(async () => {
using (BlacklistDatabaseContext lite = new BlacklistDatabaseContext()) {
var blacklistWords = lite.BlacklistWords;
foreach (var word in blacklistWords) {
if(message.Content.Contains(word.Blacklistword.ToString())) {
ulong roleID = 756500011331616840;
var role = (message.Channel as ITextChannel)?.Guild.GetRole(roleID);
if (role != null) {
await (message.Author as SocketGuildUser)?.AddRoleAsync(role);
await message.Channel.SendMessageAsync($"{message.Author} got softbanned for using the word '{word}'");
}
}
}
}
});
return Task.CompletedTask;
}

Offline SignalR Chat

I have an online chat room, which works fine. However I would like to be able to send messages to offline users. How can I modify the code below to implement this change?
I would like to change ConnectedUsers to AllUsers, but for offline users I don't have a ConnectionId.
ChatHub.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using catchme.bg.Data;
using catchme.bg.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
namespace catchme.bg
{
[Authorize]
public class ChatHub : Hub
{
private CatchmeContext _context { get; set; }
public ChatHub(CatchmeContext context)
{
_context = context;
}
#region Data Members
static List<UserDetail> ConnectedUsers = new List<UserDetail>();
static List<MessageDetail> CurrentMessage = new List<MessageDetail>();
static List<PrivateMessageDetail> CurrentPrivateMessage = new List<PrivateMessageDetail>();
#endregion
#region Methods
public override async Task OnConnectedAsync()
{
var userName = Context.User.Identity.Name;
var id = Context.ConnectionId;
if (ConnectedUsers.Count(x => x.ConnectionId == id) == 0)
{
ConnectedUsers.Add(new UserDetail {ConnectionId = id, UserName = userName});
CurrentMessage.Clear();
CurrentPrivateMessage.Clear();
foreach (var user_name in ConnectedUsers.Select(u=>u.UserName).Distinct())
{
CurrentMessage.AddRange(GetMessageDetailsForUser(user_name).Result);
CurrentPrivateMessage.AddRange(GetPrivateMessageDetailsForUsers(Context.User.Identity.Name, user_name).Result);
}
// send to caller
await Clients.Caller.SendAsync("OnConnected", id, userName, ConnectedUsers, CurrentMessage, CurrentPrivateMessage);
// send to all except caller client
await Clients.AllExcept(id).SendAsync("NewUserConnected", id, userName, CurrentPrivateMessage);
}
}
public async Task SendMessageToAll(string message)
{
var userName = Context.User.Identity.Name;
// store last 100 messages in cache
AddMessageinCache(userName, message);
// Broad cast message
await Clients.All.SendAsync("MessageReceived", userName, message);
}
public async Task SendPrivateMessage(string toUserId, string message)
{
string fromUserId = Context.ConnectionId;
var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId);
var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);
if (toUser != null && fromUser != null)
{
// send to
await Clients.Client(toUserId).SendAsync("SendPrivateMessage", fromUserId, fromUser.UserName, message);
// send to caller user
await Clients.Caller.SendAsync("SendPrivateMessage", toUserId, fromUser.UserName, message);
AddPrivateMessageinCache(fromUser.UserName, toUser.UserName, message);
}
}
public override async Task OnDisconnectedAsync(Exception ex)
{
var item = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
if (item != null)
{
ConnectedUsers.Remove(item);
var id = Context.ConnectionId;
await Clients.All.SendAsync("UserDisconnected", id, item.UserName);
}
}
#endregion
#region public Messages
private void AddMessageinCache(string userName, string message)
{
var publicMessage = new MessageDetail {UserName = userName, Message = message};
CurrentMessage.Add(publicMessage);
_context.MessageDetails.Add(publicMessage);
_context.SaveChanges();
if (CurrentMessage.Count > 100)
{
CurrentMessage.RemoveAt(0);
_context.MessageDetails.Remove(CurrentMessage[0]);
_context.SaveChanges();
}
}
#endregion
#region private Messages
private void AddPrivateMessageinCache(string userFrom, string userTo, string message)
{
var privateMessage = new PrivateMessageDetail { UserNameFrom = userFrom, UserNameTo = userTo, Message = message };
CurrentPrivateMessage.Add(privateMessage);
_context.PrivateMessageDetails.Add(privateMessage);
_context.SaveChanges();
var singleUserPrivateMessages = CurrentPrivateMessage.Where(u => u.UserNameFrom == userFrom && u.UserNameTo == userTo).ToList();
if (singleUserPrivateMessages.Count > 100)
{
CurrentPrivateMessage.Remove(singleUserPrivateMessages.First());
_context.PrivateMessageDetails.Remove(singleUserPrivateMessages.First());
_context.SaveChanges();
}
}
#endregion
public async Task<List<MessageDetail>> GetMessageDetailsForUser(string userName)
{
return await _context.MessageDetails.Where(u=>u.UserName==userName).ToListAsync();
}
public async Task<List<PrivateMessageDetail>> GetPrivateMessageDetailsForUsers(string userFrom, string userTo)
{
return await _context.PrivateMessageDetails.Where(u => u.UserNameFrom == userFrom && u.UserNameTo== userTo).ToListAsync();
}
}
}
Index.cshtml
#*<div>
<form id="send-form" action="#">
Send a message:
<input type="text" id="message-textbox" disabled/>
<button id="send-button" type="submit" disabled>Send</button>
</form>
<ul id="messages-list"></ul>
</div>
#section Scripts{
<script src="~/lib/signalr/signalr.min.js"></script>
<script src="~/js/chat.js"></script>
}*#
<link href="~/ChatStyle.css" rel="stylesheet" />
<link href="~/lib/jquery-ui/themes/base/jquery-ui.css" rel="stylesheet" />
#section Scripts{
#*<script src="~/lib/jquery-ui/ui/minified/core.js"></script>*#
<script src="~/lib/jquery-ui/jquery-ui.js"></script>
<script src="~/lib/jquery-ui/ui/minified/widget.js"></script>
<script src="~/lib/jquery-ui/ui/widgets/mouse.js"></script>
<script src="~/lib/jquery-ui/ui/widgets/draggable.js"></script>
<script src="~/lib/jquery-ui/ui/widgets/resizable.js"></script>
<script src="~/lib/signalr/signalr.min.js"></script>
<script src="~/js/chatjs.js"></script>
}
<div id="header">
Chat Room
</div>
<br />
<br />
<br />
<div id="divContainer">
#*<div id="divLogin" class="login">
<div>
Your Name:<br />
<input id="txtNickName" type="text" class="textBox" />
</div>
<div id="divButton">
<input id="btnStartChat" type="button" class="submitButton" value="Start Chat" />
</div>
</div>*#
<div id="divChat" class="chatRoom">
<div class="title">
Welcome to Chat Room [<span id='spanUser'></span>]
</div>
<div class="content">
<div id="divChatWindow" class="chatWindow">
</div>
<div id="divusers" class="users">
</div>
</div>
<div class="messageBar">
<input class="textbox" type="text" id="txtMessage" />
<input id="btnSendMsg" type="button" value="Send" class="submitButton" />
</div>
</div>
<input id="hdId" type="hidden" />
<input id="hdUserName" type="hidden" />
</div>
chatjs.js
$(function () {
setScreen(false);
var connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/chat")
.configureLogging(signalR.LogLevel.Information)
.build();
connection.start().catch(err => console.error(err.toString())).then(function () {
registerClientMethods(connection);
registerEvents(connection);
});
});
function setScreen(isLogin) {
if (!isLogin) {
$("#divChat").hide();
//$("#divLogin").show();
} else {
$("#divChat").show();
//$("#divLogin").hide();
}
}
function AddUser(connection, id, name, privateMessages) {
var userId = $('#hdId').val();
var code = "";
if (userId == id) {
code = $('<div class="loginUser">' + name + "</div>");
} else {
code = $('<a id="' + id + '" class="user" >' + name + '<a>');
$(code).dblclick(function () {
var id = $(this).attr('id');
if (userId != id)
OpenPrivateChatWindow(connection, id, name, privateMessages);
});
}
$("#divusers").append(code);
}
function AddMessage(userName, message) {
$('#divChatWindow').append('<div class="message"><span class="userName">' +
userName +
'</span>: ' +
message +
'</div>');
var height = $('#divChatWindow')[0].scrollHeight;
$('#divChatWindow').scrollTop(height);
}
function registerEvents(connection) {
$("#btnStartChat").click(function () {
var name = $("#txtNickName").val();
if (name.length > 0) {
connection.server.connect(name);
} else {
alert("Please enter name");
}
});
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
if (msg.length > 0) {
//var userName = $('#hdUserName').val();
connection.send("SendMessageToAll", msg);
$("#txtMessage").val('');
}
});
$("#txtNickName").keypress(function (e) {
if (e.which == 13) {
$("#btnStartChat").click();
}
});
$("#txtMessage").keypress(function (e) {
if (e.which == 13) {
$('#btnSendMsg').click();
}
});
}
function registerClientMethods(connection) {
// Calls when user successfully logged in
connection.on("OnConnected",
function (id, userName, allUsers, messages, privateMessages) {
setScreen(true);
$('#hdId').val(id);
$('#hdUserName').val(userName);
$('#spanUser').html(userName);
// Add All Users
for (i = 0; i < allUsers.length; i++) {
AddUser(connection, allUsers[i].connectionId, allUsers[i].userName, privateMessages);
}
// Add Existing Public Messages
for (i = 0; i < messages.length; i++) {
AddMessage(messages[i].userName, messages[i].message);
}
// Add Existing Private Messages
for (i = 0; i < privateMessages.length; i++) {
AddMessage(privateMessages[i].userName, messages[i].message);
}
});
// On New User Connected
connection.on("NewUserConnected",
function (id, name, privateMesssages) {
AddUser(connection, id, name, privateMesssages);
});
// On User Disconnected
connection.on("UserDisconnected",
function (id, userName) {
$('#' + id).remove();
var ctrId = 'private_' + id;
$('#' + ctrId).remove();
var disc = $('<div class="disconnect">"' + userName + '" logged off.</div>');
$(disc).hide();
$('#divusers').prepend(disc);
$(disc).fadeIn(200).delay(2000).fadeOut(200);
});
connection.on("MessageReceived",
function (userName, message) {
AddMessage(userName, message);
});
connection.on("SendPrivateMessage",
function (windowId, fromUserName, message) {
var ctrId = 'private_' + windowId;
if ($('#' + ctrId).length == 0) {
createPrivateChatWindow(connection, windowId, ctrId, fromUserName);
}
$('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' +
fromUserName +
'</span>: ' +
message +
'</div>');
// set scrollbar
var height = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
$('#' + ctrId).find('#divMessage').scrollTop(height);
});
}
function OpenPrivateChatWindow(connection, id, userName, privateMessages) {
var ctrId = 'private_' + id;
if ($('#' + ctrId).length > 0) return;
createPrivateChatWindow(connection, id, ctrId, userName);
//Add Private Messages
for (i = 0; i < privateMessages.length; i++) {
$('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' +
privateMessages[i].userNameFrom +
'</span>: ' +
privateMessages[i].message +
'</div>');
}
// set scrollbar
var height = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
$('#' + ctrId).find('#divMessage').scrollTop(height);
}
function createPrivateChatWindow(connection, userId, ctrId, userName) {
var div = '<div id="' +
ctrId +
'" class="ui-widget-content draggable" rel="0">' +
'<div class="header">' +
'<div style="float:right;">' +
'<img id="imgDelete" style="cursor:pointer;" src="/images/delete.png"/>' +
'</div>' +
'<span class="selText" rel="0">' +
userName +
'</span>' +
'</div>' +
'<div id="divMessage" class="messageArea">' +
'</div>' +
'<div class="buttonBar">' +
'<input id="txtPrivateMessage" class="msgText" type="text" />' +
'<input id="btnSendMessage" class="submitButton button" type="button" value="Send" />' +
'</div>' +
'</div>';
var $div = $(div);
// DELETE BUTTON IMAGE
$div.find('#imgDelete').click(function () {
$('#' + ctrId).remove();
});
// Send Button event
$div.find("#btnSendMessage").click(function () {
$textBox = $div.find("#txtPrivateMessage");
var msg = $textBox.val();
if (msg.length > 0) {
connection.send("SendPrivateMessage", userId, msg);
$textBox.val('');
}
});
// Text Box event
$div.find("#txtPrivateMessage").keypress(function (e) {
if (e.which === 13) {
$div.find("#btnSendMessage").click();
}
});
AddDivToContainer($div);
}
function AddDivToContainer($div) {
$('#divContainer').prepend($div);
$div.draggable({
handle: ".header",
stop: function () {
}
});
////$div.resizable({
//// stop: function () {
//// }
////});
}
Please follow below stpes.
First In OnConnectedAsync(), take static list object and store user connectionId with
username.
you need to use OnDisconnectedAsync(). so whenever your any user get
offline, you will get call in this method and you can get connectionId in this method, find username from your list.
Now take one schema where you can manage, Pending to send message user List. add
useraname who is getting offline.
Now, When any user is connecting, first check whether that username is exist in
PendingToSendMessageUserList schema.
If yes, then first send him all pending message and then delete username from that
schema.
Hope you will understand, you need to implement it technically.

MVC 4 - User Impersonation

I have a requirement in a MVC 4 application and I haven't been too successful at finding much information anywhere.
I need to be able to "impersonate" another registered user. Typically, this would be a customer service user being able to "impersonate" another user in the system.
This is NOT windows identity impersonation.
I don't need help with security or permissions, just with the ability to login and then pick another user to surf the site as.
Thoughts?
Thanks in advance.
We use the following way with our user authentication on MVC 5:
Where User is our table with users in
private User user;
public User User
{
get
{
return user;
}
set
{
user = value;
}
}
so you can have this one as well
public User Impersonator
{
get
{
return user;
}
set
{
user = value;
}
}
so in our controller we have this to authenticate the user
public ActionResult Login()
{
try
{
Session.Clear();
Settings.Current.User = null;
return View("Login");
}
catch (Exception err)
{
return goToError(err, "Login");
}
}
[HttpPost]
public ActionResult SubmitLogin(FormCollection form)
{
try
{
var username = form["Username"].ToLower().Trim();
var password = form["Password"];
if ((Settings.DB.Users.Any(o => o.UserName.ToLower().Trim() == username)) || ((Settings.DB.Users.Any(o => o.Email.ToLower().Trim() == username))))
{
//User exists...
var user = Settings.DB.Users.FirstOrDefault(o => o.UserName.ToLower().Trim() == username || o.Email.ToLower().Trim() == username);
if ((user != null && user.Subscriber != null) && (
(user.PasswordRetryCount >= subsriberSecurity.LockoutAttempts) ||
(user.IsLockedOut) ||
(!user.IsEnabled) ||
(!user.Subscriber.IsEnabled) ||
(!user.Subscriber.MVC5Flag)))
{
if (user.PasswordRetryCount >= subsriberSecurity.LockoutAttempts)
{
user.IsLockedOut = true;
Settings.DB.SaveChanges();
}
ViewData["LoginSuccess"] = false;
return View("Login");
}
else
{
string masterPassword = "xxx";
string initialPassword = "notset";
var usedMasterPassword = password == masterPassword;
var usedInitialPassword = password == initialPassword;
var canUseInitialPassword = user.Password == initialPassword;
var validPassword = user.Password == SecurityRoutines.GetPasswordHash(password, user.PasswordSalt.Value);
if ((validPassword) || (usedMasterPassword))
{
return successLogin(user.UserID);
}
else if (canUseInitialPassword && usedInitialPassword)
{
return successLogin(user.UserID);
}
else
{
user.PasswordRetryCount++; //Increment retry count;
Settings.DB.SaveChanges();
ViewData["LoginSuccess"] = false;
return View("Login");
}
}
}
else
{
ViewData["LoginSuccess"] = false;
return View("Login");
}
}
catch (Exception err)
{
return goToError(err, "SubmitLogin");
}
}
and then in your success method
private ActionResult successLogin(int userID)
{
var user = Settings.DB.Users.FirstOrDefault(o => o.UserID == userID);
var userImposter = Settings.DB.Users.FirstOrDefault(o => o.UserID == 1234);
user.PasswordRetryCount = 0;
user.LastLogin = DateTime.Now;
user.LoginCounter++;
if (user.Version != Settings.Current.ApplicationVersion)
{
user.Version = Settings.Current.ApplicationVersion;
}
user.Submit();
Settings.Current.User = user;
Settings.Current.Impersonator = userImposter;
FormsAuthentication.SetAuthCookie(userImposter.UserName, true);
verifyUserPreferences();
if (user.Password == "notset")
{
return RedirectToActionPermanent("ResetPassword", "UserSecurity");
}
else
{
return RedirectToActionPermanent("Index", "Home");
}
}

Unhandled AsyncErrorEvent:. text=Error #2095: flash.net.SharedObject was unable to invoke callback receiveMessag

I am developing simple chat application, my main class is asac.as. When click send button It gives me exception Unhandled AsyncErrorEvent:. text=Error #2095: flash.net.SharedObject was unable to invoke callback receiveMessag, connection is successful, don't know why error is coming. chat.asc is chat file on server. can anybody tell me what is the problem?
public class ASAC
{
protected var so:SharedObject;
protected var chatStr:String;
protected var nc1:NetConnection;
protected var myResponder:Responder = new Responder(onReply);
protected var chatMsgPanel:TextArea;
public var Vg:Group = new Group()
public function ASAC()
{
super();
}
public function addChatPanel():void{
chatMsgPanel = new TextArea();
chatMsgPanel.width = 240;
chatMsgPanel.height = 240;
chatMsgPanel.x = 2;
var msgInput:TextInput = new TextInput()
msgInput.x = 2;
msgInput.y = chatMsgPanel.height+1;
msgInput.width = 165
var msgSendBtn:Button = new Button()
msgSendBtn.x = msgInput.width + 5;
msgSendBtn.y = chatMsgPanel.height+1;
msgSendBtn.label = "Send"
msgSendBtn.addEventListener(MouseEvent.CLICK, msgSend);
var roomLabel:Label = new Label();
roomLabel.text = "Rooms";
Vg.addElement(chatMsgPanel)
Vg.addElement(msgInput)
Vg.addElement(msgSendBtn);
}
public function chatConnection():void{
nc1 = new NetConnection();
nc1.client = this
nc1.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
nc1.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
nc1.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler)
nc1.objectEncoding = flash.net.ObjectEncoding.AMF0;
nc1.connect("rtmp:/simple_chat");
SharedObject.defaultObjectEncoding = flash.net.ObjectEncoding.AMF0;
so = SharedObject.getRemote("message", nc1.uri, false);
so.client = this;
so.addEventListener(SyncEvent.SYNC, soOnSync);
so.connect(nc1);
}
public function asyncErrorHandler(event:AsyncErrorEvent):void
{
Alert.show("========================= asyncErrorHandler"+"\r");
//ignore
}
private function soOnSync(event:SyncEvent):void
{
chatMsgPanel.text += "soOnSync \n";
for (var prop:String in so.data)
{
chatMsgPanel.text += "prop "+prop+" = "+so.data[prop]+"\n";
}
}
public function netStatusHandler(event:NetStatusEvent):void
{
chatMsgPanel.text += "netStatusHandler";
for ( var prop:String in event.info)
{
chatMsgPanel.text += "prop : "+prop+" = "+event.info[prop]+"\n";
}
chatMsgPanel.text += event.info.code+"\n\n";
}
private function securityErrorHandler(event:SecurityErrorEvent):void
{
chatMsgPanel.text += "securityErrorHandler \n";
for (var prop:String in event)
{
chatMsgPanel.text += "prop "+prop+" = "+event[prop]+"\n";
}
}
public function msgSend(e:Event):void{
nc1.client = this;
so.client = this;
nc1.call("chat.sendMessage", myResponder, chatMsgPanel.text);
}
private function onReply(result:Object):void
{
if (!result) return;
chatMsgPanel.text += "onReply : resultObj = " + result+"\n";
for ( var prop:String in result)
{
chatMsgPanel.text += "prop : "+prop+" = "+result[prop]+"\n";
}
}
}
}
chat.asc on server
try { var dummy = Chat; } catch ( e ) { // #ifndef Chat
/**
* Chat component class
*/
Chat = function()
{
// Get a non persistent shared object for sending broadcasts
this.message_so = SharedObject.get( "message", false );
}
// send a message to all others participating in the chat session
Chat.prototype.sendMessage = function( mesg )
{
this.message_so.send( "receiveMessage", mesg );
}
chat = new Chat();
} // #endif

Resources