public ActionResult DeleteProfile(int profileId)
        {
            var success = false;
            var message = "";

            try
            {
                var profile = _repository.Profiles.Find(profileId);
                if (profile != null)
                {
                    profile.Widget    = null;
                    profile.Template  = null;
                    profile.Workgroup = null;
                    profile.Skills.Clear();
                    profile.Schedules.Clear();
                    _repository.SaveChanges();
                    _repository.Profiles.Remove(profile);
                    _repository.SaveChanges();
                    success = true;
                    message = "Profile Deleted Successfully.";
                    ChatServices.UpdateRefreshWatch();
                }
                else
                {
                    message = "Profile not found.";
                }
            }
            catch (Exception e)
            {
                message = e.Message;
            }
            return(Json(new { success, message }));
        }
示例#2
0
 void CheckForScheduleUpdates()
 {
     try
     {
         if (!ScheduleManager.LastUpdatedUtc.HasValue)
         {
             //new Task(ScheduleManager.LoadAllSchedules).Start();
             Task.Run(() => ScheduleManager.LoadAllSchedules());
         }
         else
         {
             var lastServerUpdate = ChatServices.LastScheduleUpdate();
             var hasServerUpdates = lastServerUpdate.HasValue && lastServerUpdate.Value > ScheduleManager.LastUpdatedUtc.Value;
             var newDateToProcess = ScheduleManager.LastUpdatedUtc.Value.AddHours(ScheduleManager.ScheduleDateTimeOffset).Date < DateTime.UtcNow.AddHours(ScheduleManager.ScheduleDateTimeOffset).Date;
             if (hasServerUpdates || newDateToProcess)
             {
                 //new Task(ScheduleManager.LoadAllSchedules).Start();
                 Task.Run(() => ScheduleManager.LoadAllSchedules());
             }
             else
             {
                 if (ScheduleManager.ProfilesToReload.Any())
                 {
                     Task.Run(() => ScheduleManager.UpdateChangedScheduleAvailability());
                 }
             }
         }
     }
     catch (Exception)
     {
     }
 }
示例#3
0
        public VMChat()
        {
            Title        = "ITESHU Chat";
            chatServices = DependencyService.Get <IChatServices>();
            chatServices = new ChatServices();

            Messages     = new ObservableCollection <ChatMessage>();
            WriteMessage = new ChatMessage();

            chatServices.Connect();
            chatServices.JoinRoom(roomName);
            chatServices.OnMessageReceived += (sender, message) =>
            {
                Messages.Add(new ChatMessage {
                    Name = message.Name, Message = message.Message
                });
            };

            SendMessageCommand = new Command(async() =>
            {
                IsBusy = true;
                await chatServices.Send(new ChatMessage {
                    Name = WriteMessage.Name, Message = WriteMessage.Message
                },
                                        roomName);
                WriteMessage.Message = "";
                IsBusy = false;
            });
        }
示例#4
0
        public void Send(string name, string message)
        {
            try
            {
                var connectionId = Context.ConnectionId;

                var chat = ChatServices.WebChats.FirstOrDefault(c => c.ConnectionId == connectionId || (c.PreviousConnectionIds != null && c.PreviousConnectionIds.Contains(connectionId)));
                if (chat != null)
                {
                    if (chat.State != ChatState.Disconnected)
                    {
                        ChatServices.SendMessage(chat, connectionId, name, message);
                    }
                    else
                    {
                        ChatNotFound(message);
                        ChatServices.QueueMessageToAgent(connectionId, message, name);
                    }
                }
                else
                {
                    ChatNotFound(message);
                    ChatServices.QueueMessageToAgent(connectionId, message, name);
                }
            }
            catch (Exception e)
            {
                LoggingService.GetInstance().LogException(e);
            }
        }
示例#5
0
 void PollVisitorMessage(VisitorMessageChat visitorMessage)
 {
     if (ChatServices.VisitorMessageChats.Any(v => v.VisitorMessageId == visitorMessage.VisitorMessageId))
     {
         ChatServices.PollVisitorMessageEvents(visitorMessage);
     }
 }
