Пример #1
0
        private async void analyze()
        {
            StatusWindow win2 = new StatusWindow();

            win2.Show();

            InputParams i = new InputParams();

            i.numOfStocks = Int32.Parse(this.numOfStocks.Text);
            i.daysAgo     = Int32.Parse(this.daysAgo.Text);
            i.clusters    = Int32.Parse(this.clusters.Text);
            i.open        = (bool)open.IsChecked;
            i.close       = (bool)close.IsChecked;
            i.high        = (bool)high.IsChecked;
            i.low         = (bool)low.IsChecked;

            var im = new Managers.InputManager(i);
            await Task.Run(() => im.GetInputReady());

            var fm = new FilesManager(i.clusters);
            //await Task.Run(() => fm.TestRun());
            await Task.Run(() => fm.Start());

            win2.Close();

            var           om     = new OutputManager(im.allStocksData);
            ResultsWindow graphs = new ResultsWindow(om.clusters);

            graphs.Show();
        }
Пример #2
0
        public App()
        {
            Properties["AppName"] = "InstructorViews";
            StatusWindow statusWindow = new StatusWindow("Probation");

            statusWindow.Show();
        }
Пример #3
0
        public void FileOut(string filePath, SMF.SMF smf)
        {
            IsFileOutput = true;
            var prog = midi_GetWavFileOutProgressPtr();

            *(int *)prog = 0;
            var fm = new StatusWindow(smf.MaxTime, prog);

            fm.Show();
            Task.Factory.StartNew(() => {
                var ms = new MemoryStream();
                var bw = new BinaryWriter(ms);
                foreach (var ev in smf.EventList)
                {
                    bw.Write(ev.Tick);
                    bw.Write(ev.Data);
                }
                var evArr         = ms.ToArray();
                fixed(byte *evPtr = &evArr[0])
                {
                    midi_WavFileOut(Marshal.StringToHGlobalAuto(filePath), mpWaveTable, mpInstList,
                                    44100, 16, (IntPtr)evPtr, (uint)evArr.Length, 960);
                }
                IsFileOutput = false;
            });
        }
Пример #4
0
        public async Task <JsonResult> LoadHistoryOfMessege(string userOrGroup, string groupname, int top, int left, string ctrId)
        {
            int i;
            var idFromUser = db.UserLogins.FirstOrDefault(u => u.UserNameCopy == User.Identity.Name).Id;
            //save status window in database
            var checkesistwindow = db.StatusWindows.Where(w => w.CtrId == ctrId && w.UserName == User.Identity.Name).ToList();

            if (checkesistwindow.Count == 0)
            {
                StatusWindow sw = new StatusWindow
                {
                    CtrId         = ctrId,
                    WindowName    = groupname,
                    TopPosition   = top.ToString() + "px",
                    LeftPosition  = left.ToString() + "px",
                    UserName      = User.Identity.Name,
                    KeyWindowName = userOrGroup
                };
                db.StatusWindows.Add(sw);
                await db.SaveChangesAsync();
            }
            else
            {
                var windowstatusupdate = checkesistwindow[0];
                windowstatusupdate.TopPosition     = top.ToString() + "px";
                windowstatusupdate.LeftPosition    = left.ToString() + "px";
                db.Entry(windowstatusupdate).State = EntityState.Modified;
                await db.SaveChangesAsync();
            }

            //
            if (int.TryParse(userOrGroup, out i)) // load  group messege
            {
                var result = (from md in db.Group_User_Messege
                              //orderby md ascending
                              where (md.GroupId == i)
                              select new
                {
                    messege = "<div class='message'><span class='userName'>" + md.WhoChat + "</span>: " + md.ConentMesseger + "</div>"
                }).ToListAsync();


                return(await Task.FromResult(Json(result.Result, JsonRequestBehavior.AllowGet)));
            }
            else // load user messege
            {
                var idToUser = db.UserLogins.FirstOrDefault(u => u.UserNameCopy == userOrGroup).Id;
                var result   = (from md in db.MessegeDirects
                                //orderby md ascending
                                where (md.FromUser == idFromUser && md.ToUser == idToUser) ||
                                (md.FromUser == idToUser && md.ToUser == idFromUser)
                                select new
                {
                    messege = "<div class='message'><span class='userName'>" + md.WhoChat + "</span>: " + md.ConentMesseger + "</div>"
                }).ToListAsync();


                return(await Task.FromResult(Json(result.Result, JsonRequestBehavior.AllowGet)));
            }
        }
Пример #5
0
        private static void Thread_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (ApplicationOptions.PopupOption == ApplicationOptions.PopupNotificationOption.Always ||
                (ApplicationOptions.PopupOption == ApplicationOptions.PopupNotificationOption.WhenMinimized &&
                 Application.Current.MainWindow.WindowState == WindowState.Minimized))
            {
                if (!Application.Current.Windows.OfType <PopupNotificationWindow>().Any())
                {
                    // Mark all existing status changes as read.
                    for (int i = 0; i < StatusChangeLog.Count; ++i)
                    {
                        StatusChangeLog[i].HasStatusBeenCleared = true;
                    }
                }
                StatusChangeLog.Add(e.UserState as StatusChangeLog);

                if (StatusWindow != null && StatusWindow.IsLoaded)
                {
                    if (StatusWindow.WindowState == WindowState.Minimized)
                    {
                        StatusWindow.WindowState = WindowState.Normal;
                    }
                    StatusWindow.Focus();
                }
                else if (!Application.Current.Windows.OfType <PopupNotificationWindow>().Any())
                {
                    var wnd = new PopupNotificationWindow(StatusChangeLog);
                    wnd.Show();
                }
            }
            else
            {
                StatusChangeLog.Add(e.UserState as StatusChangeLog);
            }
        }
