Example #1
0
 private void SetTimer(runtimer t)
 {
     SyncTimer.Stop();
     SyncTimer.Tag      = t;
     SyncTimer.Interval = 10;
     SyncTimer.Start();
 }
Example #2
0
 private void WriteLinks()
 {
     SyncTimer.Stop();
     if (sv != null && onedriveitems != null && onedriveitems.Count > 0)
     {
         var newdriveitems = onedriveitems.Where(n => n.isnew == true);
         foreach (OneDriveItem item in newdriveitems)
         {
             if (bstop == true)
             {
                 bstop = false;
                 sb.AppendLine("Stopped by user");
                 richTextStatus.Text = sb.ToString();
                 richTextStatus.Refresh();
                 SetStateReady();
                 return;
             }
             sv.WriteLink(item.Row, item.Link);
             sb.AppendLine();
             sb.AppendLine(item.Path);
             sb.AppendLine(item.Link);
         }
     }
     SetTimer(WrapUp);
 }
        public override void StartServer()
        {
            // 新建一个后台处理线程  进行初始化相关的 与服务器自己运行的, 及机器人等逻辑
            Thread.CurrentThread.IsBackground = true;
            Thread processor = new Thread(new ThreadStart(StartAutoSendData)); //

            processor.Start();                                                 //线程开始


            ////// 新建一个后台处理线程  服务器向客户端 主动发信息 保证发送消息的流畅
            ////Thread.CurrentThread.IsBackground = true;
            ////Thread msgProcessor = new Thread(new ThreadStart(StartRobot));//
            ////msgProcessor.Start();//线程开始
            BullColorLobby.instance.Initi();
            InitiRobotList();// 获取机器人列表
            //间隔1秒执行,延迟2000毫秒开始启动,执行10分钟超时    测试时候用
            SyncTimer testTimer = new SyncTimer(StartRobotTimer, 5000, 1000, 10 * 60 * 1000);

            testTimer.Start();

            SyncTimer _syncTimer = new SyncTimer(AddOnlineInformation, 1, 60000, 60 * 1000);

            _syncTimer.Start();
            base.StartServer();
        }
Example #4
0
 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     SyncTimer.Stop();
     if (sv != null)
     {
         sv.Wrapup();
     }
 }
Example #5
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            StartupBox.Checked = Properties.Settings.Default.Startup;

            Bidirectional.Checked = Properties.Settings.Default.Bidir;

            TimerBox.Checked        = Properties.Settings.Default.Timer;
            comboBox1.SelectedIndex = Properties.Settings.Default.TimeType;
            timeBox.Value           = Properties.Settings.Default.TimeAmount;

            numDayHour.Value   = Properties.Settings.Default.DayHour;
            numDayMinute.Value = Properties.Settings.Default.DayMinute;

            SyncTimer.Interval = (1000) * Convert.ToInt32(timeBox.Value) * Convert.ToInt32(Math.Pow(60, comboBox1.SelectedIndex));

            if (TimerBox.Checked)
            {
                SyncTimer.Start();
                timeBox.Enabled   = true;
                comboBox1.Enabled = true;
            }
            else
            {
                SyncTimer.Stop();
                timeBox.Enabled   = false;
                comboBox1.Enabled = false;
            }

            destBox.Text = Properties.Settings.Default.Destination;
            if (destBox.Text[0] == '\\' && destBox.Text[1] == '\\')
            {
                IsUNCPath = true;
            }
            destBox.SelectionLength = 0;
            destBox.SelectionStart  = destBox.Text.Length;

            richTextBox1.Text = Properties.Settings.Default.Folders;

            FixTimer();
            DayCheck.Checked = Properties.Settings.Default.DayTimer;
            if (DayCheck.Checked)
            {
                DailyTimer.Start();
                numDayHour.Enabled   = true;
                numDayMinute.Enabled = true;
            }
            else
            {
                DailyTimer.Stop();
                numDayHour.Enabled   = false;
                numDayMinute.Enabled = false;
            }

            SyncTimer.Tick  += new EventHandler(SyncButton_Click);
            DailyTimer.Tick += new EventHandler(SyncDailyTimer);
        }
Example #6
0
 private void SyncTimer_Tick(object sender, EventArgs e)
 {
     SyncTimer.Stop();
     SyncTimer.Interval = 30000;
     if (SyncTimer.Tag != null && SyncTimer.Tag is runtimer)
     {
         SyncTimer.Start();
         (SyncTimer.Tag as runtimer).Invoke();
     }
 }
Example #7
0
 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     Properties.Settings.Default.TimeType = comboBox1.SelectedIndex;
     SyncTimer.Interval = (1000) * Convert.ToInt32(timeBox.Value) * Convert.ToInt32(Math.Pow(60, comboBox1.SelectedIndex));
     SyncTimer.Stop();
     if (TimerBox.Checked)
     {
         SyncTimer.Start();
     }
 }