示例#6
0
 public void SendCustomInfoToAgent(string customInfo)
 {
     try
     {
         var connectionId = Context.ConnectionId;
         var chat         = ChatServices.WebChats.FirstOrDefault(c => c.ConnectionId == connectionId || (c.PreviousConnectionIds != null && c.PreviousConnectionIds.Contains(connectionId)));
         if (chat != null && chat.State != ChatState.Disconnected && !String.IsNullOrWhiteSpace(customInfo))
         {
             if (customInfo.Contains(";"))
             {
                 var customInfoList = customInfo.Split(';');
                 foreach (var customInfoLine in customInfoList)
                 {
                     ChatServices.SendMessage(chat.ParticipantId, customInfoLine);
                 }
             }
             else
             {
                 ChatServices.SendMessage(chat.ParticipantId, customInfo);
             }
         }
     }
     catch (Exception e)
     {
         LoggingService.GetInstance().LogException(e);
     }
 }
示例#7
0
        //GetStatuses
        public JsonResult GetStatuses()
        {
            var success = false;

            try
            {
                var cicStatus     = ChatServices.GetConfig();
                var serviceStatus = ChatServices.IsLicensed();
                var wcbStatus     = cicStatus && serviceStatus;
                var cicName       = ChatServices.GetCicServerName;
                var wcbName       = GetServerIpAddress();
                var port          = ConfigurationManager.AppSettings["WcbServicePort"];
                if (String.IsNullOrWhiteSpace(port))
                {
                    port = "8088";
                }
                if (!cicStatus)
                {
                    ChatServices.AddAlert("Server Error", "Error connecting to CIC server.", 0001);
                }
                if (!serviceStatus)
                {
                    ChatServices.AddAlert("Server Error", "Error connecting to WCB Service.", 0002);
                }
                var serviceName = "http://localhost:" + port;
                success = true;
                return(Json(new { success, cicStatus, cicName, serviceStatus, serviceName, wcbStatus, wcbName }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception)
            {
            }
            return(Json(new { success }, JsonRequestBehavior.AllowGet));
        }
示例#8
0
        private void BtnSend_Click(object sender, RoutedEventArgs e)
        {
            string friend_username = LvFriends.SelectedItem.ToString();
            int    friend_id       = ChatServices.GetIdByUsername(friend_username);

            ChatServices.SendMessage(CurrentUser.Id, friend_id, TbMessage.Text);
            TbMessage.Text = "";
        }
示例#9
0
        public void TestMethod1()
        {
            var httpClientManager = new Mock <IHttpClientManager>();

            var chatServices = new ChatServices(httpClientManager.Object);
            var chatDto      = chatServices.GetChats("123", 1, 1);

            Assert.IsNotNull(chatDto);
        }
示例#10
0
 private void BtnSend_Click(object sender, EventArgs e)
 {
     ChatServices.SendMessage(TbMessage.Text, ((Users)LbUsers.SelectedItem).id);
     RtbChat.AppendText(DateTime.Now.ToString() + "  ");
     RtbChat.AppendText($"to {((Users)LbUsers.SelectedItem).username}" + "\r\n");
     RtbChat.AppendText($"{TbMessage.Text}" + "\r\n");
     TbMessage.Text = "";
     TbMessage.Focus();
 }
示例#11
0
        public async Task <ListenGroup> GetGroupAsync(ChatServices service, string id)
        {
            var result = await table.ExecuteAsync(
                TableOperation.Retrieve <ListenGroup>(
                    ListenGroup.GetPartitionKey(ListenGroup.GetId(service, id)),
                    ListenGroup.GetId(service, id)));

            return(result.Result as ListenGroup);
        }
示例#12
0
        public static string GetId(ChatServices service, string serviceId)
        {
            switch (service)
            {
            case ChatServices.Telegram:
                return($"{Prefix.Telegram}|{serviceId}");

            default: throw new NotSupportedException();
            }
        }
示例#13
0
        public void Typing(bool isTyping)
        {
            var connectionId = Context.ConnectionId;
            var chat         = ChatServices.WebChats.FirstOrDefault(c => c.ConnectionId == connectionId || (c.PreviousConnectionIds != null && c.PreviousConnectionIds.Contains(connectionId)));

            if (chat != null)
            {
                ChatServices.UpdateIndicator(chat.ParticipantId, isTyping);
            }
        }
示例#14
0
 public override Task OnDisconnected(bool stopCalled)
 {
     try
     {
         var connectionId = Context.ConnectionId;
         LoggingService.GetInstance().LogNote(connectionId + " disconnected from WebChatHub");
         var webChat = ChatServices.WebChats.FirstOrDefault(c => c.ConnectionId == connectionId);
         if (webChat != null && !webChat.DateAnswered.HasValue)
         {
             var keepQueuedChatsAlive = ChatController.KeepQueuedChatsAlive;
             if (keepQueuedChatsAlive)
             {
                 ChatServices.ProcessDisconnect(connectionId);
             }
             else
             {
                 if (webChat.Messages.Any() && ChatController.EnableReloadUnansweredChatHistory())
                 {
                     var unanswered = ChatServices.UnansweredChats.FirstOrDefault(u => u.SessionId == webChat.SessionId);
                     if (unanswered == null)
                     {
                         unanswered = new UnansweredChat
                         {
                             LastUpdated = DateTime.Now,
                             SessionId   = webChat.SessionId,
                             Messages    = webChat.Messages
                         };
                         ChatServices.UnansweredChats.Add(unanswered);
                     }
                     else
                     {
                         foreach (var chatMessage in webChat.Messages)
                         {
                             if (!unanswered.Messages.Any(u => u.Id == chatMessage.Id))
                             {
                                 unanswered.Messages.Add(chatMessage);
                             }
                         }
                         unanswered.LastUpdated = DateTime.Now;
                     }
                 }
                 ChatServices.ProcessDisconnect(connectionId, false, true);
             }
         }
         else
         {
             ChatServices.ProcessDisconnect(connectionId);
         }
     }
     catch (Exception e)
     {
         LoggingService.GetInstance().LogException(e);
     }
     return(base.OnDisconnected(stopCalled));
 }
示例#15
0
        private async void ChangeMessages(object sender, ElapsedEventArgs e)
        {
            Action action = () =>
            {
                string username = LvFriends.SelectedItem.ToString();
                messages           = ChatServices.GetAllMessages(username);
                LvChat.ItemsSource = messages;
            };

            await Task.Run(() => Dispatcher.Invoke(action));
        }
示例#16
0
 public ChatWindow(string userName)
 {
     this.KeyDown      += HandleKeyDown;
     this.SizeToContent = SizeToContent.WidthAndHeight;
     this.userName      = userName;
     this.chatService   = new ChatServices();
     this.InitializeReceiver();
     InitializeComponent();
     this.ChatUsers.PreviewMouseDown += HandleClickOnName;
     this.UserNameLabel.Content       = userName;
     this.PopulateChatRoomContainer();
 }
示例#17
0
        public void ResumeChat()
        {
            var connectionId = Context.ConnectionId;
            var chat         = ChatServices.WebChats.FirstOrDefault(c => c.ConnectionId == connectionId || (c.PreviousConnectionIds != null && c.PreviousConnectionIds.Contains(connectionId)));

            if (chat != null && chat.State == ChatState.Paused)
            {
                chat.IsMinimized = false;
                chat.State       = ChatState.Connected;
                ChatServices.SendCustomSystemMessage(CustomMessageType.ResumedChat, chat.UserName, connectionId, chat);
            }
        }
 public ChatWindow(string userName)
 {
     this.KeyDown += HandleKeyDown;
     this.SizeToContent = SizeToContent.WidthAndHeight;
     this.userName = userName;
     this.chatService = new ChatServices();
     this.InitializeReceiver();
     InitializeComponent();
     this.ChatUsers.PreviewMouseDown += HandleClickOnName;
     this.UserNameLabel.Content = userName;
     this.PopulateChatRoomContainer();
 }
示例#19
0
        public void PauseChat()
        {
            var connectionId = Context.ConnectionId;
            var chat         = ChatServices.WebChats.FirstOrDefault(c => c.ConnectionId == connectionId || (c.PreviousConnectionIds != null && c.PreviousConnectionIds.Contains(connectionId)));

            if (chat != null && chat.DateAnswered.HasValue && chat.State != ChatState.Disconnected)
            {
                chat.IsMinimized = true;
                chat.State       = ChatState.Paused;
                chat.DatePaused  = DateTime.Now;
                ChatServices.SendCustomSystemMessage(CustomMessageType.PausedChat, chat.UserName, connectionId, chat);
            }
        }
示例#20
0
        private void TimerRefreshChat_Tick(object sender, EventArgs e)
        {
            int messageId = ChatServices.ReturnUnreadMessageId();

            if (messageId > 0)
            {
                ChatMessages message = ChatServices.ReturnMessage(messageId);
                RtbChat.AppendText(DateTime.Now.ToString() + "  ");
                RtbChat.AppendText($"from {ChatServices.GetUsers(message.sender_id)}" + "\r\n");
                RtbChat.AppendText($"{message.Message}" + "\r\n");
                ChatServices.SetFlagRead(messageId);
            }
        }
示例#21
0
 public JsonResult ReportIssue()
 {
     try
     {
         if (ChatServices.RestartService())
         {
             return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
         }
     }
     catch (Exception)
     {
     }
     return(Json(new { success = false }, JsonRequestBehavior.AllowGet));
 }
示例#22
0
        private void LbUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            RtbChat.Text = "";
            TimerRefreshChat.Stop();
            List <ChatMessages> chatMessages = ChatServices.ReturnReadMessages(((Users)LbUsers.SelectedItem).id);

            foreach (var message in chatMessages)
            {
                RtbChat.AppendText(DateTime.Now.ToString() + "  ");
                RtbChat.AppendText($"from {ChatServices.GetUsers(message.sender_id)}" + "\r\n");
                RtbChat.AppendText($"{message.Message}" + "\r\n");
            }
            TimerRefreshChat.Start();
        }
示例#23
0
        private void TabSupport_Load(object sender, EventArgs e)
        {
            List <Users> allUsers    = ChatServices.GetUsers();
            List <Users> admins      = allUsers.Where(x => x.IsAdmin == true && x.id != CurrentUser.user.id).ToList();
            List <Users> nonAdmins   = allUsers.Where(x => x.IsAdmin == false && x.id != CurrentUser.user.id).ToList();
            Users        currentUser = allUsers.FirstOrDefault(x => x.id == CurrentUser.user.id);

            LbUsers.Items.Add(currentUser);
            LbUsers.Items.AddRange(admins.ToArray());
            LbUsers.Items.AddRange(nonAdmins.ToArray());
            LbUsers.DisplayMember = "username";

            LbUsers.SelectedIndex = 0;
        }
示例#24
0
 public JsonResult DisconnectChat(long chatId)
 {
     try
     {
         var webChat = ChatServices.WebChats.FirstOrDefault(c => c.ChatId == chatId);
         if (webChat != null)
         {
             ChatServices.ProcessDisconnect(webChat.ConnectionId, false, true);
             return(Json(new { success = true }));
         }
     }
     catch (Exception)
     {
     }
     return(Json(new { success = false }));
 }
示例#25
0
        public BackgroundProcess()
        {
            HostingEnvironment.RegisterObject(this);
            _running = true;
            ChatServices.Licensed = ChatServices.IsLicensed();
            var isLicensed = ChatServices.Licensed;

            _checkLicense = isLicensed ? 1800 : 5;
            var baseUrl = ChatServices.BaseUrl;

            TaskTimer = new Timer(OnTimerElapsed, null, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1));
            //using (var db = new Repository())
            //{
            //    var load = db.Profiles.FirstOrDefault();
            //}
        }