Пример #6
0
        protected override void OnStartup(StartupEventArgs e)
        {
            Logger.Trace("OnStartup: Invoked");

            _pipeServerWorker.DoWork += (sender, args) =>
            {
                Logger.Trace("OnStartup: Registering event handlers");
                _pipeServer.DeskbandMouseEnter       += (o, eventArgs) => this.Dispatcher.BeginInvoke(new Action(OnMouseEnter));
                _pipeServer.DeskbandMouseLeave       += (o, eventArgs) => this.Dispatcher.BeginInvoke(new Action(OnMouseLeave));
                _pipeServer.DeskbandLeftButtonClick  += (o, eventArgs) => this.Dispatcher.BeginInvoke(new Action(OnLButtonClick));
                _pipeServer.DeskbandRightButtonClick += (o, eventArgs) => this.Dispatcher.BeginInvoke(new Action(OnRButtonClick));
                _pipeServer.DeskbandExit             += (o, eventArgs) => this.Dispatcher.BeginInvoke(new Action(OnExit));
                _pipeServer.HookFinished             += (o, eventArgs) => this.Dispatcher.BeginInvoke(new Action(OnDeskbandShown));

                _pipeServer.Start();
            };
            _pipeServerWorker.RunWorkerAsync();

            ShowDeskband();

            var splashWindow = _container.Resolve <SplashWindow>();

            splashWindow.Show();
            splashWindow.Focus();
            Logger.Trace("OnStartup: Splash window in on");

            Task.Run(() =>
            {
                _pipeServer.Send("ics_loading");
                _container.Resolve <ISplashViewModel>().Start();
            }).ContinueWith(t =>
            {
                _pipeServer.Send("ics_on");
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    splashWindow.Close();
                    Logger.Trace("OnStartup: Splash window in off");

                    var successWindow         = _container.Resolve <SuccessWindow>();
                    successWindow.DataContext = _container.Resolve <ISuccessViewModel>();
                    successWindow.Show();
                    successWindow.Focus();
                    Logger.Trace("OnStartup: Success window in on");

                    _currentWindow = successWindow;
                }));
            });

            _mainWindow             = _container.Resolve <MainWindow>();
            _mainWindow.DataContext = _container.Resolve <IMainViewModel>();

            _statusWindow             = _container.Resolve <StatusWindow>();
            _statusWindow.DataContext = _container.Resolve <IStatusViewModel>();
        }
Пример #7
0
        private void TriggerStatusChange(StatusChangeLog status)
        {
            if (ApplicationOptions.PopupOption == ApplicationOptions.PopupNotificationOption.Always ||
                (ApplicationOptions.PopupOption == ApplicationOptions.PopupNotificationOption.WhenMinimized &&
                 Application.Current.MainWindow.WindowState == WindowState.Minimized))
            {
                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    mutex.WaitOne();
                    if (!Application.Current.Windows.OfType <PopupNotificationWindow>().Any())
                    {
                        // Mark all existing status changes as read.
                        for (int i = 0; i < StatusChangeLog.Count; ++i)
                        {
                            StatusChangeLog[i].HasStatusBeenCleared = true;
                        }
                    }
                    StatusChangeLog.Add(status);
                    mutex.ReleaseMutex();

                    if (StatusWindow != null && StatusWindow.IsLoaded)
                    {
                        if (StatusWindow.WindowState == WindowState.Minimized)
                        {
                            StatusWindow.WindowState = WindowState.Normal;
                        }
                        StatusWindow.Focus();
                    }
                    else if (!Application.Current.Windows.OfType <PopupNotificationWindow>().Any())
                    {
                        new PopupNotificationWindow(StatusChangeLog).Show();
                    }
                }));
            }

            else
            {
                mutex.WaitOne();
                StatusChangeLog.Add(status);
                mutex.ReleaseMutex();
            }

            if (ApplicationOptions.IsLogStatusChangesEnabled && ApplicationOptions.LogStatusChangesPath.Length > 0)
            {
                WriteToStatusChangesLog(status);
            }

            if ((status.Status == ProbeStatus.Down) && (ApplicationOptions.IsAudioAlertEnabled))
            {
                SoundPlayer player = new SoundPlayer(ApplicationOptions.AudioFilePath);
                player.Play();
            }
        }
Пример #8
0
    void Start()
    {
        parentCanvas = GameObject.Find("GuildeMenu").GetComponent <Canvas>();

        if (GameObject.FindGameObjectWithTag("statusWindow") != null)
        {
            statusWindow = GameObject.FindGameObjectWithTag("statusWindow").GetComponent <StatusWindow>();
        }
        else
        {
            Debug.Log("status window not found");
        }
    }
Пример #9
0
    // ステータスウィンドウを生成する関数
    public void InitStatusWindow(int num)
    {
        string path = "Prefabs/StatusWindow";
        GameObject obj = Instantiate( Resources.Load(path) as GameObject ) as GameObject;

        obj.transform.parent = Manager.RootStatusWindow.transform;
        obj.transform.localPosition = new Vector3(GetStatusWindowPosX(num), obj.transform.position.y, obj.transform.position.z );	// 左詰め
        StatusWindow = obj.GetComponent<StatusWindow> ();

        Debug.Log ("MyChar.Status : " +Status.Hp + ", " + Status.Job);

        StatusWindow.SetImage (Status.Job + "_1" );
        UpdateUI ();
    }
Пример #10
0
        protected void CheckRules(IList <string> files, StatusWindow window, MainWindow wmain)
        {
            if (!config.only_rules)
            {
                return;
            }
            Excel excel = new Excel();

            int failed = 0;

            wmain.Log(DataLog.LogImage.INFO, "Включен режим проверки форм без конвертирования!");
            window.setState(true, "", 0, files.Count);

            for (int id = 0; id < files.Count; id++)
            {
                string fname   = files[id];
                string docname = Path.GetFileName(fname) ?? fname;

                window.updateState(true, "Читаем документ " + docname, id + 1);
                excel.OpenWorksheet(fname);

                var form = findCorrectForm(excel.worksheet, config);
                if (form == null)
                {
                    failed++;
                }

                var icon = form == null ? DataLog.LogImage.WARNING : DataLog.LogImage.SUCCESS;
                var line = form == null ? $"Для документа '{docname}' не найдена форма!" : $"Для документа '{docname}' выбрана форма '{form.Name}'!";

                wmain.Log(icon, line);
                Logger.info(line);
            }

            if (failed == 0)
            {
                wmain.Log(DataLog.LogImage.SUCCESS, "Для всех документов были найдены формы!");
            }
            else
            {
                wmain.Log(DataLog.LogImage.WARNING, $"Не удалось найти форму для {failed} документов!");
            }

            wmain.toggleConvertButton(true);
            excel.close();
            window.mayClose();
        }
        static void Main(string[] args)
        {
            string hostname = "10.10.0.32:1234";

            if (args.Length > 0)
            {
                hostname = args[0];
            }


            Application.Init();
            var top = Application.Top;

            top.Add(log      = new LogWindow());
            top.Add(status   = new StatusWindow());
            top.Add(controls = new ControlsWindow());



            var menu = new MenuBar(new MenuBarItem[] {
                new MenuBarItem("_File", new MenuItem [] {
                    new MenuItem("_New", "", null),
                    new MenuItem("_Close", "", null),
                    new MenuItem("_Quit", "", null)
                }),
                new MenuBarItem("_Edit", new MenuItem [] {
                    new MenuItem("_Copy", "", null),
                    new MenuItem("C_ut", "", null),
                    new MenuItem("_Paste", "", null)
                })
            });

            top.Add(menu);

            androidConnection = new AndroidConnector(hostname);
            using (scanner = new Scanner())
            {
                Task.Run(RunScanner);
                Application.Run();
            }
        }
