Implement SelectedItem for CarouselViewControl - xamarin.forms

Implement SelectedItem(like on ListView) for CarouselViewControl
tried PositionSelected and PositionSelectedCommand Doesn't work as it gives on position of item selected in the list.
ViewModel Implementation:
private void LoadData(IEnumerable<Model> myCourse)
{
this.Items.Clear();
if (myCourse != null)
{
foreach (var item in myCourse)
{
var itemToAdd = new Model
{
ActiviyId = item.ActiviyId,
};
Device.BeginInvokeOnMainThread(() =>
{
this.Items.Add(itemToAdd);
});
}
}
}
public DelegateCommand<Model> CourseSelectedCommand => new DelegateCommand<Model>(async (Param) => await this.OnCourseItemSelectedCommand(Param));
private async Task OnCourseItemSelectedCommand(Model model)
{
var navigationParams = new NavigationParameters();
navigationParams.Add("ActivityID", model.ActiviyId);
await this.navigationService.NavigateAsync("ModulePage", navigationParams, true, false);
}

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);
}
}
}
}

DbContext remove parent object Id

I've got quite weird problem... Here is what it is... When I'm comparing data from somoe goverment service and checking that last born child in my base is the same like in data from service, after updating parent lastBornChild is loosing connection to parent id and it's updated in db wiht ParentId as NULL.
I know that this code should be written better but I wonder why ef changing my lastBornChild.ParentId to NULL.
public class MyService : IMyService
{
MyService(DataDbContext context)
{
_context = context;
}
private DateTime FindYoungestChild(int parentId)
{
var lastChild = _context.Childs.Where(i => i.Parent.Id == parentId).OrderByDescending(d => d.BirthDate).FirstOrDefault();
if (lastChild == null)
return DateTime.MinValue;
else
return lastChild .BirthDate;
}
public Parent UpdateFamilyHistory(Parent parent)
{
DateTime lastStatusTransDate = FindYoungestChild(parent.Id);
var childs= new List<Child>();
var updateChildList = <some goverment public service response>(d => d.DateTimeCreated > lastStatusTransDate).ToList();
foreach (var item in updateChildList)
{
var newChild = new Child
{
Name = item.Name,
BirthDate = item.BirthDate;
};
childs.Add(newChild );
}
parent.Childs = childs;
_context.Update(parent);
_context.SaveChanges();
return parent;
}
}
Try this:
var childs = new List<Child>();
foreach (var item in updateChildList)
{
var newChild = new Child
{
ParentId = parent.Id,
Name = item.Name,
BirthDate = item.BirthDate
};
childs.Add(newChild);
}
_context.Childs.AddRange(childs);
_context.SaveChanges();

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;
}

Chat application using signalr as wcf service

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

Xamarin Forms - Xamarin Forms Labs Camera on Page Showing Up

Does anyone have an example in Xamarin.Forms of Xamarin.Forms.Labs' Camera function?
I tried to get it working, but it does not seem to work at all.
Here's my code:
public partial class CameraPictureInfoPage : ContentPage
{
public CameraPictureInfoPage ()
{
Image img = new Image ();
this.Appearing += async (s, e) => {
img.Source = await GetPicture (true);
};
this.Content = new StackLayout {
Orientation = StackOrientation.Vertical,
VerticalOptions = LayoutOptions.Center,
WidthRequest = 250,
Padding = 40, Spacing = 10,
Children = {
img
}
};
}
async Task<ImageSource> GetPicture(bool chooseNotTake){
var mediaPicker = DependencyService.Get<IMediaPicker> ();
ImageSource imgSource = null;
if (mediaPicker != null) {
Task<MediaFile> pick;
if (chooseNotTake) {
pick = mediaPicker.TakePhotoAsync (new CameraMediaStorageOptions {
DefaultCamera = CameraDevice.Rear,
MaxPixelDimension = 1024,
});
} else {
pick = mediaPicker.SelectPhotoAsync (new CameraMediaStorageOptions{ MaxPixelDimension = 1024 });
}
await pick.ContinueWith (t => {
if (!t.IsFaulted && !t.IsCanceled) {
var mediaFile = t.Result;
MemoryStream mstr = new MemoryStream ();
mediaFile.Source.CopyTo (mstr);
imgSource = ImageSource.FromStream (() => mstr);
}
return imgSource;
});
}
return imgSource;
}
}
This works for me:
in iOS project in AppDelegate.cs:
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
SetIoc ();
Forms.Init ();
window = new UIWindow (UIScreen.MainScreen.Bounds);
window.RootViewController = App.GetMainPage ().CreateViewController ();
window.MakeKeyAndVisible ();
return true;
}
private void SetIoc ()
{
var resolverContainer = new SimpleContainer ();
resolverContainer.Register<IDevice> (t => AppleDevice.CurrentDevice)
.Register<IDisplay> (t => t.Resolve<IDevice> ().Display)
.Register<IDependencyContainer> (t => resolverContainer);
Resolver.SetResolver (resolverContainer.GetResolver ());
}
In the Forms project:
private async Task<ImageSource> GetPicture(bool chooseNotTake){
var mediaPicker = DependencyService.Get<IMediaPicker> ();
ImageSource imgSource = null;
if (mediaPicker != null) {
Task<MediaFile> pick;
if (!chooseNotTake) {
pick = mediaPicker.TakePhotoAsync (new CameraMediaStorageOptions {
DefaultCamera = CameraDevice.Rear,
MaxPixelDimension = 1024,
});
} else {
pick = mediaPicker.SelectPhotoAsync (new CameraMediaStorageOptions{ MaxPixelDimension = 1024 });
}
await pick.ContinueWith (t => {
if (!t.IsFaulted && !t.IsCanceled) {
var mediaFile = t.Result;
MemoryStream mstr = new MemoryStream();
mediaFile.Source.CopyTo(mstr);
imgSource = ImageSource.FromStream (() => mstr);
}
return imgSource;
}
}
Keep in mind you may need to store the image stream by some other means or it may get garbage-collected prematurely.
To get the picture taker to show up on startup you'll have to avoid async and hook up to Appearing event. In your page's constructor add this:
public class PhotoPage : ContentPage
{
Image img = new Image ();
IMediaPicker picker = null;
Task<MediaFile> task = null;
public PhotoPage ()
{
img.WidthRequest = 60;
img.HeightRequest = 60;
img.BackgroundColor = Color.Silver;
this.Content = new StackLayout {
Orientation = StackOrientation.Vertical,
VerticalOptions = LayoutOptions.Center,
BackgroundColor = Color.Aqua,
WidthRequest = 250,
Padding = 40, Spacing = 10,
Children = {
img,
}
};
this.Appearing += (s, e) => {
picker = DependencyService.Get<IMediaPicker> ();
task = picker.SelectPhotoAsync (new CameraMediaStorageOptions{ MaxPixelDimension = 1024 });
};
Device.StartTimer (TimeSpan.FromMilliseconds (250), () => {
if (task != null) {
if (task.Status == TaskStatus.RanToCompletion) {
Device.BeginInvokeOnMainThread (() => {
img.Source = ImageSource.FromStream (() => task.Result.Source);
});
}
return task.Status != TaskStatus.Canceled
&& task.Status != TaskStatus.Faulted
&& task.Status != TaskStatus.RanToCompletion;
}
return true;
});
}
}

Resources