示例#26
0
        public void Disconnect(string connectionId, bool forceDisconnect)
        {
            var chat = ChatServices.WebChats.FirstOrDefault(c => c.ConnectionId == connectionId || (c.PreviousConnectionIds != null && c.PreviousConnectionIds.Contains(connectionId)));

            if (!forceDisconnect)
            {
                if (chat != null && ChatController.ContinueChat() && (chat.State == ChatState.Connected || chat.State == ChatState.Paused))
                {
                    var now       = DateTime.Now;
                    var remaining = ChatController.ContinueChatTimeout();
                    if (chat.DateEnded.HasValue)
                    {
                        var elapsed = now.Subtract(chat.DateEnded.Value);
                        remaining = ChatController.ContinueChatTimeout() - Convert.ToInt32(elapsed.TotalSeconds);
                    }
                    if (remaining > 0)
                    {
                        var isPaused = chat.State == ChatState.Paused;
                        Clients.Client(connectionId).pauseWcbChat(isPaused);
                        return;
                    }
                }

                Clients.Client(connectionId).disconnected(ChatController.EnableKeepOpenOnDisconnectAndStartNew(), true);
            }
            else
            {
                if (chat != null)
                {
                    ChatServices.SendCustomSystemMessage(CustomMessageType.VisitorDisconnect, "", chat.ConnectionId, chat);
                    if (chat.PreviousConnectionIds != null && chat.PreviousConnectionIds.Any())
                    {
                        foreach (var cid in chat.PreviousConnectionIds.Where(p => p != chat.ConnectionId))
                        {
                            ChatServices.SendCustomSystemMessage(CustomMessageType.VisitorDisconnect, "", cid, chat);
                        }
                    }
                    ChatServices.ProcessDisconnect(chat.ConnectionId, false, true);
                }
            }
        }