Пример #12
0
        private void Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                if (e.Key == Key.K)
                {
                    var window = new TextWindow(true);
                    window.Owner = this;
                    window.ShowDialog();
                    Settings.SetKeyWord(window.PassBox.Password);
                    Connection.SendMessage(new MessageClass(Connection.ID, -1, Commands.KeyPass, 0, window.PassBox.Password));
                }

                if (e.Key == Key.T)
                {
                    var window = new StatusWindow(Version, Status);
                    window.Owner = this;
                    window.Show();
                }
            }
        }
Пример #13
0
        public void StartGame(bool testGame = false)
        {
            IsFocused = true;

            GameLoop.World = new World(testGame);

            // Hides the main menu, so that it's possible to interact with the other windows.
            MainMenu.Hide();

            //Message Log initialization
            MessageLog = new MessageLogWindow(GameLoop.GameWidth / 2, GameLoop.GameHeight / 2, "Message Log");
            Children.Add(MessageLog);
            MessageLog.Show();
            MessageLog.Position = new Point(GameLoop.GameWidth / 2, GameLoop.GameHeight / 2);
#if DEBUG
            MessageLog.Add("Test message log works");
#endif
            // Inventory initialization
            InventoryScreen = new InventoryWindow(GameLoop.GameWidth / 2, GameLoop.GameHeight / 2, "Inventory Window");
            Children.Add(InventoryScreen);
            InventoryScreen.Hide();
            InventoryScreen.Position = new Point(GameLoop.GameWidth / 2, 0);

            StatusConsole = new StatusWindow(GameLoop.GameWidth / 2, GameLoop.GameHeight / 2, "Status Window");
            Children.Add(StatusConsole);
            StatusConsole.Position = new Point(GameLoop.GameWidth / 2, 0);
            StatusConsole.Show();

            // Build the Window
            CreateMapWindow(GameLoop.GameWidth / 2, GameLoop.GameHeight, "Game Map");

            // Then load the map into the MapConsole
            MapWindow.LoadMap(GameLoop.World.CurrentMap);

            // Start the game with the camera focused on the player
            MapWindow.CenterOnActor(GameLoop.World.Player);
        }
Пример #14
0
        private void remoteActionWizardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RemoteShutdownWizard remoteShutdownWizard = new RemoteShutdownWizard();

            if (remoteShutdownWizard.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                var t = new RemoteActionInfo()
                {
                    RemoteAction = EnumHelper.RemoteAction.RemoteReboot, Machines = new List <MachineInfo>()
                    {
                        new MachineInfo()
                        {
                            DomainName = "Workgroup", ServerName = "10.70.70.48", UserName = "******", Password = "******"
                        }
                    }, ActionName = "Reboot"
                };

                StatusWindow statusWindow = new StatusWindow(remoteShutdownWizard.remoteactionInfo);
                //StatusWindow statusWindow = new StatusWindow(t);


                statusWindow.ShowDialog(this);
            }
        }
Пример #15
0
        private void TriggerStatusChange(StatusChangeLog status)
        {
            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                if (ApplicationOptions.PopupOption == ApplicationOptions.PopupNotificationOption.Always ||
                    (ApplicationOptions.PopupOption == ApplicationOptions.PopupNotificationOption.WhenMinimized &&
                     Application.Current.MainWindow.WindowState == WindowState.Minimized))
                {
                    mutex.WaitOne();
                    if (!Application.Current.Windows.OfType <PopupNotificationWindow>().Any())
                    {
                        // Mark all existing status changes as read.
                        for (int i = 0; i < StatusChangeLog.Count; ++i)
                        {
                            StatusChangeLog[i].HasStatusBeenCleared = true;
                        }
                    }
                    StatusChangeLog.Add(status);
                    mutex.ReleaseMutex();

                    if (StatusWindow != null && StatusWindow.IsLoaded)
                    {
                        if (StatusWindow.WindowState == WindowState.Minimized)
                        {
                            StatusWindow.WindowState = WindowState.Normal;
                        }
                        StatusWindow.Focus();
                    }
                    else if (!Application.Current.Windows.OfType <PopupNotificationWindow>().Any())
                    {
                        new PopupNotificationWindow(StatusChangeLog).Show();
                    }
                }
                else
                {
                    mutex.WaitOne();
                    StatusChangeLog.Add(status);
                    mutex.ReleaseMutex();
                }
            }));

            if (ApplicationOptions.IsLogStatusChangesEnabled && ApplicationOptions.LogStatusChangesPath.Length > 0)
            {
                mutex.WaitOne();
                WriteToStatusChangesLog(status);
                mutex.ReleaseMutex();
            }

            if ((ApplicationOptions.IsAudioDownAlertEnabled) && (status.Status == ProbeStatus.Down))
            {
                try
                {
                    using (SoundPlayer player = new SoundPlayer(ApplicationOptions.AudioDownFilePath))
                    {
                        player.Play();
                    }
                }
                catch (Exception ex)
                {
                    ApplicationOptions.IsAudioDownAlertEnabled = false;
                    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        DialogWindow.ErrorWindow($"Failed to play audio file. Audio alerts have been disabled. {ex.Message}").ShowDialog();
                    }));
                }
            }
            else if ((ApplicationOptions.IsAudioUpAlertEnabled) && (status.Status == ProbeStatus.Up))
            {
                try
                {
                    using (SoundPlayer player = new SoundPlayer(ApplicationOptions.AudioUpFilePath))
                    {
                        player.Play();
                    }
                }
                catch (Exception ex)
                {
                    ApplicationOptions.IsAudioUpAlertEnabled = false;
                    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        DialogWindow.ErrorWindow($"Failed to play audio file. Audio alerts have been disabled. {ex.Message}").ShowDialog();
                    }));
                }
            }
        }