Example #8
0
        public static void Start()
        {
            mStopWatch = new Stopwatch();
            mTimer     = new SyncTimer(Tick, 0, 33);

            mTimer.Start();
            mStopWatch.Start();
            DeltaTime = 0.0f;
            mLastTime = mStopWatch.ElapsedMilliseconds;
        }
 private void StartSyncTimer(int duration)
 {
     SyncTimer.Stop();
     if (duration < 0)
     {
         return;
     }
     SyncTimer.Interval = duration;
     SyncTimer.Start();
 }
Example #10
0
        private void AddParameters_Button_Click(object sender, RoutedEventArgs e)
        {
            TimeSettings dialog = new TimeSettings(syncTimer, backupCount);

            if (dialog.ShowDialog() == true)
            {
                backupCount = dialog.BackupCount;
                syncTimer   = dialog.SyncTimer;
            }
        }
Example #11
0
        private void ValidateExcel()
        {
            SyncTimer.Stop();
            SetStateRunning();
            string excelfile = string.Format(@"{0}\Karaoke\CDG_MP3\Index\{1}", txtOneDriveRoot.Text.Trim(), txtExcel.Text.Trim());

            if (File.Exists(excelfile) == true)
            {
                try
                {
                    onedriveitems = new List <OneDriveItem>();
                    sv            = new SpreadsheetValidator(excelfile, blink);

                    int row   = 2;
                    int nrows = sv.nCnt;
                    while (row < nrows)
                    {
                        Application.DoEvents();
                        if (bstop == true)
                        {
                            bstop = false;
                            sb.AppendLine("Stopped by user");
                            richTextStatus.Text = sb.ToString();
                            richTextStatus.Refresh();
                            SetStateReady();
                            return;
                        }
                        OneDriveItem cellpath = sv.Run(row);
                        if (blink == true)
                        {
                            if (cellpath != null && cellpath.Path != null && cellpath.Path.Trim().Length > 0)
                            {
                                onedriveitems.Add(cellpath);
                            }
                        }
                        richTextStatus.Text = sb.ToString() + "\n\n" + sv.status;
                        row++;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Unexpected error");
                }
            }
            SetStateReady();
            if (blink == false)
            {
                SetTimer(WrapUp);
            }
            else
            {
                SetTimer(SetOneDriveLinks);
            }
        }
Example #12
0
        private void WorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
        {
            AppSettings.RefreshSettings();
            UsuarioActual.ResetearValoresCacheados();

            if (_secuenciaDesfasada)
            {
                CurrentForm.Invoke(new ActualizarMensajeDelegate(ActualizarMensaje), "Reanudando sincronización en pocos segundos..");
            }
            else
            {
                if (_huboError)
                {
                    CurrentForm.Invoke(new ActualizarMensajeDelegate(ActualizarMensaje), "Sincronización finalizada con errores");
                }
                else
                {
                    CurrentForm.Invoke(new ActualizarMensajeDelegate(ActualizarMensaje), "Sincronización finalizada");
                    ActualizacionPantallasHelper.ActualizarPantallaVentas();

                    if (SyncExitosaEvent != null)
                    {
                        SyncExitosaEvent();
                    }
                }
            }

            if (SyncTimer != null)
            {
                SyncTimer.Stop();
            }
            else
            {
                SyncTimer       = new Timer();
                SyncTimer.Tick += SyncTimerOnTick;
            }

            if (UsuarioActual.Cuenta.SincronizarAutomaticamente.GetValueOrDefault())
            {
                var interval = _secuenciaDesfasada
                                    ? 10 * 1000                                                                       //10 segundos
                                    : (_huboError
                                        ? 5 * 60 * 1000                                                               //5 minutos
                                        : UsuarioActual.Cuenta.IntervaloSincronizacion.GetValueOrDefault() * 360000); //confiuracion
                SyncTimer.Interval = interval;
                SyncTimer.Start();
            }

            Timer = new Timer {
                Interval = 5000
            };
            Timer.Tick += TimerOnTick;
            Timer.Start();
        }
Example #13
0
        public CreateTaskDialog(SyncCore syncCore, SyncTask syncTask) : this(syncCore)
        {
            localPaths.AddRange(syncTask.LocalPaths);
            selectedUri = syncTask.ServerDirectoryUri;
            backupCount = syncTask.BackupCount;
            syncTimer   = syncTask.SyncTimer;

            LocalPaths_ListBox.Items.Refresh();
            SelectedDirName_TexBlock.Text = syncTask.ServerDirName;
            backupCount = syncTask.BackupCount;
        }
Example #14
0
        private async void ReadyCheck()
        {
            if (this.liveConnectClient == null)
            {
                SigninButton_Click(this, new EventArgs());
                return;
            }
            SetStateRunning();
            parents = new Dictionary <string, string>();
            sb.Clear();
            sb.AppendLine(String.Format("Started: {0}", DateTime.Now.ToShortTimeString()));

            richTextStatus.Text = sb.ToString();
            richTextStatus.Refresh();

            try
            {
                string excelfile = string.Format(@"{0}\Karaoke\CDG_MP3\Index\{1}", txtOneDriveRoot.Text.Trim(), txtExcel.Text.Trim());
                if (txtExcel.Text.Trim().Length == 0 || txtOneDriveRoot.Text.Trim().Length == 0 || File.Exists(excelfile) == false)
                {
                    MessageBox.Show(string.Format("Excel document not found\n{0}", excelfile), "Path not found");
                    SetStateReady();
                    return;
                }
                LiveOperationResult rootresult = await this.liveConnectClient.GetAsync("me/skydrive");

                if (rootresult == null || rootresult.Result == null)
                {
                    MessageBox.Show("OneDrive root not found", "Path not found");
                    SetStateReady();
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Unexpected error");
                SetStateReady();
                return;
            }
            finally
            {
            }
            SetStateReady();
            SyncTimer.Stop();
            if (bfiles == true)
            {
                SetTimer(ValidateFiles);
            }
            else
            {
                SetTimer(ValidateExcel);
            }
        }
Example #15
0
 private void StopTimer()
 {
     if (this.InvokeRequired)
     {
         StopTimerDelegate d = new StopTimerDelegate(StopTimer);
         this.Invoke(d, null);
     }
     else
     {
         SyncTimer.Stop();
     }
 }
Example #16
0
 static GameSession()
 {
     HeartbeatTimeout = 60;          //60s
     RequestTimeout   = 500;
     Timeout          = 2 * 60 * 60; //2H
     clearTime        = new SyncTimer(OnClearSession, 6000, 60000);
     clearTime.Start();
     _globalSession = new ConcurrentDictionary <Guid, GameSession>();
     _userHash      = new ConcurrentDictionary <int, Guid>();
     _remoteHash    = new ConcurrentDictionary <string, Guid>();
     LoadUnLineData();
 }
Example #17
0
        public CreateTaskDialog(SyncCore syncCore)
        {
            InitializeComponent();

            MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
            MaxWidth  = SystemParameters.MaximizedPrimaryScreenWidth;

            backupCount = 0;
            syncTimer   = new SyncTimer();
            core        = syncCore;
            localPaths  = new List <string>();
            LocalPaths_ListBox.ItemsSource = localPaths;
            ShowRootDir();
        }
Example #18
0
        /////////////////////////////////////////////////////////////////////////////////////////////////////////

        private void TimerBox_CheckedChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.Timer = SyncTimer.Enabled = TimerBox.Checked;
            if (TimerBox.Checked)
            {
                SyncTimer.Start();
                timeBox.Enabled   = true;
                comboBox1.Enabled = true;
            }
            else
            {
                SyncTimer.Stop();
                timeBox.Enabled   = false;
                comboBox1.Enabled = false;
            }
        }
Example #19
0
        public TimeSettings(SyncTimer syncTimer, int backupCount) : this()
        {
            SyncTimer = syncTimer;

            BackupCount_TextBox.Text     = backupCount.ToString();
            IsEnabled_CheckBox.IsChecked = syncTimer.IsEnabled;
            startDatePicker.SelectedDate = syncTimer.StartDate;
            startTimePicker.Value        = syncTimer.StartDate;
            var checkedButton = container.Children.OfType <RadioButton>()
                                .FirstOrDefault(r => r.Name == syncTimer.Type.ToString());

            checkedButton.IsChecked = true;
            Days.Value    = syncTimer.Period.Days;
            Hours.Value   = syncTimer.Period.Hours;
            Minutes.Value = syncTimer.Period.Minutes;
        }
Example #20
0
 private void timeBox_ValueChanged(object sender, EventArgs e)
 {
     if (timeBox.Value == 0)
     {
         timeBox.Value = 59;
     }
     else if (timeBox.Value == 60)
     {
         timeBox.Value = 1;
     }
     Properties.Settings.Default.TimeAmount = Convert.ToInt32(timeBox.Value);
     SyncTimer.Interval = (1000) * Convert.ToInt32(timeBox.Value) * Convert.ToInt32(Math.Pow(60, comboBox1.SelectedIndex));
     SyncTimer.Stop();
     if (TimerBox.Checked)
     {
         SyncTimer.Start();
     }
 }
Example #21
0
        public override void StartServer()
        {
            //建一个后台处理线程  进行初始化相关的 与服务器自己运行的, 及机器人等逻辑
            Thread.CurrentThread.IsBackground = true;
            Thread processor = new Thread(new ThreadStart(StartAutoSendData)); //

            processor.Start();                                                 //线程开始


            TCLobby.instance.Initi(); // 初始化 大厅 及下面的 房间 与桌子
            InitiRobotList();         // 获取机器人列表
            //间隔1秒执行,延迟2000毫秒开始启动,执行10分钟超时    测试时候用
            SyncTimer testTimer = new SyncTimer(StartRobotTimer, 2000, 1000, 10 * 60 * 1000);

            testTimer.Start();

            base.StartServer();
        }
Example #22
0
 public RoomUpdater(Room roomData)
 {
     m_SyncTimer        = new SyncTimer(OnUpdate, 0, 100);
     m_Room             = roomData;
     MessageQueue       = new List <Message>();
     m_ActionProcessors = new Dictionary <ActionType, BaseActionProcessor>()
     {
         { ActionType.GetRoomInfo, new GetRoomInfoProcessor(roomData) },
         { ActionType.CREntityMove, new EntityMoveProcessor(roomData) },
         { ActionType.CREntityPerformSkillStart, new EntityPerformSkillStartProcessor(roomData) },
         { ActionType.CREntityPerformSkillEnd, new EntityPerformSkillEndProcessor(roomData) },
         { ActionType.CREntityImpact, new EntityPerformSkillImpactProcessor(roomData) },
         { ActionType.GiveUpBattle, new PlayerGiveUpProcessor(roomData) },
         { ActionType.EntitySwitchHero, new EntitySwitchHeroProcessor(roomData) },
         { ActionType.CREntityPerformSkillFF, new EntityPerformSkillFFProcessor(roomData) },
         { ActionType.CREntitySKillRushing, new EntitySkillRushingProcessor(roomData) },
         { ActionType.CREntityAddBuff, new EntityAddBuffProcessor(roomData) },
         { ActionType.CREntityRemoveBuff, new EntityRemoveBuffProcessor(roomData) },
         { ActionType.CRRoomReady, new RoomReadyProcessor(roomData) },
     };
 }
Example #23
0
        /// <summary>
        ///
        /// </summary>
        public static void Start()
        {
            _refreshTime = DateTime.Now;
            int intervalSecond = GetSection().ProfileCollectInterval;

            _operateTimer = new SyncTimer(obj => WriteToStorage(), 1000, 1000);
            _operateTimer.Start();
            _collectTimer = new SyncTimer(obj => Collect(), 100, intervalSecond * 1000);
            _collectTimer.Start();
            StorageMode = ProfileStorageMode.File;

            if (WorkingLogPath.ToLower().StartsWith("mysql:"))
            {
                StorageMode = ProfileStorageMode.MySql;
                CheckLogTable(typeof(MySqlDataProvider).Name, WorkingLogPath.Substring(6));
            }
            else if (WorkingLogPath.ToLower().StartsWith("sql:"))
            {
                StorageMode = ProfileStorageMode.Sql;
                CheckLogTable(typeof(SqlDataProvider).Name, WorkingLogPath.Substring(4));
            }
        }
Example #24
0
        private void WrapUp()
        {
            SyncTimer.Stop();
            SetStateRunning();
            if (sv != null)
            {
                sv.Wrapup();
                sb.AppendLine();
                sb.AppendLine("Rows: " + sv.Rows);
                sb.AppendLine("CDGs: " + sv.CDGs);
                sb.AppendLine("ZIPs: " + sv.ZIPs);
                sb.AppendLine("URLs: " + sv.URLs);
                sb.AppendLine("Bads: " + sv.Bads);
                sb.AppendLine("Not Found: " + sv.NotFound);
                if (sv.PathNotFound.Count > 0 && sv.PathNotFound.Count < 100)
                {
                    foreach (string path in sv.PathNotFound)
                    {
                        sb.AppendLine(path);
                    }
                }
                richTextStatus.Text = sb.ToString();
                richTextStatus.Refresh();
                //StreamWriter swd = File.CreateText(@"c:\temp\zipd.txt");
                //StreamWriter swa = File.CreateText(@"c:\temp\zipa.txt");
                //StreamWriter swi = File.CreateText(@"c:\temp\zid3.txt");
                //swd.Write(sv.zipdelete.ToString());
                //swa.Write(sv.zipadd.ToString());
                //swi.Write(sv.id3.ToString());
                //swd.Close();
                //swa.Close();
                //swi.Close();
            }

            SetStateReady();
        }
Example #25
0
        private void ValidateFiles()
        {
            SyncTimer.Stop();
            SetStateRunning();
            string excelfile = string.Format(@"{0}\Karaoke\CDG_MP3\Index\{1}", txtOneDriveRoot.Text.Trim(), txtExcel.Text.Trim());

            if (File.Exists(excelfile) == true)
            {
                try
                {
                    onedriveitems = new List <OneDriveItem>();
                    sv            = new SpreadsheetValidator(excelfile, blink);
                    List <string> cdgfiles = new List <string>();
                    List <string> zipfiles = new List <string>();

                    int row   = 2;
                    int nrows = sv.nCnt;
                    while (row < nrows)
                    {
                        Application.DoEvents();
                        if (bstop == true)
                        {
                            bstop = false;
                            sb.AppendLine("Stopped by user");
                            richTextStatus.Text = sb.ToString();
                            richTextStatus.Refresh();
                            SetStateReady();
                            return;
                        }
                        OneDriveItem cellpath = sv.Run(row);
                        if (cellpath != null && cellpath.Path != null && cellpath.Path.Trim().Length > 0)
                        {
                            cdgfiles.Add(cellpath.PathCDG.ToLower());
                            zipfiles.Add(cellpath.PathZIP.ToLower());
                        }
                        richTextStatus.Text = sb.ToString() + "\n\n" + sv.status;
                        row++;
                    }
                    if (bzip == true)
                    {
                        string   rootfile    = string.Format(@"{0}\Karaoke\CDG_ZIP", txtOneDriveRoot.Text.Trim());
                        string[] files       = Directory.GetFiles(rootfile, "*.zip", SearchOption.AllDirectories);
                        var      missingzips = files.Where(n => zipfiles.Contains(n.ToLower()) == false);
                        foreach (string file in missingzips)
                        {
                            sb.AppendLine(file);
                        }
                    }
                    else
                    {
                        string   rootfile    = string.Format(@"{0}\Karaoke\CDG_MP3", txtOneDriveRoot.Text.Trim());
                        string[] files       = Directory.GetFiles(rootfile, "*.cdg", SearchOption.AllDirectories);
                        var      missingcdgs = files.Where(n => cdgfiles.Contains(n.ToLower()) == false);
                        foreach (string file in missingcdgs)
                        {
                            sb.AppendLine(file);
                        }
                    }
                    richTextStatus.Text = sb.ToString();
                    richTextStatus.Refresh();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Unexpected error");
                }
            }
            SetStateReady();
            SetTimer(WrapUp);
        }
Example #26
0
 private void CreateTask(List <string> localPaths, Uri serverDirUri, SyncTimer syncTimer, int backupCount)
 {
     SyncTask = SyncTask.CreateSyncTask(localPaths, serverDirUri, syncTimer, backupCount);
 }
Example #27
0
        public static SyncTasksModel LoadTasks(string userServer)
        {
            SyncTasksModel model = new SyncTasksModel
            {
                UserServer = userServer
            };

            try
            {
                string    filePath  = Settings.FilesSavePath + userServer + ".xml";
                XDocument syncTasks = XDocument.Load(filePath);

                string logPath = syncTasks.Root.Attribute("Файл_логов").Value;

                List <SyncTask> tasks = new List <SyncTask>();
                foreach (XElement task in syncTasks.Root.Elements("Задача"))
                {
                    List <string> paths = new List <string>();
                    foreach (XElement path in task.Element("Папки_на_компьютере").Elements("Папка"))
                    {
                        paths.Add(path.Value);
                    }

                    Uri serverDirectoryUri = new Uri(task.Element("Папка_на_сервере").Value);

                    DateTime createDate = DateTime.MinValue;
                    if (DateTime.TryParse(task.Element("Дата_создания").Value, out DateTime cdate))
                    {
                        createDate = cdate;
                    }

                    DateTime?lastSyncDate = null;
                    if (DateTime.TryParse(task.Element("Дата_последней_синхронизации").Value, out DateTime ldate))
                    {
                        lastSyncDate = ldate;
                    }

                    int backupCount = int.Parse(task.Element("Количество_версий").Value);

                    SyncTimer syncTimer = new SyncTimer();
                    XElement  timer     = task.Element("Таймер");
                    if (bool.TryParse(timer.Element("Синхронизация").Value, out bool isEnabled))
                    {
                        syncTimer.IsEnabled = isEnabled;
                    }

                    if (DateTime.TryParse(timer.Element("Дата_начала_синхнонизации").Value, out DateTime startDate))
                    {
                        syncTimer.StartDate = startDate;
                    }
                    else
                    {
                        syncTimer.StartDate = DateTime.MinValue;
                    }

                    string timerType = timer.Element("Тип_синхронизации").Value;
                    switch (timerType)
                    {
                    case "EveryDay":
                        syncTimer.Type = SyncTimerType.EveryDay;
                        break;

                    case "Custom":
                        syncTimer.Type = SyncTimerType.Custom;
                        break;

                    case "Once":
                    default:
                        syncTimer.Type = SyncTimerType.Once;
                        break;
                    }

                    if (TimeSpan.TryParse(timer.Element("Период_синхронизации").Value, out TimeSpan period))
                    {
                        syncTimer.Period = period;
                    }

                    SyncTask syncTask = new SyncTask(paths, serverDirectoryUri, createDate, syncTimer, lastSyncDate, backupCount);
                    tasks.Add(syncTask);
                }

                model.SyncTasks = tasks;
                model.LogPath   = logPath;

                LogController.Info(logger, $"Файл {userServer}.xml успешно загружен");
            }
            catch (Exception e)
            {
                LogController.Error(logger, e, $"Не удалось загрузить файл {userServer}.xml");
            }

            return(model);
        }
Example #28
0
        //оброботка входящих данных из сети
        private void M_TcpClient_Receive(object sender, SocketData s)
        {
            // TcpModule tcp = (TcpModule)sender;
            NetworkTransferObjects obj = (NetworkTransferObjects)sender;

            //проверка соединения
            if (obj.ProtocolMessage == ProtocolOfExchange.CheckConnectionOK)
            {
                m_IsConnectedToServer = true;
                this.Invoke((new Action(() => connectionStatusLabel.BackColor = Color.Green)));
                TimeOutTimer.Stop();
                SendReqest(ProtocolOfExchange.AskUserInfoList, new NetworkTransferObjects());
            }
            //получение списка пользователей для выбора при авторизации
            if (obj.ProtocolMessage == ProtocolOfExchange.UserInfoListOk)
            {
                m_UserInfoArray = (List <UserInfo>)obj.ListUserInfo;
                this.Invoke((new Action(() => UserListRecieved())));
            }

            if (obj.ProtocolMessage == ProtocolOfExchange.AuthOk)
            {
                m_CurrentUser = obj.User;
                m_CurrentAuth = obj.AuthInfo;
                this.Invoke((new Action(() => MessageBox.Show("Вы авторизированы"))));
                this.Invoke((new Action(() => this.Text = m_CurrentUser.FullName)));
                this.Invoke((new Action(() => SyncTimer_Tick(null, null))));
                this.Invoke((new Action(() => SyncTimer.Start())));
            }
            if (obj.ProtocolMessage == ProtocolOfExchange.AuthFail)
            {
                this.Invoke((new Action(() => UserListRecieved())));
            }
            //временно

            /* if (e.sendInfo.ProtocolMsg== ProtocolOfExchange.AddUserOK)
             *   this.Invoke((new Action(() => MessageBox.Show("UserAdded"))));*/

            if (obj.ProtocolMessage == ProtocolOfExchange.SyncMessages)
            {
                if (obj.AuthInfo.UserId == m_CurrentUser.Id)
                {
                    if (obj.Message != null)
                    {
                        m_inbox.Add(obj.Message);
                    }
                    if (obj.Message_1 != null)
                    {
                        m_outbox.Add(obj.Message_1);
                    }
                    this.Invoke((new Action(() => SyncMessageInbox())));
                }
            }
            if (obj.ProtocolMessage == ProtocolOfExchange.NewVersionClientNone)
            {
                this.Invoke((new Action(() => MessageBox.Show("Нет новых обновлений"))));
            }
            if (obj.ProtocolMessage == ProtocolOfExchange.NewVersionClientOk)
            {
                this.Invoke((new Action(() => System.Diagnostics.Process.Start("Updater.exe", m_ServerIp + " 5454"))));
                this.Invoke((new Action(() => this.Close())));
            }
        }
Example #29
0
        public async void SetOneDriveLinks()
        {
            SyncTimer.Stop();
            SetStateRunning();
            OneDriveFolder rootfolder = null;

            if (onedriveitems != null && onedriveitems.Count > 0)
            {
                int titems = onedriveitems.Count;
                sb.AppendLine("Item Count: " + titems.ToString());
                int nitems  = 0;
                int nerrors = 0;
                foreach (OneDriveItem item in onedriveitems)
                {
                    nitems++;
                    if (bstop == true)
                    {
                        bstop = false;
                        sb.AppendLine("Stopped by user");
                        richTextStatus.Text = sb.ToString();
                        richTextStatus.Refresh();
                        SetStateReady();
                        return;
                    }
                    string karaoke     = "/karaoke/";
                    string lowpath     = item.Path.Trim().ToLower();
                    string therootpath = item.Path.Trim().Replace('\\', '/');
                    string lowrootpath = therootpath.ToLower();
                    if (lowrootpath.StartsWith("http") == true || lowrootpath.StartsWith("www") == true)
                    {
                        item.Link = item.Path;
                        continue;
                    }
                    int ixi = lowrootpath.IndexOf(karaoke);
                    int ixe = therootpath.LastIndexOf('/');
                    if (!(ixi > 0 && ixi < ixe))
                    {
                        item.Link = item.Path;
                        sb.AppendLine(string.Format("Path not found: {0}", therootpath));
                        richTextStatus.Text = sb.ToString();
                        richTextStatus.Refresh();
                        if (nerrors++ < 20)
                        {
                            continue;
                        }
                        else
                        {
                            sb.AppendLine("Excessive not found errors - aborting...");
                            richTextStatus.Text = sb.ToString();
                            richTextStatus.Refresh();
                            SetStateReady();
                            return;
                        }
                    }
                    if (item.Link != null && item.Link.Trim().Length > 0)
                    {
                        signinButton.Enabled  = true;
                        signOutButton.Enabled = true;
                    }
                    else
                    {
                        string   thefile   = Path.GetFileName(therootpath);
                        string   rootpath  = therootpath.Substring(ixi + 1, ixe - ixi - 1);
                        string[] rootpaths = rootpath.Split('/');
                        rootpath = "me/skydrive";
                        foreach (string root in rootpaths)
                        {
                            if (bstop == true)
                            {
                                bstop = false;
                                sb.AppendLine("Stopped by user");
                                richTextStatus.Text = sb.ToString();
                                richTextStatus.Refresh();
                                SetStateReady();
                                return;
                            }
                            if (parents.ContainsKey(root) == true)
                            {
                                rootfolder = new OneDriveFolder("", parents[root], root, "");
                                rootpath   = parents[root];
                            }
                            else
                            {
                                richTextStatus.Text = sb.ToString() + String.Format("Finding root: {0}", root);
                                richTextStatus.Refresh();
                                LiveOperationResult   rootresult  = null;
                                List <OneDriveFolder> rootfolders = new List <OneDriveFolder>();
                                try
                                {
                                    rootresult = await this.liveConnectClient.GetAsync(string.Format("{0}/files", rootpath));

                                    if (rootresult != null && rootresult.Result != null && rootresult.Result["data"] != null)
                                    {
                                        foreach (KeyValuePair <string, object> o in rootresult.Result)
                                        {
                                            if (bstop == true)
                                            {
                                                bstop = false;
                                                sb.AppendLine("Stopped by user");
                                                richTextStatus.Text = sb.ToString();
                                                richTextStatus.Refresh();
                                                SetStateReady();
                                                return;
                                            }
                                            if (o.Key == "data")
                                            {
                                                if (o.Value != null && o.Value is List <object> )
                                                {
                                                    foreach (object obj in o.Value as List <object> )
                                                    {
                                                        string id     = "";
                                                        string name   = "";
                                                        string type   = "";
                                                        string link   = "";
                                                        string source = "";
                                                        foreach (KeyValuePair <string, object> kvp in obj as IDictionary <string, object> )
                                                        {
                                                            switch (kvp.Key)
                                                            {
                                                            case "id":
                                                                id = kvp.Value.ToString();
                                                                break;

                                                            case "name":
                                                                name = kvp.Value.ToString();
                                                                break;

                                                            case "type":
                                                                type = kvp.Value.ToString();
                                                                break;

                                                            case "link":
                                                                link = kvp.Value.ToString();
                                                                break;

                                                            case "source":
                                                                source = kvp.Value.ToString();
                                                                break;
                                                            }
                                                        }
                                                        if (type == "folder")
                                                        {
                                                            rootfolders.Add(new OneDriveFolder("root", id, name, link));
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    sb.AppendLine(ex.Message);
                                    richTextStatus.Text = sb.ToString();
                                    richTextStatus.Refresh();
                                    if (nerrors++ > 20)
                                    {
                                        SetStateReady();
                                        return;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                bool found = false;
                                foreach (OneDriveFolder f in rootfolders)
                                {
                                    if (f.name == root)
                                    {
                                        parents.Add(root, f.id);
                                        rootfolder = f;
                                        rootpath   = f.id;
                                        found      = true;
                                        break;
                                    }
                                }
                                if (found == false)
                                {
                                    rootfolder = null;
                                }
                            }
                        }

                        if (rootfolder == null)
                        {
                            sb.AppendLine(string.Format("Root folder not found: {0}", rootpath));
                            richTextStatus.Text = sb.ToString();
                            richTextStatus.Refresh();
                            continue;
                        }

                        //folder.a645bfc91d3b795a.A645BFC91D3B795A!41650/files //Sample path (using id)
                        //https://onedrive.live.com/redir?resid=A645BFC91D3B795A!41650&authkey=!ABx2Nb-uPkoa7RA&ithint=folder%2ctxt //Sample link
                        try
                        {
                            LiveOperationResult result = await this.liveConnectClient.GetAsync(string.Format("{0}/files", rootfolder.id));

                            if (result != null && result.Result != null && result.Result["data"] != null)
                            {
                                foreach (KeyValuePair <string, object> o in result.Result)
                                {
                                    if (bstop == true)
                                    {
                                        bstop = false;
                                        sb.AppendLine("Stopped by user");
                                        richTextStatus.Text = sb.ToString();
                                        richTextStatus.Refresh();
                                        SetStateReady();
                                        return;
                                    }
                                    if (o.Key == "data")
                                    {
                                        if (o.Value != null && o.Value is List <object> )
                                        {
                                            foreach (object obj in o.Value as List <object> )
                                            {
                                                string id     = "";
                                                string name   = "";
                                                string type   = "";
                                                string link   = "";
                                                string source = "";
                                                foreach (KeyValuePair <string, object> kvp in obj as IDictionary <string, object> )
                                                {
                                                    switch (kvp.Key)
                                                    {
                                                    case "id":
                                                        id = kvp.Value.ToString();
                                                        break;

                                                    case "name":
                                                        name = kvp.Value.ToString();
                                                        break;

                                                    case "type":
                                                        type = kvp.Value.ToString();
                                                        break;

                                                    case "link":
                                                        link = kvp.Value.ToString();
                                                        break;

                                                    case "source":
                                                        source = kvp.Value.ToString();
                                                        break;
                                                    }
                                                }
                                                if (type == "file")
                                                {
                                                    if (name.ToLower().Trim() == thefile.ToLower().Trim())
                                                    {
                                                        string ic = string.Format("Item {0} of {1} -> {2}", nitems, titems, name);
                                                        richTextStatus.Text = sb.ToString() + ic;
                                                        richTextStatus.Refresh();
                                                        LiveOperationResult resultlink = null;
                                                        for (int i = 0; i < 3; i++)
                                                        {
                                                            try
                                                            {
                                                                resultlink = await this.liveConnectClient.GetAsync(string.Format("{0}/shared_read_link", id));

                                                                if (resultlink != null && resultlink.RawResult != null && resultlink.RawResult.Length > 0)
                                                                {
                                                                    break;
                                                                }
                                                                else
                                                                {
                                                                    Thread.Sleep(5000);
                                                                }
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                MessageBox.Show(ex.Message, "Navigation failed - will try to continue");
                                                                Thread.Sleep(5000);
                                                            }
                                                        }
                                                        if (resultlink != null && resultlink.RawResult != null && resultlink.RawResult.Length > 0)
                                                        {
                                                            string ilink = "link\": ";
                                                            string raw   = resultlink.RawResult.Trim();
                                                            int    iof   = raw.IndexOf(ilink);
                                                            if (iof > 0)
                                                            {
                                                                iof += ilink.Length + 1;
                                                                int end = raw.LastIndexOf('"');
                                                                if (end > 0 && end > iof)
                                                                {
                                                                    item.Link  = raw.Substring(iof, end - iof);
                                                                    item.isnew = true;
                                                                }
                                                                else
                                                                {
                                                                    MessageBox.Show("Operation will continue", "Unexpected start/end result");
                                                                }
                                                            }
                                                            else
                                                            {
                                                                MessageBox.Show("Operation will continue", "Unexpected parsing result");
                                                            }
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Received an error. " + ex.Message);
                        }
                        finally
                        {
                            signinButton.Enabled  = true;
                            signOutButton.Enabled = true;
                            //btnCreateMap.Enabled = true;
                            //txtRoot.Enabled = true;
                        }
                    }
                }
            }
            SetTimer(WriteLinks);
        }
Example #30
0
        private void OkTimer_Button_Click(object sender, RoutedEventArgs e)
        {
            if (int.TryParse(BackupCount_TextBox.Text, out int backupCount))
            {
                BackupCount = backupCount;
            }
            else
            {
                BackupCount = 0;
            }

            if (IsEnabled_CheckBox.IsChecked != null)
            {
                timerIsEnabled = IsEnabled_CheckBox.IsChecked.Value;
            }

            if (timerIsEnabled)
            {
                if (startDatePicker.SelectedDate != null)
                {
                    timerStartDate = startDatePicker.SelectedDate.Value.Date;
                }
                if (startTimePicker.Value != null)
                {
                    timerStartDate = timerStartDate.Date.AddTicks(startTimePicker.Value.Value.TimeOfDay.Ticks);
                }

                var checkedButton = container.Children.OfType <RadioButton>()
                                    .FirstOrDefault(r => r.GroupName == "TimerType" && r.IsChecked == true);
                switch (checkedButton.Name)
                {
                case "EveryDay":
                    timerType = SyncTimerType.EveryDay;
                    break;

                case "Custom":
                    timerType = SyncTimerType.Custom;
                    break;

                case "Once":
                default:
                    timerType = SyncTimerType.Once;
                    break;
                }

                if (timerType == SyncTimerType.Custom)
                {
                    if (Days.Value != null)
                    {
                        timerPeriod = timerPeriod.Add(TimeSpan.FromDays(Days.Value.Value));
                    }
                    if (Hours.Value != null)
                    {
                        timerPeriod = timerPeriod.Add(TimeSpan.FromHours(Hours.Value.Value));
                    }
                    if (Minutes.Value != null)
                    {
                        timerPeriod = timerPeriod.Add(TimeSpan.FromMinutes(Minutes.Value.Value));
                    }
                }
            }

            SyncTimer = new SyncTimer
            {
                IsEnabled = timerIsEnabled,
                StartDate = timerStartDate,
                Type      = timerType,
                Period    = timerPeriod
            };

            DialogResult = true;
        }