示例#27
0
 public void Disconnect(WebChat webChat, ChatServices.DisconnectReason reason)
 {
     try
     {
         var chatId                = webChat.ChatId;
         var connectionId          = webChat.ConnectionId;
         var participantId         = webChat.ParticipantId;
         var previousConnectionIds = webChat.PreviousConnectionIds;
         if (ChatController.EnableKeepOpenOnDisconnectAndStartNew() && webChat.DateAnswered.HasValue)
         {
             if (webChat.Messages.Any() && !ChatServices.DisconnectedWebChats.Any(
                     d =>
                     d.ConnectionId == webChat.ConnectionId &&
                     (d.PreviousConnectionIds != null &&
                      d.PreviousConnectionIds.Contains(webChat.ConnectionId))))
             {
                 ChatServices.DisconnectedWebChats.Add(webChat);
             }
         }
         ChatServices.WebChats.Remove(webChat);
         ChatServices.Disconnect(connectionId, reason);
         if (previousConnectionIds != null)
         {
             foreach (var previousConnectionId in previousConnectionIds)
             {
                 ChatServices.Disconnect(previousConnectionId, reason, "", true, true);
             }
         }
         ChatServices.EndChat(participantId);
         var repository = new Repository();
         var chat       = repository.Chats.Find(chatId);
         if (chat != null)
         {
             chat.DateEnded = DateTime.Now;
             repository.SaveChanges();
         }
     }
     catch (Exception e)
     {
     }
 }