Пример #16
0
        public void ShowStatusView()
        {
            var statusWin = new StatusWindow();

            statusWin.Show();
        }
Пример #17
0
        private void Connection_AcceptMessage(MessageClass message)
        {
            #region StandartCommands
            if (message.Command == Commands.Disconnect)
            {
                Task.Run(LostConnection);
                Dispatcher.Invoke(() =>
                {
                    int count = Users.Count;
                    for (int i = 0; i < count; i++)
                    {
                        FullTable.Items.Remove(Users[0]);
                        Users.Remove(Users[0]);
                    }

                    DisconnectLabel.Opacity = 1;
                });
            }

            if (message.Command == Commands.AcceptLogin)
            {
                Task.Run(FindConnection);
                Dispatcher.Invoke(() => DisconnectLabel.Opacity = 0);
                Connection.ID = message.Getter;
                Connection.SendMessage(new MessageClass(Connection.ID, -1, Commands.RsaKey, 0, Connection.Secure.GetPublicKey()));
            }

            if (message.Command == Commands.AesKey)
            {
                Connection.Secure.SetAesKey(Connection.Secure.RsaDecrypt(message.Package));
                Connection.Secured = true;
                Connection.SendMessage(new MessageClass(Connection.ID, -1, Commands.GetList, 0));
                Connection.SendMessage(new MessageClass(Connection.ID, -1, Commands.KeyPass, 0, Settings.KeyWord));
            }

            if (message.Command == Commands.List)
            {
                try
                {
                    string[] com = message.GetStringPackage().Split(';');
                    AddUser(com);
                    Dispatcher.Invoke(() =>
                    {
                        try
                        {
                            /*
                             * int count = Users.Count;
                             * for (int i = 0; i < count; i++)
                             * {
                             *  FullTable.Items.Remove(Users[0]);
                             *  Users.Remove(Users[0]);
                             * }
                             *
                             * for (int i = 0; i < com.Length; i += 3)
                             * {
                             *  var user = new UserControll(Convert.ToInt32(com[i]), com[i + 1], com[i + 2]);
                             *  user.ActiveEvent += User_ActiveEvent;
                             *  Users.Add(user);
                             *  FullTable.Items.Add(user);
                             *  if (Status != "Simple")
                             *      user.SetEnabled(1, true);
                             * }
                             */
                        }
                        catch { }
                    });
                }
                catch { }
            }

            if (message.Command == Commands.ChangeStatus)
            {
                Status = message.GetStringPackage();
                if (Status != "Simple")
                {
                    Dispatcher.Invoke(() =>
                    {
                        for (int i = 0; i < VideoClasses.Count; i++)
                        {
                            VideoClasses[i].Close();
                        }
                        var window   = new StatusWindow(Version, Status);
                        window.Owner = this;
                        window.Show();
                    });
                    for (int i = 0; i < Users.Count; i++)
                    {
                        Dispatcher.Invoke(() => Users[i].SetEnabled(1, true));
                    }
                }
                else
                {
                    for (int i = 0; i < Users.Count; i++)
                    {
                        Dispatcher.Invoke(() => Users[i].SetEnabled(0, false));
                    }
                }
            }

            if (message.Command == Commands.ChangeName)
            {
                Dispatcher.Invoke(() =>
                {
                    for (int i = 0; i < Users.Count; i++)
                    {
                        if (message.Getter == Users[i].ID)
                        {
                            Users[i].NameLabel.Content = message.GetStringPackage();
                        }
                    }
                });
            }

            if (message.Command == Commands.GetInfo)
            {
                string result = Version + "\n";
                if (Status != "Simple")
                {
                    result += "[Secret]\n";
                }
                else
                {
                    result += "Simple\n";
                }

                result += Directory.GetCurrentDirectory() + "\n";

                result += TurnOnTime.ToString();

                Connection.SendMessage(new MessageClass(Connection.ID, message.Sender, Commands.Info, 0, result));
            }

            if (message.Command == Commands.Info)
            {
                Dispatcher.Invoke(() => System.Windows.MessageBox.Show(message.GetStringPackage()));
            }
            #endregion

            #region FileCommands
            if (message.Command == Commands.RFileSend)
            {
                Task.Run(() =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        string name = "[Secret]";
                        for (int i = 0; i < Users.Count; i++)
                        {
                            if (message.Sender == Users[i].ID)
                            {
                                name = Users[i].NameLabel.Content as string;
                            }
                        }
                        var window   = new RequestWindow(name, message.GetStringPackage());
                        window.Owner = this;
                        if (!SilenceControll.Mode)
                        {
                            window.Topmost = false;
                            window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                            if (!IsActive)
                            {
                                this.Show();
                                if (Icons != null)
                                {
                                    Icons.Visible = false;
                                }
                                this.WindowState = WindowState.Minimized;
                            }
                        }
                        Helper.FlashApplicationWindow();
                        window.ShowDialog();
                        if (window.Result)
                        {
                            Connection.SendMessage(new MessageClass(Connection.ID, message.Sender, Commands.AcceptFile, message.ElementID));
                        }
                        else
                        {
                            Connection.SendMessage(new MessageClass(Connection.ID, message.Sender, Commands.CancelFile, message.ElementID));
                        }
                    });
                });
            }

            if (message.Command == Commands.AcceptFile)
            {
                Dispatcher.Invoke(() =>
                {
                    try
                    {
                        var setuper = FindSetuper(message.ElementID);
                        setuper.Accept();
                    }
                    catch { }
                });
            }

            if (message.Command == Commands.CancelFile)
            {
                Dispatcher.Invoke(() =>
                {
                    try
                    {
                        var setuper = FindSetuper(message.ElementID);
                        setuper.Cancel();
                    }
                    catch { }
                });
            }

            if (message.Command == Commands.FileOK)
            {
                Dispatcher.Invoke(() =>
                {
                    try
                    {
                        var setuper = FindSetuper(message.ElementID);
                        setuper.OK();
                    }
                    catch { }
                });
            }

            if (message.Command == Commands.FileInfo)
            {
                Dispatcher.Invoke(() =>
                {
                    var getter         = new GettingWindow(Connection, Settings);
                    getter.ID          = message.ElementID;
                    getter.UserID      = message.Sender;
                    string[] com       = message.GetStringPackage().Split(';');
                    getter.FileName    = com[0];
                    getter.FileSize    = Convert.ToInt64(com[1]);
                    getter.CloseEvent += (GettingWindow window) =>
                    {
                        Getters.Remove(window);
                        GC.Collect();
                    };
                    getter.Owner = this;
                    getter.Show();
                    Getters.Add(getter);
                });
            }

            if (message.Command == Commands.FileData)
            {
                Dispatcher.Invoke(() =>
                {
                    try
                    {
                        var getter = FindGetter(message.ElementID, message.Sender);
                        getter.SetData(message.Package);
                    }
                    catch { }
                });
            }

            if (message.Command == Commands.FileDone)
            {
                Dispatcher.Invoke(() =>
                {
                    try
                    {
                        var getter = FindGetter(message.ElementID, message.Sender);
                        getter.Done();
                    }
                    catch { }
                });
            }

            #endregion

            #region VideoMCommands
            if (message.Command == Commands.RVideoModule)
            {
                Task.Run(() =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        string name = "[Secret]";
                        for (int i = 0; i < Users.Count; i++)
                        {
                            if (message.Sender == Users[i].ID)
                            {
                                name = Users[i].NameLabel.Content as string;
                            }
                        }
                        var window   = new RequestWindow(name, "<Video.mp4>");
                        window.Owner = this;
                        if (!SilenceControll.Mode)
                        {
                            window.Topmost = false;
                            window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                            if (!IsActive)
                            {
                                this.Show();
                                if (Icons != null)
                                {
                                    Icons.Visible = false;
                                }
                                this.WindowState = WindowState.Minimized;
                            }
                        }
                        Helper.FlashApplicationWindow();
                        window.ShowDialog();
                        if (window.Result)
                        {
                            var video         = new VideoClass(message.ElementID, message.Sender, Connection);
                            video.CloseEvent += (VideoClass obj) =>
                            {
                                VideoClasses.Remove(obj);
                                GC.Collect();
                            };
                            video.Start();
                            VideoClasses.Add(video);
                        }
                        else
                        {
                            Connection.SendMessage(new MessageClass(Connection.ID, message.Sender, Commands.VideoDenied, message.ElementID));
                        }
                    });
                });
            }

            if (message.Command == Commands.HVideoModule)
            {
                var video = new VideoClass(message.ElementID, message.Sender, Connection);
                video.CloseEvent += (VideoClass obj) =>
                {
                    VideoClasses.Remove(obj);
                    GC.Collect();
                };
                video.Start();
                VideoClasses.Add(video);
            }

            if (message.Command == Commands.VideoDenied)
            {
                try
                {
                    Dispatcher.Invoke(FindVideoWindow(message.ElementID).Denied);
                }
                catch { }
            }

            if (message.Command == Commands.VideoPulsar)
            {
                try
                {
                    Dispatcher.Invoke(FindVideoClasses(message.ElementID, message.Sender).Pulsar);
                }
                catch { }
            }

            if (message.Command == Commands.VideoClose)
            {
                try
                {
                    Dispatcher.Invoke(FindVideoClasses(message.ElementID, message.Sender).Close);
                }
                catch { }
            }

            if (message.Command == Commands.VideoData)
            {
                Dispatcher.Invoke(() =>
                {
                    try
                    {
                        FindVideoWindow(message.ElementID).SetVideoData(message.Package);
                    }
                    catch
                    {
                        Connection.SendMessage(new MessageClass(Connection.ID, message.Sender, Commands.VideoClose, message.ElementID));
                    }
                });
            }

            if (message.Command == Commands.SetVideo)
            {
                try
                {
                    if (message.GetStringPackage() == "True")
                    {
                        Dispatcher.Invoke(() => FindVideoClasses(message.ElementID, message.Sender).VideoStream = true);
                    }
                    else
                    {
                        Dispatcher.Invoke(() => FindVideoClasses(message.ElementID, message.Sender).VideoStream = false);
                    }
                }
                catch { }
            }

            if (message.Command == Commands.SetMaxFps)
            {
                try
                {
                    Dispatcher.Invoke(() => FindVideoClasses(message.ElementID, message.Sender).MaxFps = Convert.ToInt32(message.GetStringPackage()));
                }
                catch { }
            }

            if (message.Command == Commands.SetSize)
            {
                try
                {
                    Dispatcher.Invoke(() => FindVideoClasses(message.ElementID, message.Sender).Size = Convert.ToInt32(message.GetStringPackage()));
                }
                catch { }
            }

            if (message.Command == Commands.SetQuality)
            {
                try
                {
                    Dispatcher.Invoke(() => FindVideoClasses(message.ElementID, message.Sender).Quality = Convert.ToInt32(message.GetStringPackage()));
                }
                catch { }
            }

            if (message.Command == Commands.SetMicro)
            {
                try
                {
                    if (message.GetStringPackage() == "True")
                    {
                        Dispatcher.Invoke(FindVideoClasses(message.ElementID, message.Sender).MicroInput.StartRecording);
                    }
                    else
                    {
                        Dispatcher.Invoke(FindVideoClasses(message.ElementID, message.Sender).MicroInput.StopRecording);
                    }
                }
                catch { }
            }

            if (message.Command == Commands.MicroData)
            {
                try
                {
                    if (message.Package != null)
                    {
                        Dispatcher.Invoke(() => FindVideoWindow(message.ElementID).MicroBuffer.AddSamples(message.Package, 0, message.Package.Length));
                    }
                }
                catch { }
            }

            if (message.Command == Commands.SetCursor)
            {
                try
                {
                    if (message.GetStringPackage() == "True")
                    {
                        Dispatcher.Invoke(() => FindVideoClasses(message.ElementID, message.Sender).Cursor = true);
                    }
                    else
                    {
                        Dispatcher.Invoke(() => FindVideoClasses(message.ElementID, message.Sender).Cursor = false);
                    }
                }
                catch { }
            }

            if (message.Command == Commands.SetLoop)
            {
                try
                {
                    if (message.GetStringPackage() == "True")
                    {
                        Dispatcher.Invoke(() => FindVideoClasses(message.ElementID, message.Sender).LoopInput.StartRecording());
                    }
                    else
                    {
                        Dispatcher.Invoke(() => FindVideoClasses(message.ElementID, message.Sender).LoopInput.StopRecording());
                    }
                }
                catch { }
            }

            if (message.Command == Commands.LoopInfo)
            {
                try
                {
                    Dispatcher.Invoke(() => FindVideoWindow(message.ElementID).SetupLoop(message.Package));
                }
                catch { }
            }


            if (message.Command == Commands.LoopData)
            {
                try
                {
                    Dispatcher.Invoke(() => FindVideoWindow(message.ElementID).LoopBuffer.AddSamples(message.Package, 0, message.Package.Length));
                }
                catch { }
            }
            #endregion

            #region FileMCommands
            if (message.Command == Commands.RFileModule)
            {
                Task.Run(() =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        string name = "[Secret]";
                        for (int i = 0; i < Users.Count; i++)
                        {
                            if (message.Sender == Users[i].ID)
                            {
                                name = Users[i].NameLabel.Content as string;
                            }
                        }
                        var window   = new RequestWindow(name, "<TextFile>");
                        window.Owner = this;
                        if (!SilenceControll.Mode)
                        {
                            window.Topmost = false;
                            window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                            if (!IsActive)
                            {
                                this.Show();
                                if (Icons != null)
                                {
                                    Icons.Visible = false;
                                }
                                this.WindowState = WindowState.Minimized;
                            }
                        }
                        Helper.FlashApplicationWindow();
                        window.ShowDialog();
                        if (window.Result)
                        {
                            var fileClass         = new FileClass(message.ElementID, message.Sender, Connection);
                            fileClass.CloseEvent += (FileClass obj) =>
                            {
                                FileClasses.Remove(obj);
                                GC.Collect();
                            };
                            fileClass.Start();
                            FileClasses.Add(fileClass);
                        }
                        else
                        {
                            Connection.SendMessage(new MessageClass(Connection.ID, message.Sender, Commands.FileMDenied, message.ElementID));
                        }
                    });
                });
            }

            if (message.Command == Commands.HFileModule)
            {
                var fileClass = new FileClass(message.ElementID, message.Sender, Connection);
                fileClass.CloseEvent += (FileClass obj) =>
                {
                    FileClasses.Remove(obj);
                    GC.Collect();
                };
                fileClass.Start();
                FileClasses.Add(fileClass);
            }

            if (message.Command == Commands.FileMAccepted)
            {
                try
                {
                    FindFileWindow(message.ElementID).Accept();
                }
                catch { }
            }

            if (message.Command == Commands.FileMDenied)
            {
            }

            if (message.Command == Commands.FilePulsar)
            {
                try
                {
                    FindFileClass(message.ElementID, message.Sender).Pulsar();
                }
                catch { }
            }

            if (message.Command == Commands.CD)
            {
                try
                {
                    byte[] data = FindFileClass(message.ElementID, message.Sender).CD(message.GetStringPackage());
                    Connection.SendMessage(new MessageClass(Connection.ID, message.Sender, Commands.Dirs, message.ElementID, data));
                }
                catch { }
            }

            if (message.Command == Commands.Dirs)
            {
                Dispatcher.Invoke(() =>
                {
                    try
                    {
                        FindFileWindow(message.ElementID).SetDirs(message.Package);
                    }
                    catch { }
                });
            }

            if (message.Command == Commands.Run)
            {
                try
                {
                    if (FindFileClass(message.ElementID, message.Sender) == null)
                    {
                        return;
                    }
                    ProcessStartInfo startInfo = new ProcessStartInfo(message.GetStringPackage());
                    startInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(message.GetStringPackage());
                    Process.Start(startInfo);
                }
                catch { }
            }

            if (message.Command == Commands.RunWith)
            {
                try
                {
                    if (FindFileClass(message.ElementID, message.Sender) == null)
                    {
                        return;
                    }
                    string[]         com       = message.GetStringPackage().Split(';');
                    ProcessStartInfo startInfo = new ProcessStartInfo(com[0], com[1]);
                    startInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(com[0]);
                    Process.Start(startInfo);
                }
                catch { }
            }

            if (message.Command == Commands.Delete)
            {
                try
                {
                    FileClass fileClass = FindFileClass(message.ElementID, message.Sender);
                    if (fileClass == null)
                    {
                        return;
                    }

                    string path = message.GetStringPackage();
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path);
                    }
                    else if (File.Exists(path))
                    {
                        File.Delete(path);
                    }

                    byte[] data = fileClass.CD(Path.GetDirectoryName(message.GetStringPackage()));
                    Connection.SendMessage(new MessageClass(Connection.ID, message.Sender, Commands.Dirs, message.ElementID, data));
                }
                catch { }
            }

            if (message.Command == Commands.StartDownload)
            {
                try
                {
                    Task.Run(() => FindFileClass(message.ElementID, message.Sender).StartDownload(message.GetStringPackage()));
                }
                catch { }
            }

            if (message.Command == Commands.StopDownload)
            {
                try
                {
                    FindFileClass(message.ElementID, message.Sender).StopDownload();
                }
                catch { }
            }

            if (message.Command == Commands.FileUData)
            {
                try
                {
                    FindFileClass(message.ElementID, message.Sender).SetData(message.Package);
                }
                catch { }
            }

            if (message.Command == Commands.FileUError)
            {
                try
                {
                    FindFileWindow(message.ElementID).SetUError(message.GetStringPackage());
                }
                catch { }
            }

            if (message.Command == Commands.FileDData)
            {
                try
                {
                    FindFileWindow(message.ElementID).SetData(message.Package);
                }
                catch { }
            }

            if (message.Command == Commands.GetDirInfo)
            {
                try
                {
                    Task.Run(() => FindFileClass(message.ElementID, message.Sender).GetDirInfo(message.GetStringPackage()));
                }
                catch { }
            }

            if (message.Command == Commands.DirInfo)
            {
                try
                {
                    FindFileWindow(message.ElementID).SetProp(message.Package);
                }
                catch { }
            }
            #endregion
        }