示例#28
0
        public void SendTest(string name, string message)
        {
            var imgsrc    = "/Content/Images/user.png";
            var direction = "out";

            if (TestModeInt == 0)
            {
                TestModeInt = 1;
            }
            else
            {
                TestModeInt = 0;
                direction   = "in";
                name        = "Agent";
                imgsrc      = "/Content/Images/agent.png";
            }
            var initials  = ChatServices.GetInitialsFromName(name);
            var messageId = ChatServices.GetNewMessageId();

            Clients.Caller.addNewMessageToPage(name, message, imgsrc, direction, initials, messageId);
        }
        public ActionResult UpdateProfile(CreateProfileViewModel model)
        {
            try
            {
                var existingName = _repository.Profiles.FirstOrDefault(p => p.Name.ToLower() == model.ProfileName.ToLower() && p.ProfileId != model.ProfileId);
                var widget       = _repository.Widgets.FirstOrDefault(w => w.WidgetId == model.Widget);
                var template     = _repository.Templates.FirstOrDefault(t => t.TemplateId == model.Template);
                var workgroup    = _repository.Workgroups.FirstOrDefault(w => w.WorkgroupId == model.Workgroup);
                var user         = _repository.Users.Find(User.Identity.GetUserId());
                var skills       = model.Skills != null && model.Skills.Any() ? model.Skills.Select(skillId => _repository.Skills.Find(skillId)).ToList() : null;
                var schedules    = model.Schedules != null && model.Schedules.Any() ? model.Schedules.Select(i => _repository.Schedules.Find(i)).ToList() : null;

                if (existingName != null)
                {
                    ModelState.AddModelError("", "Profile Name is not Unique.");
                }
                ////Need to add this back
                //if (widget == null)
                //{
                //    ModelState.AddModelError("","Widget Not Found.");
                //}
                if (template == null)
                {
                    ModelState.AddModelError("", "Template Not Found.");
                }
                if (workgroup == null)
                {
                    ModelState.AddModelError("", "Workgroup Not Found.");
                }
                if (ModelState.IsValid)
                {
                    var profile = _repository.Profiles.Find(model.ProfileId);
                    if (profile != null)
                    {
                        profile.Name           = model.ProfileName;
                        profile.HeaderLogoPath = model.HeaderLogoPath;
                        profile.HeaderText     = model.HeaderText;
                        profile.Description    = model.Description;
                        profile.Template       = template;
                        profile.Widget         = widget;
                        profile.Workgroup      = workgroup;
                        profile.Skills.Clear();
                        profile.Skills        = skills;
                        profile.LastUpdatedBy = user;
                        profile.LastUpdatedOn = DateTime.Now;
                        profile.IncludeUserDataAsAttributes = model.IncludeUserDataAsAttributes;
                        profile.IncludeUserDataAsCustomInfo = model.IncludeUserDataAsCustomInfo;
                        profile.Schedules.Clear();
                        profile.Schedules        = schedules;
                        profile.AllowAttachments = model.AllowAttachments;
                    }
                    _repository.SaveChanges();
                    UpdateSchedules(profile);
                    ChatServices.UpdateRefreshWatch();
                    return(Json(new { success = true, message = "Profile updated successfully!" }));
                }
            }
            catch (Exception)
            {
            }
            model.Logos = GetLogos();
            var workgroupList = _repository.Workgroups.Where(w => w.IsAssignable).Select(w => new SelectListItem
            {
                Text     = w.DisplayName,
                Value    = w.WorkgroupId.ToString(),
                Selected = w.WorkgroupId == model.Workgroup
            }).ToList();
            var templateList = _repository.Templates.Select(t => new SelectListItem
            {
                Text     = t.Title,
                Value    = t.TemplateId.ToString(),
                Selected = t.TemplateId == model.Template
            }).ToList();
            var widgetList = !_repository.Widgets.Any() ? new List <SelectListItem>() : _repository.Widgets.Select(w => new SelectListItem
            {
                Text     = w.Name,
                Value    = w.WidgetId.ToString(),
                Selected = w.WidgetId == model.Widget
            }).ToList();
            var skillsList = !_repository.Skills.Any(s => s.IsAssignable) ? new List <Skill>() : _repository.Skills.Where(s => s.IsAssignable).ToList();

            var schedulesList = !_repository.Schedules.Any(s => s.IsAssignable) ? new List <Schedule>() : _repository.Schedules.Where(s => s.IsAssignable).ToList();

            model.SchedulesList = schedulesList;
            model.SkillsList    = skillsList;
            model.WorkgroupList = workgroupList;
            model.TemplateList  = templateList;
            model.WidgetList    = widgetList;
            return(PartialView("_CreateProfile", model));
        }
示例#30
0
        private async Task initialize()
        {
            if (State != TVTCommentState.NotInitialized)
            {
                throw new InvalidOperationException("This object is already initialized");
            }

            // プラグインの無効化→有効化を短時間で行うと
            // 設定ファイルがアクセス中でIOExceptionが飛ぶので時間を空けて試す
            for (int i = 1; ; ++i)
            {
                try
                {
                    this.Settings = await this.settingReaderWriter.Read();

                    break;
                }
                catch (FormatException)
                {
                    this.Settings = new TVTCommentSettings();
                    break;
                }
                catch (IOException)
                {
                    const int retryCount = 6;
                    if (i >= retryCount)
                    {
                        throw;
                    }
                }
                await Task.Delay(500);
            }

            string baseDir = Path.GetDirectoryName(getExePath());

            this.channelDatabase = new ChannelDatabase(Path.Combine(baseDir, "channels.txt"));
            this.ChatServices    = new ReadOnlyCollection <ChatService.IChatService>(new ChatService.IChatService[] {
                new ChatService.NiconicoChatService(
                    Settings.Niconico, this.channelDatabase, Path.Combine(baseDir, "niconicojikkyouids.txt"), Path.Combine(baseDir, "niconicoliveids.txt")
                    ),
                new ChatService.NichanChatService(Settings.Nichan, this.channelDatabase, Path.Combine(baseDir, "2chthreads.txt")),
                new ChatService.FileChatService()
            });

            var chatCollectServiceEntryIds = this.ChatServices.SelectMany(x => x.ChatCollectServiceEntries).Select(x => x.Id);

            System.Diagnostics.Debug.Assert(
                chatCollectServiceEntryIds.Distinct().Count() == chatCollectServiceEntryIds.Count(),
                "IDs of ChatCollectServiceEntries are not unique"
                );

            //Viewerとの接続
            string[] commandLine = Environment.GetCommandLineArgs();
            if (commandLine.Length == 3)
            {
                ipcModule = new IPCModule(commandLine[1], commandLine[2], SynchronizationContext.Current);
            }
            else
            {
                ipcModule = new IPCModule("TVTComment_Up", "TVTComment_Down", SynchronizationContext.Current);
            }

            ipcModule.Disposed -= ipcManager_Disposed;
            ipcModule.Disposed += ipcManager_Disposed;
            try
            {
                await ipcModule.Connect();
            }
            catch (IPCModule.ConnectException) { return; }
            ipcModule.MessageReceived += ipcManager_MessageReceived;

            //各種SubModule作成
            ChannelInformationModule = new ChannelInformationModule(ipcModule);
            ChatCollectServiceModule = new ChatCollectServiceModule(ChannelInformationModule);
            ChatTrendServiceModule   = new ChatTrendServiceModule(SynchronizationContext.Current);
            ChatModule = new ChatModule(
                this.Settings, ChatServices, ChatCollectServiceModule, ipcModule, ChannelInformationModule
                );
            DefaultChatCollectServiceModule = new DefaultChatCollectServiceModule(
                this.Settings, ChannelInformationModule, ChatCollectServiceModule, ChatServices.SelectMany(x => x.ChatCollectServiceEntries)
                );
            CommandModule = new CommandModule(
                ipcModule, SynchronizationContext.Current
                );
            ChatCollectServiceCreationPresetModule = new ChatCollectServiceCreationPresetModule(
                this.Settings, ChatServices.SelectMany(x => x.ChatCollectServiceEntries)
                );

            //コメント透過度設定処理
            ChatOpacity = new ObservableValue <byte>(this.Settings.ChatOpacity);
            ChatOpacity.Subscribe(async opacity =>
            {
                this.Settings.ChatOpacity = opacity;
                await ipcModule.Send(new IPC.IPCMessage.SetChatOpacityIPCMessage {
                    Opacity = opacity
                });
            });

            //メール欄例設定
            var chatPostMailTextExamples = this.Settings.ChatPostMailTextExamples;

            ChatPostMailTextExamples.AddRange(chatPostMailTextExamples);

            ipcModule.StartReceiving();
            State = TVTCommentState.Working;
        }
        public ActionResult CreateProfile()
        {
            var message = "";

            try
            {
                if (!_repository.Workgroups.Any(w => w.IsAssignable))
                {
                    throw new Exception("No Assignable Workgroups found.");
                }
                if (!_repository.Templates.Any())
                {
                    throw new Exception("No Templates found. Please create one to continue.");
                }
                //Create a default widget and Template
                var          profileName = "";
                const string defaultName = "Profile";
                var          cnt         = 1;
                var          distinct    = false;
                while (!distinct)
                {
                    profileName = defaultName + cnt;
                    var existing = _repository.Profiles.FirstOrDefault(p => p.Name.ToLower() == profileName.ToLower());
                    if (existing != null)
                    {
                        cnt++;
                    }
                    else
                    {
                        distinct = true;
                    }
                }
                var user      = _repository.Users.Find(User.Identity.GetUserId());
                var template  = _repository.Templates.FirstOrDefault();
                var workgroup = _repository.Workgroups.FirstOrDefault(i => i.IsAssignable);
                //var widget = _repository.Widgets.FirstOrDefault();
                var profile = new Profile
                {
                    Name          = profileName,
                    CreatedBy     = user,
                    CreatedOn     = DateTime.Now,
                    LastUpdatedBy = user,
                    LastUpdatedOn = DateTime.Now,
                    Workgroup     = workgroup,
                    Template      = template,
                    Widget        = null,
                    IncludeUserDataAsAttributes = false,
                    IncludeUserDataAsCustomInfo = false,
                    AllowAttachments            = true
                };
                _repository.Profiles.Add(profile);
                _repository.SaveChanges();
                var model = GetCreateProfileViewModel(profile);
                ChatServices.UpdateRefreshWatch();
                return(PartialView("_CreateProfile", model));
            }
            catch (Exception e)
            {
                message = e.Message;
            }
            return(Json(new { success = false, message }, JsonRequestBehavior.AllowGet));
        }