Пример #18
0
        /// <summary>
        /// Основной поток обработки
        /// </summary>
        /// <param name="obj">Форма процесса обработки, главная форма, список файлов для обработки</param>
        protected void delegate_action(object obj)
        {
            object [] data = (object[])obj;

            StatusWindow  window = (StatusWindow)data[0];
            MainWindow    wmain  = (MainWindow)data[1];
            List <string> files  = (List <string>)data[2];

            window.setState(true, "Подготовка файлов", 0, files.Count);

            wmain.Log(DataLog.LogImage.NONE, DateTime.Now.ToString("Начало конвертации dd.MM.yyyy в HH:mm:ss"));
            wmain.Log(DataLog.LogImage.NONE, "Директория: " + LastLaunch.Default.inputDirectory);
            wmain.Log(DataLog.LogImage.NONE, "Задано файлов для обработки: " + files.Count);

            if (config.only_rules)
            {
                CheckRules(files, window, wmain);
                return;
            }

            int   errcount    = 0;
            bool  reopenExcel = true;
            Excel excel       = null;
            DBF   dbf         = null;

            Stopwatch totalwatch = Stopwatch.StartNew();

            for (int idoc = 0; idoc < files.Count; idoc++)
            {
                string pathFull = files[idoc];
                string filename = Path.GetFileName(pathFull);
                string pathTemp = Path.GetTempFileName();

                bool deleteDbf = false;

                if (reopenExcel)
                {
                    excel       = new Excel();
                    reopenExcel = false;
                }

                try
                {
                    Logger.info("");
                    Logger.debug("");
                    Logger.debug("==============================================================");
                    Logger.info($"======= Загружаем Excel документ: {filename} ======");
                    Logger.debug("==============================================================");
                    window.updateState(true, $"Документ: {filename}", idoc);

                    excel.OpenWorksheet(pathFull);

                    var form = findCorrectForm(excel.worksheet, config);
                    if (form == null)
                    {
                        string warning = $"Для документа '{filename}' не найдено подходящих форм обработки!";
                        Logger.warn(warning);
                        wmain.Log(DataLog.LogImage.WARNING, warning);
                        throw new ArgumentNullException(warning);
                    }

                    string fileName   = getOutputFilename(excel.worksheet, pathFull, config.outfile.simple, config.outfile.script);
                    string pathOutput = Path.Combine(LastLaunch.Default.outputDirectory, fileName);

                    dbf = new DBF(pathTemp, form.DBF);

                    var total = excel.worksheet.UsedRange.Rows.Count - form.Fields.StartY;
                    window.setState(false, $"Обработано записей: {0}/{total}", 0, total);

                    Work     work    = new Work(form, config.buffer_size);
                    TimeSpan elapsed = work.IterateRecords(excel.worksheet, dbf.appendRecord,
                                                           id => window.updateState(false, $"Обработано записей: {id}/{total}", id)
                                                           );

                    dbf.close();

                    // Перемещение файла
                    if (File.Exists(pathOutput))
                    {
                        File.Delete(pathOutput);
                    }
                    File.Move(pathTemp, pathOutput);
                    Logger.debug($"Перемещение файла с {pathTemp} в {pathOutput}");

                    wmain.Log(
                        DataLog.LogImage.SUCCESS,
                        $"Документ '{filename}' в {dbf.Writed} строк успешно обработан за {elapsed:hh\\:mm\\:ss\\.ff}."
                        );
                    outlog.Add($"{filename} в {dbf.Writed} строк за {elapsed:hh\\:mm\\:ss\\.ff}");

                    Logger.info("Времени потрачено на обработку данных: " + elapsed);
                    Logger.info("Обработано записей: " + dbf.Writed);
                    Logger.debug($"Начиная с {form.Fields.StartY} по {form.Fields.StartY + dbf.Writed}");
                    Logger.info($"=============== Документ {Path.GetFileName(pathFull)} успешно обработан! ===============");
                }
                catch (Exception ex) when(!DEBUG)
                {
                    bool addToFormLog = true;

                    if (ex is COMException)
                    {
                        Logger.error("Excel вероятнее всего крашанулся, он будет перезапущен для следующего документа в очереди!");
                        reopenExcel = true;
                    }

                    if (ex is ThreadAbortException || ex.InnerException is ThreadAbortException)
                    {
                        Logger.warn($"Пользователь вышел во время процесса конвертации документа '{filename}'!");
                        goto skip_error_msgbox;
                    }

                    if (ex is ArgumentNullException)
                    {
                        if (!config.no_form_is_error)
                        {
                            continue;
                        }
                        addToFormLog = false;
                    }

                    if (addToFormLog)
                    {
                        wmain.Log(DataLog.LogImage.ERROR, $"Документ '{filename}' был пропущен из-за ошибки!\n{ex.Message}");
                    }
                    Logger.error($"Документ {filename} был пропущен из-за ошибки:\n{ex.Message}\n\n{ex.StackTrace}");

skip_error_msgbox:
                    errcount++;
                    deleteDbf = true;
                }
                finally
                {
                    Logger.debug("Закрытие COM Excel и DBF");
                    dbf?.close();
                    if (deleteDbf)
                    {
                        dbf?.delete();
                    }
                }
            }
            totalwatch.Stop();

            // Не забываем завершить Excel
            excel.close();

            string msgTotal = $"\nВремени затрачено суммарно: {totalwatch.Elapsed:hh\\:mm\\:ss\\.ff}";

            wmain.Log(DataLog.LogImage.INFO, msgTotal);
            Logger.info(msgTotal);

            if (errcount > 0)
            {
                wmain.Log(DataLog.LogImage.ERROR, config.warning ?? "{0}");
            }

            wmain.toggleConvertButton(true);
            updateDirectory();
            wmain.BeginInvoke((MethodInvoker)wmain.fillElementsData);
            window.mayClose();
        }
Пример #19
0
        /// <summary>
        /// Запускает процесс конвертирования файлов в отдельном потоке
        /// Вызывается по кнопке "Конвертировать" на форме
        /// </summary>
        /// <param name="wmain">Окно, которое вызывает процесс конвертации</param>
        /// <param name="selectedfiles">Список файлов для конвертирования (с учётом выбора пользователя)</param>
        public bool action(MainWindow wmain, HashSet <string> selectedfiles)
        {
            if (selectedfiles.Count == 0)
            {
                MessageBox.Show($"Вы выбрали 0 файлов!\nДля продолжения выберите хотя бы один файл!",
                                "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }

            if (selectedfiles.Count == 0 && filesExcel.Count == 0)
            {
                MessageBox.Show($"В директории нет Excel файлов для обработки!\nВыберите другую директорию!\n\n{LastLaunch.Default.inputDirectory}",
                                "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }

            if (process != null && process.IsAlive)
            {
                MessageBox.Show("Процесс конвертирования уже запущен!\nДождись его завершения, если вы хотите начать новый.", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }

            StatusWindow wstatus = new StatusWindow();

            wstatus.FormClosing += delegate(object sender, FormClosingEventArgs e)
            {
                if (e.CloseReason != CloseReason.UserClosing)
                {
                    return;
                }
                if (wstatus.codeClose)
                {
                    return;
                }
                e.Cancel = DialogResult.No == MessageBox.Show("Вы действительно хотите прервать обработку файлов?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (!e.Cancel)
                {
                    process.Abort();
                    wstatus.mayClose();
                    MessageBox.Show(wmain, "Документы не были обработаны: процесс был прерван пользователем!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            };
            wstatus.Location = new Point(
                wmain.Location.X + ((wmain.Width - wstatus.Width) / 2),
                wmain.Location.Y + ((wmain.Height - wstatus.Height) / 2)
                );
            wstatus.Show(wmain);
            // Альтернативный вариант:
            //wstatus.StartPosition = FormStartPosition.CenterParent;
            //wstatus.ShowDialog(wmain);

            object data = new object[] { wstatus, wmain, selectedfiles.ToList() };

            outlog.Clear();
            errlog.Clear();
            formToFile.Clear();

            wmain.toggleConvertButton(false);
            process = new Thread(delegate_action);
            process.Start(data);
            return(true);
        }
Пример #20
0
        public async Task SendPrivateMessage(string toUserId, string message)
        {
            string fromUserId = Context.User.Identity.Name;
            var    idFromUser = db.UserLogins.FirstOrDefault(u => u.UserNameCopy == fromUserId).Id;
            int    i;

            if (int.TryParse(toUserId, out i)) // send group
            {
                var listGroup       = db.Group_User.Where(gu => gu.GroupId == i && gu.UserOfGroup != idFromUser).ToList();
                var listUserInGroup = new List <string>();
                var GroupName       = db.Groups.FirstOrDefault(g => g.GroupId == i).GroupName;

                foreach (var item in listGroup)
                {
                    listUserInGroup.Add(item.UserLogin.UserNameCopy);
                    //GroupName += item.UserLogin.UserNameCopy + "|";

                    // lưu trạng thái nếu chưa nhận dc tin
                    var group = db.StatusWindows.FirstOrDefault(sw => sw.KeyWindowName == toUserId && sw.UserName == item.UserLogin.UserNameCopy);
                    if (group == null)
                    {
                        StatusWindow sw = new StatusWindow
                        {
                            CtrId         = "Group_" + i,
                            WindowName    = GroupName,
                            TopPosition   = "200" + "px",
                            LeftPosition  = "100" + "px",
                            UserName      = item.UserLogin.UserNameCopy,
                            KeyWindowName = toUserId
                        };
                        db.StatusWindows.Add(sw);
                        await db.SaveChangesAsync();
                    }
                }


                Group_User_Messege group_User_Messege = new Group_User_Messege
                {
                    ConentMesseger = message,
                    CreatedDate    = DateTime.Now,
                    GroupId        = i,
                    WhoChat        = fromUserId
                };
                try
                {
                    db.Group_User_Messege.Add(group_User_Messege);
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    throw;
                }
                // send group
                Clients.Users(listUserInGroup).sendPrivateMessage(toUserId, fromUserId, message, "G", GroupName);

                // send to caller user
                Clients.Caller.sendPrivateMessage(toUserId, fromUserId, message, "G", GroupName);
            }
            else // send direct messenge
            {
                var           idToUser      = db.UserLogins.FirstOrDefault(u => u.UserNameCopy == toUserId).Id;
                MessegeDirect messegeDirect = new MessegeDirect
                {
                    ConentMesseger = message,
                    CreatedDate    = DateTime.Now,
                    FromUser       = idFromUser,
                    ToUser         = idToUser,
                    WhoChat        = fromUserId
                };

                // lưu trạng thái nếu chưa nhận dc tin
                var Frompirvate = db.StatusWindows.FirstOrDefault(sw => sw.KeyWindowName == toUserId && sw.UserName == fromUserId);
                if (Frompirvate == null)
                {
                    StatusWindow sw = new StatusWindow
                    {
                        CtrId         = "private_" + toUserId,
                        WindowName    = toUserId,
                        TopPosition   = "200" + "px",
                        LeftPosition  = "100" + "px",
                        UserName      = fromUserId,
                        KeyWindowName = toUserId
                    };
                    db.StatusWindows.Add(sw);
                    //await db.SaveChangesAsync();
                }
                var topirvate = db.StatusWindows.FirstOrDefault(sw => sw.KeyWindowName == fromUserId && sw.UserName == toUserId);
                if (topirvate == null)
                {
                    StatusWindow sw = new StatusWindow
                    {
                        CtrId         = "private_" + fromUserId,
                        WindowName    = fromUserId,
                        TopPosition   = "200" + "px",
                        LeftPosition  = "100" + "px",
                        UserName      = toUserId,
                        KeyWindowName = fromUserId
                    };
                    db.StatusWindows.Add(sw);
                    //await db.SaveChangesAsync();
                }
                //end

                db.MessegeDirects.Add(messegeDirect);
                await db.SaveChangesAsync();

                // send to

                Clients.User(toUserId).sendPrivateMessage(fromUserId, fromUserId, message, "P", fromUserId);

                // send to caller user
                Clients.Caller.sendPrivateMessage(toUserId, fromUserId, message, "P", fromUserId);
            }
            // tạo cua so khi khong nhan dc  tin nhắn
            //var checkesistwindow = db.StatusWindows.Where(w => w.CtrId == ctrId && w.UserName == User.Identity.Name).ToList();
        }