Exemplo n.º 1
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");
            XmlConfigurator.ConfigureAndWatch(logCfg);

            DeleteOldPositions();

            _timScheduledTask = new System.Timers.Timer
            {
                Interval = 86400000,
                Enabled = true
            };

            _timScheduledTask.Elapsed += (o, e) =>
           {
               DeleteOldPositions();
           };

            //            ConvertVoiceTest();
            //            TestConvert3gpToMp4();
        }
Exemplo n.º 2
0
 public static void InitAgentLogTimer()
 {
     var agentLogTimer = new Timer();
     agentLogTimer.Elapsed += RefreshAgentLogFile_Tick;
     agentLogTimer.Interval = AgentLogRefreshTime;
     agentLogTimer.Enabled = true;
 }
Exemplo n.º 3
0
        protected override void OnStart(string[] args)
        {
            if (!LoadSettings()) return;

            //Создаем таймер и выставляем его параметры
            timer1 = new System.Timers.Timer();
            timer1.Enabled = true;
            timer1.Interval = 60000;
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
            timer1.AutoReset = true;
            timer1.Start();

            timer2 = new System.Timers.Timer();
            timer2.Enabled = true;
            timer2.Interval = 300000;
            timer2.Elapsed += new System.Timers.ElapsedEventHandler(this.timer2_Elapsed);
            timer2.AutoReset = true;
            timer2.Start();

            timer3 = new System.Timers.Timer();
            timer3.Enabled = true;
            timer3.Interval = 600000;
            timer3.Elapsed += new System.Timers.ElapsedEventHandler(this.timer3_Elapsed);
            timer3.AutoReset = true;
            timer3.Start();

            timer4 = new System.Timers.Timer();
            timer4.Enabled = true;
            timer4.Interval = 600000;
            timer4.Elapsed += new System.Timers.ElapsedEventHandler(this.timer4_Elapsed);
            timer4.AutoReset = true;
            timer4.Start();
        }
Exemplo n.º 4
0
        protected override void OnStart(string[] args)
        {
            try
            {
                log.Info("BatchJob Service Start");
                container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));

                timer = new System.Timers.Timer();
                timer.Interval = Convert.ToDouble(TimerHelper.GetInterval(Settings.Default.IntervalType, 1));
                timer.Enabled = true;
                timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);

                leanEngineTimer = new System.Timers.Timer();
                leanEngineTimer.Interval = Convert.ToDouble(TimerHelper.GetInterval(Settings.Default.IntervalType, 1));
                leanEngineTimer.Enabled = true;
                leanEngineTimer.Elapsed += new System.Timers.ElapsedEventHandler(leanEngineTimer_Elapsed);

                receiveWOTimer = new System.Timers.Timer();
                receiveWOTimer.Interval = Convert.ToDouble(TimerHelper.GetInterval(Settings.Default.IntervalType, 1));
                receiveWOTimer.Enabled = true;
                receiveWOTimer.Elapsed += new System.Timers.ElapsedEventHandler(receiveWOTimer_Elapsed);
            }
            catch (Exception ex)
            {
                log.Error("BatchJob Service Start Failure", ex);
            }
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            if (String.IsNullOrEmpty(name))
                name = "RiakSessionStateStore";

            base.Initialize(name, config);

            ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

            Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);
            _config = (SessionStateSection)cfg.GetSection("system.web/sessionState");

            var container = UnityBootstrapper.Bootstrap();
            _client = container.Resolve<IRiakClient>();

            var riakSessionConfiguration = container.Resolve<RiakSessionStateConfiguration>();
            int expiredSessionDeletionInterval = riakSessionConfiguration.TimeoutInMilliseconds;

            _expiredSessionDeletionTimer = new System.Timers.Timer(expiredSessionDeletionInterval);
            _expiredSessionDeletionTimer.Elapsed += ExpiredSessionDeletionTimerElapsed;
            _expiredSessionDeletionTimer.Enabled = true;
            _expiredSessionDeletionTimer.AutoReset = true;
        }
Exemplo n.º 6
0
        public StockNotifier(string[] args)
        {
            InitializeComponent();
            niNewData.Visible = true;
            this.SizeChanged += StockNotifier_MinimumSizeChanged;
            niNewData.MouseClick += niNewData_MouseClick;

            List<Stock> Configs = LogRecord.ReadSerXmlLog<List<Stock>>(System.Windows.Forms.Application.StartupPath + "\\Stocks.xml");
            if (Configs != null && Configs.Count > 0)
            {
                this.Height = 114 + Configs.Count * 23;
                dgvStocks.Visible = true;
                dgvStocks.Height = 20 + Configs.Count * 23;
                dgvStocks.DataSource = Configs;
            }
            else
            {
                this.Height = 80;
                dgvStocks.Visible = false;
            }

            UpdateTimer = new System.Timers.Timer(300);
            UpdateTimer.Elapsed += UpdateTimer_Elapsed;
            UpdateTimer.Start();
            if (args != null && args.Contains("min"))
                UpdateTimer.Interval += 1;
        }
Exemplo n.º 7
0
 protected override void OnStart(string[] args)
 {
     System.Timers.Timer timer = new System.Timers.Timer();
     timer.Interval = 60000; // 60 seconds
     timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
     timer.Start();
 }
Exemplo n.º 8
0
 private void button1_Click(object sender, EventArgs e)
 {
     tim = new System.Timers.Timer(25000);
     tim.Elapsed += new System.Timers.ElapsedEventHandler(CheckPageAgain);
     tim.Start();
     CheckPageAgain(null, null);
 }
Exemplo n.º 9
0
        /// <summary>
        /// 
        /// </summary>
        public TestClient(ClientManager manager)
        {
			ClientManager = manager;

            updateTimer = new System.Timers.Timer(500);
            updateTimer.Elapsed += new System.Timers.ElapsedEventHandler(updateTimer_Elapsed);

            RegisterAllCommands(Assembly.GetExecutingAssembly());

            Settings.DEBUG = true;
            Settings.LOG_RESENDS = false;
            Settings.STORE_LAND_PATCHES = true;
            Settings.ALWAYS_DECODE_OBJECTS = true;
            Settings.ALWAYS_REQUEST_OBJECTS = true;
            Settings.SEND_AGENT_UPDATES = true;

            Network.RegisterCallback(PacketType.AgentDataUpdate, new NetworkManager.PacketCallback(AgentDataUpdateHandler));

            Self.OnInstantMessage += new AgentManager.InstantMessageCallback(Self_OnInstantMessage);
            Groups.OnGroupMembers += new GroupManager.GroupMembersCallback(GroupMembersHandler);
            Inventory.OnObjectOffered += new InventoryManager.ObjectOfferedCallback(Inventory_OnInventoryObjectReceived);

            Network.RegisterCallback(PacketType.AvatarAppearance, new NetworkManager.PacketCallback(AvatarAppearanceHandler));
            Network.RegisterCallback(PacketType.AlertMessage, new NetworkManager.PacketCallback(AlertMessageHandler));
            
            updateTimer.Start();
        }
Exemplo n.º 10
0
        public Form1()
        {
            _heartbeat = 0;
            InitializeComponent();
            this.WindowState = FormWindowState.Minimized;
            icnStopped = Resources.Icon1;
            icnStarted = Resources.Icon2;

            timestamp = Utils.RetrieveLinkerTimestamp();

            // notifyIcon1.Text = "MTC Multi-SHDR Agent - Release " + _assembly.ImageRuntimeVersion ;
            notifyIcon1.Text = "Autostart MTC SHDR Agent - Release " + timestamp.ToLocalTime(); ;
            notifyIcon1.Icon = icnStopped;

            Utilities.Logger.RestartLog();
            aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
               // System.Threading.Thread.Sleep(30000);

            MTConnectAgentCore.Configuration.defaultDirectory = Application.StartupPath + "\\";
            MTConnectAgentCore.Configuration.confDirectory = "" ;

            SystemEvents.SessionEnding += SystemEvents_SessionEnding;
            Reset();
        }
Exemplo n.º 11
0
        //LongPolling Action 1 - 处理客户端发起的请求
        public void LongPollingAsync()
        {
            var state = Request["state"];
            //计时器,5秒种触发一次Elapsed事件
            var timer = new System.Timers.Timer(1000);
            //告诉ASP.NET接下来将进行一个异步操作
            AsyncManager.OutstandingOperations.Increment();
            //订阅计时器的Elapsed事件
            timer.Elapsed += (sender, e) =>
            {
                //保存将要传递给LongPollingCompleted的参数
                AsyncManager.Parameters["model"] = new LoginLogModel();
                if (state != null)
                {
                    var log = _loginLogService.GetLoginLog(state);
                    if (log != null && log.IsDeleted == false)
                    {
                        //保存将要传递给LongPollingCompleted的参数
                        AsyncManager.Parameters["model"] = new LoginLogModel
                        {
                            Id = log.Id,
                            CreateTime = log.CreateTime,
                            State = log.State
                        };
                    }

                }
                //告诉ASP.NET异步操作已完成,进行LongPollingCompleted方法的调用
                AsyncManager.OutstandingOperations.Decrement();
            };
            //启动计时器
            timer.Start();
        }
Exemplo n.º 12
0
 public OutputTCBase(Protocol protocol, string devicename, string ip, int port, int deviceid, byte[] hw_status, bool isconnected )
     : base(protocol, devicename, ip, port, deviceid, hw_status,  isconnected)
 {
     tmrCheckOutput = new System.Timers.Timer(outputCompareMin*1000 * 60);
     tmrCheckOutput.Elapsed += new System.Timers.ElapsedEventHandler(tmrCheckOutput_Elapsed);
     tmrCheckOutput.Start();
 }
Exemplo n.º 13
0
        private void DisplayInfoOrError(string message, Int32 msTime, bool isError = false)
        {
            tbErrorOrInfo.Text = message;
            tbErrorOrInfo.Visibility = System.Windows.Visibility.Visible;

            if(isError)
            {
                tbErrorOrInfo.Foreground = Brushes.Red;
            }

            System.Timers.Timer timer = new System.Timers.Timer(msTime);

            timer.Start();

            timer.Elapsed += (sender, args) =>
            {
                Dispatcher.BeginInvoke(new System.Threading.ThreadStart(delegate
                {                
                    tbErrorOrInfo.Text = string.Empty;
                    tbErrorOrInfo.Visibility = System.Windows.Visibility.Collapsed;

                    if (isError)
                    {
                        tbErrorOrInfo.Foreground = Brushes.White;
                    }

                }), System.Windows.Threading.DispatcherPriority.Input);

                timer.Dispose();
            };            
        }
Exemplo n.º 14
0
        /// <summary>
        /// Tutaj inicjalizujemy podstawowe obiekty i podpinamy customowe eventy. Nic ciekawego.
        /// </summary>
        public Main()
        {
            InitializeComponent();

            //Dziwny fix dla outputRecivedDataHex - bez tego program lubi się wieszać.
            NotifyMessageReceive("INIT");
            this.outputRecivedDataHex.Clear();
            this.outputRecivedData.Clear();

            //Obiekt reprezentujący port COM.
            _usedPort = new SerialPort();
            _usedPort.Encoding = Encoding.GetEncoding(28591);
            //Podpinanie custom eventów etc.
            _usedPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            this.NoResponseFromDevice += new NoResponseHandler(NotifyNoPingResponse);
            this.NoDtrDsrResponseFromDevice += new NoResponseHandler(NotifyNoResponseFromDevice);

            //Tworzenie timerów.
            pingResponseTimeoutTimer = new System.Timers.Timer();
            pingResponseTimeoutTimer.Elapsed += new System.Timers.ElapsedEventHandler(pingTimer_Elapsed);

            sendTimeoutTimer = new System.Timers.Timer();
            sendTimeoutTimer.Elapsed += new System.Timers.ElapsedEventHandler(sendTimer_Elapsed);

            //Wczytanie ustawień domyślnych.
            NotifySettingsChanged();
            //new Settings(this).ShowDialog(this);
        }
Exemplo n.º 15
0
 private void BrowseTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
     lock (browseLock) {
         browseTimer.Dispose();
         browseTimer = null;
         MainForm.mainForm.Invoke((MethodInvoker)delegate {
             string searchTerm = browseTextBox.Text;
             switch (browseTypeDropDownList.SelectedIndex) {
                 case 0:
                     browseObjects = StorageManager.searchCreature(searchTerm);
                     break;
                 case 1:
                     browseObjects = StorageManager.searchItem(searchTerm);
                     break;
                 case 2:
                     browseObjects = StorageManager.searchNPC(searchTerm);
                     break;
                 case 3:
                     browseObjects = StorageManager.searchHunt(searchTerm).ToList<TibiaObject>();
                     break;
                 case 4:
                     browseObjects = StorageManager.searchQuest(searchTerm);
                     break;
                 case 5:
                     browseObjects = StorageManager.searchMount(searchTerm);
                     break;
                 case 6:
                     browseObjects = StorageManager.searchOutfit(searchTerm);
                     break;
             }
             refreshItems(creaturePanel, creaturePanel.Controls, browseObjects, browseSortedHeader, browseDesc, sortBrowse);
         });
     }
 }
        public GameCoordinator(SteamClient steamClient, CallbackManager manager)
        {
            SessionMap = new Dictionary<uint, SessionInfo>();

            // Map gc messages to our callback functions
            MessageMap = new Dictionary<uint, Action<uint, IPacketGCMsg>>
            {
                { (uint)EGCBaseClientMsg.k_EMsgGCClientConnectionStatus, OnConnectionStatus },
                { (uint)EGCBaseClientMsg.k_EMsgGCClientWelcome, OnWelcome },
                { (uint)EGCItemMsg.k_EMsgGCUpdateItemSchema, OnItemSchemaUpdate },
                { (uint)EGCItemMsg.k_EMsgGCClientVersionUpdated, OnVersionUpdate },
                { (uint)EGCBaseMsg.k_EMsgGCSystemMessage, OnSystemMessage },

                // TF2 specific messages
                { k_EMsgGCClientGoodbye, OnConnectionStatus },
                { (uint)EGCItemMsg.k_EMsgGCGoldenWrenchBroadcast, OnWrenchBroadcast },
                { k_EMsgGCTFSpecificItemBroadcast, OnItemBroadcast },
            };

            SteamGameCoordinator = steamClient.GetHandler<SteamGameCoordinator>();

            SessionTimer = new Timer();
            SessionTimer.Interval = TimeSpan.FromSeconds(30).TotalMilliseconds;
            SessionTimer.Elapsed += OnSessionTick;
            SessionTimer.Start();

            manager.Register(new Callback<SteamGameCoordinator.MessageCallback>(OnGameCoordinatorMessage));
            manager.Register(new Callback<SteamUser.LoggedOffCallback>(OnLoggedOff));
            manager.Register(new Callback<SteamClient.DisconnectedCallback>(OnDisconnected));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Contructeur qui test s'il peut se connecter a la Database et qui part le timer de déconnection des joueurs.
        /// </summary>
        public ServiceHugoWorld()
        {
            try
            {
                context.Database.Connection.Open();
                if (context.Database.Connection.State == ConnectionState.Open)
                {
                    Console.WriteLine(@"INFO: ConnectionString: " + context.Database.Connection.ConnectionString
                        + "\n DataBase: " + context.Database.Connection.Database
                        + "\n DataSource: " + context.Database.Connection.DataSource
                        + "\n ServerVersion: " + context.Database.Connection.ServerVersion
                        + "\n TimeOut: " + context.Database.Connection.ConnectionTimeout);
                    context.Database.Connection.Close();
                }
                else
                    throw new FaultException("Connection error...");

                lock (context.Heroes)
                {
                    foreach (Hero hero in context.Heroes.Where(h => h.Connected))
                        hero.Connected = false;
                    context.SaveChanges();
                }

                timer = new System.Timers.Timer(15000);
                timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);

                timer.Start();
            }
            catch (Exception ex)
            {
                throw new FaultException(ex.Message);
            }
        }
Exemplo n.º 18
0
      protected override void OnStart(string[] args) {
         base.OnStart(args);
         switch (ReceiverKind) {
            case SupportedReceiver.RoyalTek:
               _reader = new RoyalTekReader(Port, 0);
               ((RoyalTekReader)_reader).Frequency = Frequency;
               break;
            default:
               Log.Warn("{0} recieved is unsupported.", ReceiverKind);
               break;
         }
         if (_reader != null) {
            _reader.TmcTransmissionArrived += onDataArrived;

            var tm = new System.Timers.Timer {
               Interval = 30000,
               AutoReset = true
            };
            tm.Elapsed += new System.Timers.ElapsedEventHandler((o, a) => _sendTrafficState());
            tm.Start();

            var lookup = new TmcLookup(_reader);
            lookup.StartLookupForTmc();
            
         } else {
            throw new NotSupportedException("Unable to initialize serial TMC reader");
         }
      }
Exemplo n.º 19
0
 public grabber(settings _s)
 {
     committedsettings = _s;
     committedsettings.SettingsChanged += new SettingsChangedHandler(settingsChanged);
     nextgrab = new System.Timers.Timer();
     nextgrab.Elapsed += new System.Timers.ElapsedEventHandler(this.nextgrab_Tick);
 }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            TimeSpan TsStart = new TimeSpan(DateTime.Now.Ticks);
            String[] CmdArgs= System.Environment.GetCommandLineArgs();
            if (CmdArgs.Length > 1)
            {
                //参数0是它本身的路径
                String FileName = CmdArgs[1].ToString();
                String Dir = CmdArgs[2].ToString();
                String Url = CmdArgs[3].ToString();
                SnapShot sp = new SnapShot();
                sp.FileName = FileName;// "test.jpg";
                sp.Dir = Dir; //@"D:\web\7.03\eweb_lifetour";
                sp.Url = Url; //@"http://lifetour20.travelindex.com.tw/eWeb/GO/V_GO_Detail.asp?MGRUP_CD=0000&GRUP_CD=0000141015A&SUB_CD=GO&JOIN_TP=1";
                sp.Save();

            }

            System.Timers.Timer tmr = new System.Timers.Timer(20000);
            tmr.Elapsed += delegate
            {
                Environment.Exit(0);
            };
            tmr.Start();
            Console.ReadKey();
        }
Exemplo n.º 21
0
 public override void OnStartUp()
 {
     _timer = new Timer(1000);
     //_timer.Elapsed += Elapsed;
     _timer.Start();
     Elapsed(null, null);
 }
        public AutoCompleteTextBox()
        {
            controls = new VisualCollection(this);
            InitializeComponent();

            searchThreshold = 2;        // default threshold to 2 char

            // set up the key press timer
            keypressTimer = new System.Timers.Timer();
            keypressTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);

            // set up the text box and the combo box
            comboBox = new ComboBox();
            comboBox.IsSynchronizedWithCurrentItem = true;
            comboBox.IsTabStop = false;
            comboBox.SelectionChanged += new SelectionChangedEventHandler(comboBox_SelectionChanged);

            textBox = new TextBox();
            textBox.TextChanged += new TextChangedEventHandler(textBox_TextChanged);
            textBox.VerticalContentAlignment = VerticalAlignment.Center;

            controls.Add(comboBox);
            controls.Add(textBox);

        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            ObjectBase.Container = MEFLoader.Init();

            System.Console.WriteLine("Starting up services");
            System.Console.WriteLine("");

            SM.ServiceHost hostStyleManger = new SM.ServiceHost(typeof(StyleManager));

            SM.ServiceHost hostProductManger = new SM.ServiceHost(typeof(ProductManager));

            /* More services to call  */
            StartService(hostStyleManger, "StyleManger Host");
            StartService(hostProductManger, "ProductManager Host");

            System.Timers.Timer timer = new System.Timers.Timer(10000);
            timer.Elapsed += OnTimerElapsed;
            timer.Start();

            System.Console.WriteLine("eCommerce Monitor has started.");

            System.Console.WriteLine("");
            System.Console.WriteLine("Press [Enter] to exit.");
            System.Console.ReadLine();

            timer.Stop();
            System.Console.WriteLine("eCommerce Monitor stopped.");

            StopService(hostStyleManger, "AccountManager Host");
            StopService(hostProductManger, "AccountManager Host");
        }
Exemplo n.º 24
0
        public RaptorDBServer(int port, string DataPath)
        {
            _path = Directory.GetCurrentDirectory();
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            _server = new NetworkServer();

            if (_S == "/")// unix system
                _datapath = DataPath.Replace("\\", "/");
            else
                _datapath = DataPath;

            if (_datapath.EndsWith(_S) == false)
                _datapath += _S;

            _raptor = RaptorDB.Open(DataPath);
            register = _raptor.GetType().GetMethod("RegisterView", BindingFlags.Instance | BindingFlags.Public);
            save = _raptor.GetType().GetMethod("Save", BindingFlags.Instance | BindingFlags.Public);
            Initialize();
            _server.Start(port, processpayload);

            // add timer to cleanup connected clients
            _concleanuptimer = new System.Timers.Timer(30 * 1000);
            _concleanuptimer.AutoReset = true;
            _concleanuptimer.Enabled = true;
            _concleanuptimer.Elapsed += _concleanuptimer_Elapsed;
        }
Exemplo n.º 25
0
 public Sessions(TimeSpan timeout)
 {
     this.sessions = Hashtable.Synchronized(new Hashtable(32));
     this.timeout = timeout;
     this.timer = new System.Timers.Timer(timeout.TotalMilliseconds/2d);
     this.timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
 }
Exemplo n.º 26
0
 public ClassWithFinalizer()
 {
     _sillyTimer = new System.Timers.Timer(100);
     _sillyTimer.Elapsed +=
         (a, b) => Console.WriteLine("Still Alive");
     _sillyTimer.Start();
 }
Exemplo n.º 27
0
 public RexObjectProperties()
 {
     RexMaterials.SetSceneObjectPart(this);
     m_saveProperties = new System.Timers.Timer();
     m_saveProperties.Interval = 1000;
     m_saveProperties.Elapsed += m_saveProperties_Elapsed;
 }
        public async void StartIndexingAsync()
        {
            bool fromFile = !string.IsNullOrWhiteSpace(OpenDirectoryIndexerSettings.FileName);

            if (fromFile)
            {
                Session = Library.LoadSessionJson(OpenDirectoryIndexerSettings.FileName);
                Console.WriteLine(Statistics.GetSessionStats(Session, includeExtensions: true));
                Console.ReadKey(intercept: true);
                return;
            }
            else
            {
                Session = new Session
                {
                    Started = DateTimeOffset.UtcNow,
                    Root    = new WebDirectory(parentWebDirectory: null)
                    {
                        Name = "ROOT",
                        Url  = OpenDirectoryIndexerSettings.Url
                    }
                };
            }

            if (Session.Root.Uri.Host == Constants.GoogleDriveDomain)
            {
                Logger.Warn("Google Drive scanning is limited to 10 directories per second!");
            }

            if (Session.Root.Uri.Scheme == "ftp")
            {
                Logger.Warn("Retrieving FTP software!");
                // TODO: Replace with library?
                Logger.Warn(await FtpParser.GetFtpServerInfo(Session.Root));
                //AddProcessedWebDirectory(webDirectory, parsedWebDirectory);
            }

            TimerStatistics = new System.Timers.Timer
            {
                Enabled  = true,
                Interval = TimeSpan.FromSeconds(30).TotalMilliseconds
            };

            TimerStatistics.Elapsed += TimerStatistics_Elapsed;

            IndexingTask = Task.Run(async() =>
            {
                try
                {
                    WebDirectoriesQueue = new ConcurrentQueue <WebDirectory>();

                    if (fromFile)
                    {
                        SetParentDirectories(Session.Root);

                        // TODO: Add unfinished items to queue, very complicated, we need to ALSO fill the ParentDirectory...
                        //// With filter predicate, with selection function
                        //var flatList = nodes.Flatten(n => n.IsDeleted == false, n => n.Children);
                        //var directoriesToDo = Session.Root.Subdirectories.Flatten(null, wd => wd.Subdirectories).Where(wd => !wd.Finished);
                    }
                    else
                    {
                        // Add root
                        WebDirectoriesQueue.Enqueue(Session.Root);
                    }

                    IndexingTaskCTS = new CancellationTokenSource();

                    for (int i = 1; i <= WebDirectoryProcessors.Length; i++)
                    {
                        string processorId = i.ToString();

                        WebDirectoryProcessors[i - 1] = WebDirectoryProcessor(WebDirectoriesQueue, $"Processor {processorId}", IndexingTaskCTS.Token);
                    }

                    for (int i = 1; i <= WebFileFileSizeProcessors.Length; i++)
                    {
                        string processorId = i.ToString();

                        WebFileFileSizeProcessors[i - 1] = WebFileFileSizeProcessor(WebFilesFileSizeQueue, $"Processor {processorId}", IndexingTaskCTS.Token, WebDirectoryProcessors);
                    }

                    await Task.WhenAll(WebDirectoryProcessors);
                    Console.WriteLine("Finshed indexing");
                    Logger.Info("Finshed indexing");

                    if (Session.Root.Uri.Scheme == "ftp")
                    {
                        FtpParser.CloseAll();
                    }

                    if (WebFilesFileSizeQueue.Any())
                    {
                        TimerStatistics.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds;
                        Console.WriteLine($"Retrieving filesize of {WebFilesFileSizeQueue.Count} urls");
                    }

                    await Task.WhenAll(WebFileFileSizeProcessors);

                    TimerStatistics.Stop();

                    Session.Finished               = DateTimeOffset.UtcNow;
                    Session.TotalFiles             = Session.Root.TotalFiles;
                    Session.TotalFileSizeEstimated = Session.Root.TotalFileSize;

                    if (!OpenDirectoryIndexerSettings.CommandLineOptions.NoUrls)
                    {
                        Logger.Info("Saving URL list to file...");
                        Console.WriteLine("Saving URL list to file...");

                        string scansPath = Library.GetScansPath();

                        try
                        {
                            string fileUrls     = string.Join(Environment.NewLine, Session.Root.AllFileUrls.Distinct());
                            string urlsFileName = $"{Library.CleanUriToFilename(Session.Root.Uri)}.txt";
                            string urlsPath     = Path.Combine(scansPath, urlsFileName);
                            Logger.Info("String joined");
                            File.WriteAllText(urlsPath, fileUrls);
                            Logger.Info($"Saved URL list to file: {urlsFileName}");
                            Console.WriteLine($"Saved URL list to file: {urlsFileName}");

                            if (OpenDirectoryIndexerSettings.CommandLineOptions.UploadUrls && Session.TotalFiles > 0)
                            {
                                Console.WriteLine("Uploading URLs...");

                                //UploadFilesFile uploadFilesFile = await UploadFileIo.UploadFile(HttpClient, urlsPath);
                                //HistoryLogger.Info($"uploadfiles.io: {JsonConvert.SerializeObject(uploadFilesFile)}");
                                //Session.UploadedUrlsUrl = uploadFilesFile.Url.ToString();

                                GoFilesFile uploadedFile = await GoFileIo.UploadFile(HttpClient, urlsPath);
                                HistoryLogger.Info($"goFile.io: {JsonConvert.SerializeObject(uploadedFile)}");
                                Session.UploadedUrlsUrl = uploadedFile.Url.ToString();

                                Console.WriteLine($"Uploaded URLs: {Session.UploadedUrlsUrl}");
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex);
                        }
                    }

                    if (OpenDirectoryIndexerSettings.CommandLineOptions.Speedtest)
                    {
                        if (Session.TotalFiles > 0)
                        {
                            if (Session.Root.Uri.Scheme == "https" || Session.Root.Uri.Scheme == "http")
                            {
                                try
                                {
                                    WebFile biggestFile = Session.Root.AllFiles.OrderByDescending(f => f.FileSize).First();

                                    Console.WriteLine($"Starting speedtest (10-25 seconds)...");
                                    Console.WriteLine($"Test file: {FileSizeHelper.ToHumanReadable(biggestFile.FileSize)} {biggestFile.Url}");
                                    Session.SpeedtestResult = await Library.DoSpeedTestAsync(HttpClient, biggestFile.Url);
                                    Console.WriteLine($"Finished speedtest. Downloaded: {FileSizeHelper.ToHumanReadable(Session.SpeedtestResult.DownloadedBytes)}, Time: {Session.SpeedtestResult.ElapsedMiliseconds / 1000:F1} s, Speed: {Session.SpeedtestResult.MaxMBsPerSecond:F1} MB/s ({Session.SpeedtestResult.MaxMBsPerSecond * 8:F0} mbit)");
                                }
                                catch (Exception ex)
                                {
                                    Logger.Error(ex, "Speedtest failed");
                                }
                            }
                            else
                            {
                                Logger.Warn($"Only a speedtest for HTTP(S), not '{Session.Root.Uri.Scheme}'");
                            }
                        }
                    }

                    Logger.Info("Logging sessions stats...");
                    try
                    {
                        string sessionStats = Statistics.GetSessionStats(Session, includeExtensions: true);
                        Logger.Info(sessionStats);
                        HistoryLogger.Info(sessionStats);
                        Logger.Info("Logged sessions stats");

                        if (!OpenDirectoryIndexerSettings.CommandLineOptions.NoReddit)
                        {
                            // Also log to screen, when saving links or JSON fails and the logs keep filling by other sessions, this will be saved
                            Console.WriteLine(sessionStats);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex);
                    }

                    if (Session.UrlsWithErrors.Any())
                    {
                        Logger.Info("URLs with errors:");
                        Console.WriteLine("URLs with errors:");

                        foreach (string urlWithError in Session.UrlsWithErrors.OrderBy(u => u))
                        {
                            Logger.Info(urlWithError);
                            Console.WriteLine(urlWithError);
                        }
                    }

                    if (OpenDirectoryIndexerSettings.CommandLineOptions.Json)
                    {
                        Logger.Info("Save session to JSON");
                        Console.WriteLine("Save session to JSON");

                        try
                        {
                            Library.SaveSessionJson(Session);
                            Logger.Info($"Saved session: {PathHelper.GetValidPath(Session.Root.Url)}.json");
                            Console.WriteLine($"Saved session: {PathHelper.GetValidPath(Session.Root.Url)}.json");
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex);
                        }
                    }

                    Logger.Info("Finished indexing!");
                    Console.WriteLine("Finished indexing!");

                    Program.SetConsoleTitle($"✔ {Program.ConsoleTitle}");

                    if (OpenDirectoryIndexerSettings.CommandLineOptions.Quit)
                    {
                        Command.KillApplication();
                    }
                    else
                    {
                        Console.WriteLine("Press ESC to exit! Or C to copy to clipboard and quit!");
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }
            });
        }
Exemplo n.º 29
0
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     this.radioDefault  = new System.Windows.Forms.RadioButton();
     this.tmrUpdate     = new System.Timers.Timer();
     this.checkLoop     = new System.Windows.Forms.CheckBox();
     this.textVolume    = new System.Windows.Forms.TextBox();
     this.label10       = new System.Windows.Forms.Label();
     this.groupBox1     = new System.Windows.Forms.GroupBox();
     this.groupBox4     = new System.Windows.Forms.GroupBox();
     this.radioHardware = new System.Windows.Forms.RadioButton();
     this.label12       = new System.Windows.Forms.Label();
     this.radioSoftware = new System.Windows.Forms.RadioButton();
     this.groupBox2     = new System.Windows.Forms.GroupBox();
     this.radioSticky   = new System.Windows.Forms.RadioButton();
     this.label13       = new System.Windows.Forms.Label();
     this.radioGlobal   = new System.Windows.Forms.RadioButton();
     this.radioNormal   = new System.Windows.Forms.RadioButton();
     this.textFile      = new System.Windows.Forms.TextBox();
     this.groupBox5     = new System.Windows.Forms.GroupBox();
     this.lblBehavior   = new System.Windows.Forms.Label();
     this.buttonSound   = new System.Windows.Forms.Button();
     this.textStatus    = new System.Windows.Forms.TextBox();
     this.buttonPlay    = new System.Windows.Forms.Button();
     this.tbarPan       = new System.Windows.Forms.TrackBar();
     this.ofdFile       = new System.Windows.Forms.OpenFileDialog();
     this.buttonExit    = new System.Windows.Forms.Button();
     this.label11       = new System.Windows.Forms.Label();
     this.tbarVolume    = new System.Windows.Forms.TrackBar();
     this.label8        = new System.Windows.Forms.Label();
     this.label9        = new System.Windows.Forms.Label();
     this.buttonStop    = new System.Windows.Forms.Button();
     this.lblMaxFreq    = new System.Windows.Forms.Label();
     this.label5        = new System.Windows.Forms.Label();
     this.label6        = new System.Windows.Forms.Label();
     this.label7        = new System.Windows.Forms.Label();
     this.label1        = new System.Windows.Forms.Label();
     this.label2        = new System.Windows.Forms.Label();
     this.lblMinFreq    = new System.Windows.Forms.Label();
     this.textFreq      = new System.Windows.Forms.TextBox();
     this.tbarFreq      = new System.Windows.Forms.TrackBar();
     this.textPan       = new System.Windows.Forms.TextBox();
     ((System.ComponentModel.ISupportInitialize)(this.tmrUpdate)).BeginInit();
     this.groupBox1.SuspendLayout();
     this.groupBox4.SuspendLayout();
     this.groupBox2.SuspendLayout();
     this.groupBox5.SuspendLayout();
     ((System.ComponentModel.ISupportInitialize)(this.tbarPan)).BeginInit();
     ((System.ComponentModel.ISupportInitialize)(this.tbarVolume)).BeginInit();
     ((System.ComponentModel.ISupportInitialize)(this.tbarFreq)).BeginInit();
     this.SuspendLayout();
     //
     // radioDefault
     //
     this.radioDefault.Checked         = true;
     this.radioDefault.Location        = new System.Drawing.Point(93, 16);
     this.radioDefault.Name            = "radioDefault";
     this.radioDefault.Size            = new System.Drawing.Size(79, 14);
     this.radioDefault.TabIndex        = 3;
     this.radioDefault.TabStop         = true;
     this.radioDefault.Text            = "Default";
     this.radioDefault.CheckedChanged += new System.EventHandler(this.RadioChecked);
     //
     // tmrUpdate
     //
     this.tmrUpdate.Enabled             = true;
     this.tmrUpdate.SynchronizingObject = this;
     this.tmrUpdate.Elapsed            += new System.Timers.ElapsedEventHandler(this.tmrUpdate_Elapsed);
     //
     // checkLoop
     //
     this.checkLoop.Location = new System.Drawing.Point(8, 399);
     this.checkLoop.Name     = "checkLoop";
     this.checkLoop.Size     = new System.Drawing.Size(151, 19);
     this.checkLoop.TabIndex = 3;
     this.checkLoop.Text     = "Loop Sound";
     //
     // textVolume
     //
     this.textVolume.Location = new System.Drawing.Point(85, 148);
     this.textVolume.Name     = "textVolume";
     this.textVolume.ReadOnly = true;
     this.textVolume.Size     = new System.Drawing.Size(43, 20);
     this.textVolume.TabIndex = 1;
     this.textVolume.Text     = "0";
     //
     // label10
     //
     this.label10.Location  = new System.Drawing.Point(6, 140);
     this.label10.Name      = "label10";
     this.label10.Size      = new System.Drawing.Size(73, 38);
     this.label10.TabIndex  = 2;
     this.label10.Text      = "Volume";
     this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // groupBox1
     //
     this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {
         this.groupBox4,
         this.groupBox2
     });
     this.groupBox1.Location = new System.Drawing.Point(6, 181);
     this.groupBox1.Name     = "groupBox1";
     this.groupBox1.Size     = new System.Drawing.Size(437, 91);
     this.groupBox1.TabIndex = 5;
     this.groupBox1.TabStop  = false;
     this.groupBox1.Text     = "Buffer Settings";
     //
     // groupBox4
     //
     this.groupBox4.Controls.AddRange(new System.Windows.Forms.Control[] {
         this.radioHardware,
         this.label12,
         this.radioSoftware,
         this.radioDefault
     });
     this.groupBox4.Location = new System.Drawing.Point(8, 48);
     this.groupBox4.Name     = "groupBox4";
     this.groupBox4.Size     = new System.Drawing.Size(423, 36);
     this.groupBox4.TabIndex = 6;
     this.groupBox4.TabStop  = false;
     //
     // radioHardware
     //
     this.radioHardware.Location        = new System.Drawing.Point(173, 16);
     this.radioHardware.Name            = "radioHardware";
     this.radioHardware.Size            = new System.Drawing.Size(79, 14);
     this.radioHardware.TabIndex        = 3;
     this.radioHardware.Text            = "Hardware";
     this.radioHardware.CheckedChanged += new System.EventHandler(this.RadioChecked);
     //
     // label12
     //
     this.label12.Location  = new System.Drawing.Point(6, 13);
     this.label12.Name      = "label12";
     this.label12.Size      = new System.Drawing.Size(73, 15);
     this.label12.TabIndex  = 2;
     this.label12.Text      = "Buffer Mixing";
     this.label12.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // radioSoftware
     //
     this.radioSoftware.Location        = new System.Drawing.Point(268, 17);
     this.radioSoftware.Name            = "radioSoftware";
     this.radioSoftware.Size            = new System.Drawing.Size(79, 14);
     this.radioSoftware.TabIndex        = 3;
     this.radioSoftware.Text            = "Software";
     this.radioSoftware.CheckedChanged += new System.EventHandler(this.RadioChecked);
     //
     // groupBox2
     //
     this.groupBox2.Controls.AddRange(new System.Windows.Forms.Control[] {
         this.radioSticky,
         this.label13,
         this.radioGlobal,
         this.radioNormal
     });
     this.groupBox2.Location = new System.Drawing.Point(7, 11);
     this.groupBox2.Name     = "groupBox2";
     this.groupBox2.Size     = new System.Drawing.Size(423, 36);
     this.groupBox2.TabIndex = 6;
     this.groupBox2.TabStop  = false;
     //
     // radioSticky
     //
     this.radioSticky.Location        = new System.Drawing.Point(173, 16);
     this.radioSticky.Name            = "radioSticky";
     this.radioSticky.Size            = new System.Drawing.Size(79, 16);
     this.radioSticky.TabIndex        = 3;
     this.radioSticky.Text            = "Sticky";
     this.radioSticky.CheckedChanged += new System.EventHandler(this.RadioChecked);
     //
     // label13
     //
     this.label13.Location  = new System.Drawing.Point(6, 13);
     this.label13.Name      = "label13";
     this.label13.Size      = new System.Drawing.Size(73, 15);
     this.label13.TabIndex  = 2;
     this.label13.Text      = "Focus";
     this.label13.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // radioGlobal
     //
     this.radioGlobal.Location        = new System.Drawing.Point(268, 17);
     this.radioGlobal.Name            = "radioGlobal";
     this.radioGlobal.Size            = new System.Drawing.Size(79, 14);
     this.radioGlobal.TabIndex        = 3;
     this.radioGlobal.Text            = "Global";
     this.radioGlobal.CheckedChanged += new System.EventHandler(this.RadioChecked);
     //
     // radioNormal
     //
     this.radioNormal.Checked         = true;
     this.radioNormal.Location        = new System.Drawing.Point(93, 16);
     this.radioNormal.Name            = "radioNormal";
     this.radioNormal.Size            = new System.Drawing.Size(79, 14);
     this.radioNormal.TabIndex        = 3;
     this.radioNormal.TabStop         = true;
     this.radioNormal.Text            = "Normal";
     this.radioNormal.CheckedChanged += new System.EventHandler(this.RadioChecked);
     //
     // textFile
     //
     this.textFile.Location = new System.Drawing.Point(85, 6);
     this.textFile.Name     = "textFile";
     this.textFile.ReadOnly = true;
     this.textFile.Size     = new System.Drawing.Size(350, 20);
     this.textFile.TabIndex = 1;
     this.textFile.Text     = "";
     //
     // groupBox5
     //
     this.groupBox5.Controls.AddRange(new System.Windows.Forms.Control[] {
         this.lblBehavior
     });
     this.groupBox5.Location = new System.Drawing.Point(8, 278);
     this.groupBox5.Name     = "groupBox5";
     this.groupBox5.Size     = new System.Drawing.Size(431, 120);
     this.groupBox5.TabIndex = 6;
     this.groupBox5.TabStop  = false;
     this.groupBox5.Text     = "Expected Behavior";
     //
     // lblBehavior
     //
     this.lblBehavior.Location  = new System.Drawing.Point(6, 16);
     this.lblBehavior.Name      = "lblBehavior";
     this.lblBehavior.Size      = new System.Drawing.Size(422, 100);
     this.lblBehavior.TabIndex  = 0;
     this.lblBehavior.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // buttonSound
     //
     this.buttonSound.Location = new System.Drawing.Point(3, 6);
     this.buttonSound.Name     = "buttonSound";
     this.buttonSound.Size     = new System.Drawing.Size(74, 21);
     this.buttonSound.TabIndex = 0;
     this.buttonSound.Text     = "Sound File...";
     this.buttonSound.Click   += new System.EventHandler(this.buttonSound_Click);
     //
     // textStatus
     //
     this.textStatus.Location = new System.Drawing.Point(85, 33);
     this.textStatus.Name     = "textStatus";
     this.textStatus.ReadOnly = true;
     this.textStatus.Size     = new System.Drawing.Size(350, 20);
     this.textStatus.TabIndex = 1;
     this.textStatus.Text     = "No File Loaded.";
     //
     // buttonPlay
     //
     this.buttonPlay.Enabled  = false;
     this.buttonPlay.Location = new System.Drawing.Point(7, 421);
     this.buttonPlay.Name     = "buttonPlay";
     this.buttonPlay.Size     = new System.Drawing.Size(74, 21);
     this.buttonPlay.TabIndex = 0;
     this.buttonPlay.Text     = "Play";
     this.buttonPlay.Click   += new System.EventHandler(this.buttonPlay_Click);
     //
     // tbarPan
     //
     this.tbarPan.Location      = new System.Drawing.Point(164, 97);
     this.tbarPan.Maximum       = 20;
     this.tbarPan.Minimum       = -20;
     this.tbarPan.Name          = "tbarPan";
     this.tbarPan.Size          = new System.Drawing.Size(236, 42);
     this.tbarPan.TabIndex      = 4;
     this.tbarPan.TickFrequency = 5;
     this.tbarPan.Scroll       += new System.EventHandler(this.tbarPan_Scroll);
     //
     // ofdFile
     //
     this.ofdFile.Filter = "Wave Files (*.wav)|*.wav|All Files (*.*)|*.*";
     this.ofdFile.Title  = "Open Audio File";
     //
     // buttonExit
     //
     this.buttonExit.DialogResult = System.Windows.Forms.DialogResult.Cancel;
     this.buttonExit.Location     = new System.Drawing.Point(362, 421);
     this.buttonExit.Name         = "buttonExit";
     this.buttonExit.Size         = new System.Drawing.Size(74, 21);
     this.buttonExit.TabIndex     = 0;
     this.buttonExit.Text         = "Exit";
     this.buttonExit.Click       += new System.EventHandler(this.buttonExit_Click);
     //
     // label11
     //
     this.label11.Location  = new System.Drawing.Point(6, 13);
     this.label11.Name      = "label11";
     this.label11.Size      = new System.Drawing.Size(73, 15);
     this.label11.TabIndex  = 2;
     this.label11.Text      = "Focus";
     this.label11.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // tbarVolume
     //
     this.tbarVolume.Location = new System.Drawing.Point(165, 140);
     this.tbarVolume.Maximum  = 0;
     this.tbarVolume.Minimum  = -50;
     this.tbarVolume.Name     = "tbarVolume";
     this.tbarVolume.Size     = new System.Drawing.Size(236, 42);
     this.tbarVolume.TabIndex = 4;
     this.tbarVolume.Scroll  += new System.EventHandler(this.tbarVolume_Scroll);
     //
     // label8
     //
     this.label8.Location  = new System.Drawing.Point(131, 147);
     this.label8.Name      = "label8";
     this.label8.Size      = new System.Drawing.Size(41, 20);
     this.label8.TabIndex  = 2;
     this.label8.Text      = "Low";
     this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // label9
     //
     this.label9.Location  = new System.Drawing.Point(396, 149);
     this.label9.Name      = "label9";
     this.label9.Size      = new System.Drawing.Size(47, 20);
     this.label9.TabIndex  = 2;
     this.label9.Text      = "High";
     this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // buttonStop
     //
     this.buttonStop.Enabled  = false;
     this.buttonStop.Location = new System.Drawing.Point(87, 421);
     this.buttonStop.Name     = "buttonStop";
     this.buttonStop.Size     = new System.Drawing.Size(74, 21);
     this.buttonStop.TabIndex = 0;
     this.buttonStop.Text     = "Stop";
     this.buttonStop.Click   += new System.EventHandler(this.buttonStop_Click);
     //
     // lblMaxFreq
     //
     this.lblMaxFreq.Location  = new System.Drawing.Point(396, 68);
     this.lblMaxFreq.Name      = "lblMaxFreq";
     this.lblMaxFreq.Size      = new System.Drawing.Size(47, 20);
     this.lblMaxFreq.TabIndex  = 2;
     this.lblMaxFreq.Text      = "100 KHz";
     this.lblMaxFreq.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // label5
     //
     this.label5.Location  = new System.Drawing.Point(130, 104);
     this.label5.Name      = "label5";
     this.label5.Size      = new System.Drawing.Size(41, 20);
     this.label5.TabIndex  = 2;
     this.label5.Text      = "Left";
     this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // label6
     //
     this.label6.Location  = new System.Drawing.Point(395, 106);
     this.label6.Name      = "label6";
     this.label6.Size      = new System.Drawing.Size(47, 20);
     this.label6.TabIndex  = 2;
     this.label6.Text      = "Right";
     this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // label7
     //
     this.label7.Location  = new System.Drawing.Point(5, 97);
     this.label7.Name      = "label7";
     this.label7.Size      = new System.Drawing.Size(73, 38);
     this.label7.TabIndex  = 2;
     this.label7.Text      = "Pan";
     this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // label1
     //
     this.label1.Location  = new System.Drawing.Point(4, 33);
     this.label1.Name      = "label1";
     this.label1.Size      = new System.Drawing.Size(73, 20);
     this.label1.TabIndex  = 2;
     this.label1.Text      = "Status";
     this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // label2
     //
     this.label2.Location  = new System.Drawing.Point(6, 59);
     this.label2.Name      = "label2";
     this.label2.Size      = new System.Drawing.Size(73, 38);
     this.label2.TabIndex  = 2;
     this.label2.Text      = "Frequency";
     this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // lblMinFreq
     //
     this.lblMinFreq.Location  = new System.Drawing.Point(131, 66);
     this.lblMinFreq.Name      = "lblMinFreq";
     this.lblMinFreq.Size      = new System.Drawing.Size(41, 20);
     this.lblMinFreq.TabIndex  = 2;
     this.lblMinFreq.Text      = "100 Hz";
     this.lblMinFreq.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // textFreq
     //
     this.textFreq.Location = new System.Drawing.Point(85, 67);
     this.textFreq.Name     = "textFreq";
     this.textFreq.ReadOnly = true;
     this.textFreq.Size     = new System.Drawing.Size(43, 20);
     this.textFreq.TabIndex = 1;
     this.textFreq.Text     = "0";
     //
     // tbarFreq
     //
     this.tbarFreq.LargeChange   = 1000;
     this.tbarFreq.Location      = new System.Drawing.Point(165, 59);
     this.tbarFreq.Maximum       = 100000;
     this.tbarFreq.Minimum       = 100;
     this.tbarFreq.Name          = "tbarFreq";
     this.tbarFreq.Size          = new System.Drawing.Size(236, 42);
     this.tbarFreq.SmallChange   = 100;
     this.tbarFreq.TabIndex      = 4;
     this.tbarFreq.TickFrequency = 10000;
     this.tbarFreq.Value         = 100;
     this.tbarFreq.Scroll       += new System.EventHandler(this.tbarFreq_Scroll);
     //
     // textPan
     //
     this.textPan.Location = new System.Drawing.Point(85, 105);
     this.textPan.Name     = "textPan";
     this.textPan.ReadOnly = true;
     this.textPan.Size     = new System.Drawing.Size(43, 20);
     this.textPan.TabIndex = 1;
     this.textPan.Text     = "0";
     //
     // wfAdjust
     //
     this.AcceptButton      = this.buttonSound;
     this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
     this.CancelButton      = this.buttonExit;
     this.ClientSize        = new System.Drawing.Size(460, 448);
     this.Controls.AddRange(new System.Windows.Forms.Control[] {
         this.groupBox5,
         this.groupBox1,
         this.textVolume,
         this.label8,
         this.label9,
         this.label10,
         this.tbarVolume,
         this.label5,
         this.label6,
         this.tbarPan,
         this.textPan,
         this.label7,
         this.lblMaxFreq,
         this.lblMinFreq,
         this.textFreq,
         this.tbarFreq,
         this.label2,
         this.checkLoop,
         this.buttonStop,
         this.buttonPlay,
         this.buttonExit,
         this.label1,
         this.textStatus,
         this.textFile,
         this.buttonSound
     });
     this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
     this.MaximizeBox     = false;
     this.Name            = "wfAdjust";
     this.Text            = "AdjustSound";
     ((System.ComponentModel.ISupportInitialize)(this.tmrUpdate)).EndInit();
     this.groupBox1.ResumeLayout(false);
     this.groupBox4.ResumeLayout(false);
     this.groupBox2.ResumeLayout(false);
     this.groupBox5.ResumeLayout(false);
     ((System.ComponentModel.ISupportInitialize)(this.tbarPan)).EndInit();
     ((System.ComponentModel.ISupportInitialize)(this.tbarVolume)).EndInit();
     ((System.ComponentModel.ISupportInitialize)(this.tbarFreq)).EndInit();
     this.ResumeLayout(false);
 }
Exemplo n.º 30
0
        public MainForm()
        {
            InitializeComponent();

            //Enable double buffering
            typeof(Panel).InvokeMember("DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, panel, new object[] { true });

            //Panel handlers
            panel.Paint     += new PaintEventHandler(panel_Paint);
            panel.MouseMove += new MouseEventHandler(panel_MouseMove);
            panel.MouseDown += new MouseEventHandler(panel_MouseDown);
            panel.MouseUp   += new MouseEventHandler(panel_MouseUp);

            this.FormClosing += new FormClosingEventHandler(MainForm_FormClosing);

            this.KeyDown += new KeyEventHandler(MainForm_KeyDown);
            this.KeyUp   += new KeyEventHandler(MainForm_KeyUp);

            //Screen refresh timer
            gametimer          = new System.Timers.Timer();
            gametimer.Interval = 32;
            gametimer.Elapsed += new System.Timers.ElapsedEventHandler(gametimer_Elapsed);

            //Get default mouse position
            Point paneltopleft = this.PointToScreen(Point.Empty);

            paneltopleft.X += panel.Left;
            paneltopleft.Y += panel.Top;

            mouseclipold = Cursor.Clip;
            mouseclipnew = new Rectangle(paneltopleft.X, paneltopleft.Y, panel.Width, panel.Height);

            defaultmousepos = new Point(paneltopleft.X + panel.Width / 2, paneltopleft.Y + panel.Height / 2);

            renderer = new Renderer(panel.Size);
            player   = new Player();
            player.SetYView(panel.Height / 2);
            gameobjects = new List <GameObject>();
            int status = LoadInfo();

            if (status == 0)
            {
                loadsuccess  = true;
                mousecapture = true;
                renderer.LoadSky("sky.png");
                renderer.LoadFloor("floor.png");
                renderer.LoadFPSOverlay1("fpshands1.png");
                renderer.LoadFPSOverlay2("fpshands2.png");
                gametimer.Start();
            }
            else
            {
                MessageBox.Show("Couldn't load game info. Code: " + status);
                Application.Exit();
            }

            //Default mouse and hide
            if (mousecapture)
            {
                Cursor.Position = defaultmousepos;
                Cursor.Hide();
            }
        }
        internal void UDPReciever()
        {
            try
            {
                timerforchecklogin          = new System.Timers.Timer();
                timerforchecklogin.Interval = 30000;
                timerforchecklogin.Start();
                timerforchecklogin.Elapsed += timerforchecklogin_Elapsed;
                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        //		string address = subscriber.Receive (Encoding.Unicode);
                        //	    byte[] buffer = new byte[512];
                        //	    int bufferSize = subscriber.Receive (buffer);

                        var buffer = subscriber.Receive();
                        if (buffer == null)
                        {
                            this.OnDataStatusChange.Raise(OnDataStatusChange, OnDataStatusChange.CreateReadOnlyArgs("STOP"));
                            continue;
                        }

                        //Data = (INTERACTIVE_ONLY_MBP)DataPacket.RawDeserialize(buffer.Skip(4).ToArray(), typeof(INTERACTIVE_ONLY_MBP));


                        long TokenName = BitConverter.ToInt64(buffer, 0);

                        Data = (INTERACTIVE_ONLY_MBP)DataPacket.RawDeserialize(buffer.Skip(8).ToArray(), typeof(INTERACTIVE_ONLY_MBP));
                        OnDataChange.Raise(OnDataChange, OnDataChange.CreateReadOnlyArgs(Data));

                        //if (Global.Instance.Data_With_Nano.ContainsKey(TokenName))
                        //{
                        //    switch(Global.Instance.Data_With_Nano[TokenName])
                        //    {
                        //        case ClassType.MARKETWTCH:

                        //        Data = (INTERACTIVE_ONLY_MBP)DataPacket.RawDeserialize(buffer.Skip(8).ToArray(), typeof(INTERACTIVE_ONLY_MBP));
                        //        OnDataChange.Raise(OnDataChange, OnDataChange.CreateReadOnlyArgs(Data));
                        //            break;

                        //        case ClassType.SPREAD:

                        //            SpreadData_7211 = (MS_SPD_MKT_INFO_7211)DataPacket.RawDeserialize(buffer.Skip(8).ToArray(), typeof(MS_SPD_MKT_INFO_7211));
                        //            OnSpreadDataChange.Raise(OnSpreadDataChange, OnSpreadDataChange.CreateReadOnlyArgs(SpreadData_7211));
                        //            break;
                        //    }
                        //}
                    }
                });
            }
            catch (OperationCanceledException e)
            {
                Console.WriteLine("Cancellation invoked");
            }
            catch (AggregateException e)
            {
                Console.WriteLine("Some unexpected exception ");
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Exception Raised " + Ex.StackTrace);
            }
        }
Exemplo n.º 32
0
        private void ReceivingWorker()
        {
            System.Timers.Timer checkConnectionTimer = new System.Timers.Timer();
            checkConnectionTimer.Interval = 1000;

            checkConnectionTimer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e)
            {
                lock (oClientSocketLock)
                {
                    for (int i = 0; i < lClientSockets.Count; i++)
                    {
                        if (!lClientSockets[i].SocketConnected())
                        {
                            lClientSockets.RemoveAt(i);
                            if (eSocketListChanged != null)
                            {
                                eSocketListChanged(lClientSockets);
                            }
                            continue;
                        }
                    }
                }
            };

            checkConnectionTimer.Start();

            while (bServerRunning)
            {
                lock (oClientSocketLock)
                {
                    for (int i = 0; i < lClientSockets.Count; i++)
                    {
                        byte[] buffer = lClientSockets[i].Receive(1);

                        while (buffer.Length != 0)
                        {
                            if (buffer[0] == 0)
                            {
                                lClientSockets[i].bFrameCaptured = true;
                            }
                            else if (buffer[0] == 1)
                            {
                                lClientSockets[i].ReceiveCalibrationData();
                            }
                            //stored frame
                            else if (buffer[0] == 2)
                            {
                                lClientSockets[i].ReceiveFrame();
                                lClientSockets[i].bStoredFrameReceived = true;
                                lClientSockets[i].bWaitingForFrame     = false;
                            }

                            //last frame
                            else if (buffer[0] == 3)
                            {
                                lClientSockets[i].ReceiveFrame();
                                lClientSockets[i].bLatestFrameReceived = true;
                                lClientSockets[i].bWaitingForFrame     = false;
                            }
                            // Camera intrinsic parameters
                            else if (buffer[0] == 4)
                            {
                                lClientSockets[i].ReceiveCameraIntrinsicParameters();
                            }
                            else if (buffer[0] == 5)
                            {
                                lClientSockets[i].bNoMoreStoredFrames = true;
                                lClientSockets[i].bWaitingForFrame    = false;
                            }

                            buffer = lClientSockets[i].Receive(1);
                        }
                    }
                }

                Thread.Sleep(10);
            }

            checkConnectionTimer.Stop();
        }
Exemplo n.º 33
0
 public void DestroySimulation()
 {
     PauseSimulation();
     _timer = null;
 }
Exemplo n.º 34
0
    private static void emailTriggerTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e, string fname, System.Timers.Timer emailTriggerTimer)
    {
        emailTriggerTimer.Stop();
        emailTriggerTimer.Enabled = false;

        Console.WriteLine(fname + " Elapsed " + DateTime.Now);
        emailTriggerTimer.Interval = GetsTimeIntervalFromConfigFile();     //** Gets Client specific TIME INTERVAL

        emailTriggerTimer.Start();
        emailTriggerTimer.Enabled = true;
    }
Exemplo n.º 35
0
        /// <summary>
        /// Handles a failed connection to a server.
        /// This method can be overrided to implement a custom failover handling
        /// </summary>
        /// <param name="server">The failed server</param>
        internal protected virtual void HandleFailover(ReplicationServer server)
        {
            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
                bool isRunning            = false;
                ReplicationServer server1 = e.Argument as ReplicationServer;
#if !RT
                System.Timers.Timer timer = new System.Timers.Timer(RetryTime * 1000.0);

                System.Timers.ElapsedEventHandler elapsedEvent = delegate(object sender1, System.Timers.ElapsedEventArgs e1)
                {
                    if (isRunning)
                    {
                        return;
                    }
                    try
                    {
                        isRunning = true;
                        using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString))
                        {
                            connectionFailed.Open();
                            server1.IsAvailable = true;
                            timer.Stop();
                        }
                    }
                    catch
                    {
                        MySqlTrace.LogWarning(0,
                                              string.Format(SqlConsoleProvider.Properties.Resources.Replication_ConnectionAttemptFailed, server1.Name));
                    }
                    finally
                    {
                        isRunning = false;
                    }
                };
                timer.Elapsed += elapsedEvent;
                timer.Start();
                elapsedEvent(sender, null);
#else
                Windows.UI.Xaml.DispatcherTimer timer = new Windows.UI.Xaml.DispatcherTimer();
                TimeSpan ts = new TimeSpan(RetryTime * 1000);
                System.EventHandler <object> elapsedEvent = (TickSender, TickEventArgs) =>
                {
                    if (isRunning)
                    {
                        return;
                    }
                    try
                    {
                        isRunning = true;
                        using (MySqlConnection connectionFailed = new MySqlConnection(server.ConnectionString))
                        {
                            connectionFailed.Open();
                            server1.IsAvailable = true;
                            timer.Stop();
                        }
                    }
                    catch
                    {
                        MySqlTrace.LogWarning(0,
                                              string.Format(Properties.Resources.Replication_ConnectionAttemptFailed, server1.Name));
                    }
                    finally
                    {
                        isRunning = false;
                    }
                };
                timer.Tick += elapsedEvent;
                elapsedEvent(sender, null);
                timer.Start();
#endif
            };

            worker.RunWorkerAsync(server);
        }
        public MainWindow()
        {
            InitializeComponent();

            TasksList = new ObservableCollection <Task>();

            Shown = IsShown.no;
            foreach (var task in TasksList)
            {
                if (task.EndingDate == DateTime.Now.AddDays(1).ToString("dd-MM-yyyy HH:mm"))
                {
                    if (Shown == IsShown.no)
                    {
                        MessageBox.Show("One of your tasks is going to meet a deadline tomorrow!" +
                                        "\nCheck tasklist for further information.",
                                        "Announcement - deadline tomorrow",
                                        MessageBoxButton.OK, MessageBoxImage.Information);
                        Shown = IsShown.yes;
                    }
                }
                else if (task.EndingDate == DateTime.Now.AddHours(1).ToString("dd-MM-yyyy HH:mm"))
                {
                    if (Shown == IsShown.no)
                    {
                        MessageBox.Show("One of your tasks is going to meet a deadline in one hour!" +
                                        "\nCheck tasklist for further information.",
                                        "Announcement - deadline in one hour",
                                        MessageBoxButton.OK, MessageBoxImage.Information);
                        Shown = IsShown.yes;
                    }
                }
                else if (task.EndingDate == DateTime.Now.AddHours(12).ToString("dd-MM-yyyy HH:mm"))
                {
                    if (Shown == IsShown.no)
                    {
                        MessageBox.Show("One of your tasks is going to meet a deadline in 12 hours!" +
                                        "\nCheck tasklist for further information.",
                                        "Announcement - deadline in one hour",
                                        MessageBoxButton.OK, MessageBoxImage.Information);
                        Shown = IsShown.yes;
                    }
                }
                else if (task.EndingDate == DateTime.Now.AddHours(6).ToString("dd-MM-yyyy HH:mm"))
                {
                    if (Shown == IsShown.no)
                    {
                        MessageBox.Show("One of your tasks is going to meet a deadline in 6 hours!" +
                                        "\nCheck tasklist for further information.",
                                        "Announcement - deadline in one hour",
                                        MessageBoxButton.OK, MessageBoxImage.Information);
                        Shown = IsShown.yes;
                    }
                }
                else if (task.EndingDate == DateTime.Now.ToString("dd-MM-yyyy HH:mm"))
                {
                    if (Shown == IsShown.no)
                    {
                        MessageBox.Show("One of your tasks have met a deadline!" +
                                        "\nCheck tasklist for further information.",
                                        "Announcement - deadline in one hour",
                                        MessageBoxButton.OK, MessageBoxImage.Warning);
                        Shown = IsShown.yes;
                    }
                }
            }
            Shown = IsShown.no;

            TimeCounter          = new System.Timers.Timer(60000);
            TimeCounter.Elapsed += TimeCounter_Elapsed;
            TimeCounter.Start();

            OnPropertyChanged(nameof(TasksList));
        }
        private void run()
        {
            byte[] dataBuffer     = new byte[256];
            int    bufferPosition = 0;

            timeoutTimer          = new System.Timers.Timer();
            timeoutTimer.Interval = 200;
            timeoutTimer.Elapsed += TimeoutTimer_Elapsed;

            try
            {
                serialPort.Open();

                ConnectionStateChanged?.Invoke(this, null);

                while (serialPort.IsOpen)
                {
                    int bytesToRead = serialPort.BytesToRead;
                    if (state == State.Idle)
                    {
                        if (bytesToRead > 0)
                        {
                            timeoutTimer.Start();
                            state = State.Receiving;
                        }
                        else if (commandToSend != null)
                        {
                            state = State.Sending;
                        }
                    }

                    switch (state)
                    {
                    case State.Receiving:
                    {
                        if (bytesToRead > 0)
                        {
                            if ((bytesToRead + bufferPosition) < dataBuffer.Length)
                            {
                                serialPort.Read(dataBuffer, bufferPosition, bytesToRead);
                                bufferPosition += bytesToRead;
                            }
                            else
                            {
                                serialPort.Read(dataBuffer, bufferPosition, (dataBuffer.Length - bufferPosition));
                                bufferPosition += (dataBuffer.Length - bufferPosition);
                            }


                            while (CheckDataBuffer(dataBuffer, bufferPosition))
                            {
                                MGBTCommandData data = MGBTCommandData.FromArray(dataBuffer);
                                if (data.VerifyCRC())
                                {
                                    rxQueue.Enqueue(data);
                                    NewDataArrived?.Invoke(this, null);
                                }
                                else
                                {
                                }
                                if (bufferPosition > (data.dataLength + 8))
                                {
                                    byte[] newDataBuffer = new byte[dataBuffer.Length];
                                    Array.Copy(dataBuffer, (data.dataLength + 8), newDataBuffer, 0, dataBuffer.Length - (data.dataLength + 8));
                                    dataBuffer      = newDataBuffer;
                                    bufferPosition -= (data.dataLength + 8);
                                }
                                else
                                {
                                    Array.Clear(dataBuffer, 0, dataBuffer.Length);
                                    bufferPosition = 0;
                                    state          = State.Idle;
                                }
                            }
                        }
                        break;
                    }

                    case State.Sending:
                    {
                        byte[] data = null;
                        lock (lockObj)
                        {
                            commandToSend.UpdateCRC();
                            data          = commandToSend.ToArray(false);
                            commandToSend = null;
                            state         = State.Idle;
                        }

                        if (data != null)
                        {
                            serialPort.Write(data, 0, data.Length);
                        }

                        break;
                    }

                    default:
                    {
                        break;
                    }
                    }

                    Thread.Sleep(10);
                }
            }
            catch (Exception e)
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
            }
            ConnectionStateChanged?.Invoke(this, null);
        }
Exemplo n.º 38
0
 /// <summary>
 /// Add the reset method to the System.Timer class.
 /// </summary>
 /// <param name="timer">System.timer object</param>
 public static void Reset(this Timer timer)
 {
     timer.Stop();
     timer.Start();
 }
Exemplo n.º 39
0
        // Кнопка "Старт"
        private async void button_Upload_Start_Click(object sender, RoutedEventArgs e)
        {
            button_Upload_Start.IsEnabled = false;

            // Проверка путей
            CheckPath();

            // Очищаем
            Upload_IsStop  = false;
            Upload_IsPause = false;
            button_Upload_Stop.IsEnabled = true;

            // Обновляем статистику
            label_Upload_Count_Accounts.Text = "0";
            label_Upload_Count_Error.Text    = "0";
            label_Upload_Count_Good.Text     = "0";
            label_Upload_Count_ThisIP.Text   = "0";
            label_Upload_Count_LastIP.Text   = "0";
            label_Upload_Count_Time.Text     = "00:00:00";
            Upload_ProgressCounter           = 0;
            Upload_AllIPProgressCounter      = 0;
            Upload_ProgressBarText.Text      = "0 %";

            // Задаем значения прогрессбара
            Upload_ProgressBar.Minimum = 0;
            Upload_ProgressBar.Maximum = 100;
            Upload_ProgressBar.Value   = 0;

            // Объявляем объект синхронизации статистики
            object Upload_Sync_Stat = new object();

            // Задаем стартовое время
            Upload_Time = DateTime.Now;

            // Счетчик потоков
            int ThreadCount = (int)numericUpDown_Upload_ThreadCount.Value;

            // Таймаут
            int Timeout = (int)numericUpDown_Upload_Timeout.Value * 1000;

            // Таймаут загрузки
            int LoadTimeout = (int)numericUpDown_Upload_LoadTimeout.Value * 1000;

            // Таймаут подключения
            int ConnectTimeout = (int)numericUpDown_Upload_ConnectTimeout.Value * 1000;

            // Режим отладки
            bool Debug = (bool)checkBox_Upload_Debug.IsChecked;

            // FTP
            bool UseFTP = (bool)checkBox_Upload_UseFTP.IsChecked;

            // DRIVE
            bool UseDRIVE = (bool)checkBox_Upload_UseDRIVE.IsChecked;

            // CLIPBOARD
            bool UseCLIPBOARD = (bool)checkBox_Upload_UseCLIPBOARD.IsChecked;

            // HTTP PS
            bool UseHTTP_BA = (bool)checkBox_Upload_UseHTTP_BA.IsChecked;

            // HTTP PS
            bool UseHTTP_PS = (bool)checkBox_Upload_UseHTTP_PS.IsChecked;

            // HTTP URL
            string URL = textBox_Upload_HTTP_URL.Text.Trim();

            // FTP хост
            string FTPHost = textBox_Upload_FTPHost.Text.Trim();

            // FTP порт
            string FTPPort = textBox_Upload_FTPPort.Text.Trim();

            // FTP логин
            string FTPLogin = textBox_Upload_FTPLogin.Text.Trim();

            // FTP пароль
            string FTPPassword = textBox_Upload_FTPPassword.Text.Trim();

            // FTP путь к файлу
            string FTPPFilePath = textBox_Upload_FTPFilePath.Text.Trim();

            // Список аккаунтов
            var AccountList = new List <string>();

            // Получаем аккаунты
            if (string.IsNullOrWhiteSpace(richTextBox_Upload_AccountList.Text))
            {
                var mbox = new MessageBox("RDP accounts is empty!", "Notification");
                mbox.ShowDialog();
                button_Upload_Start.IsEnabled = true;
                return;
            }
            else
            {
                foreach (var account in richTextBox_Upload_AccountList.Text.Trim().Split(new string[] { "\n" }, StringSplitOptions.None))
                {
                    string ip       = "";
                    string port     = "";
                    string login    = "";
                    string password = "";
                    string param    = "";

                    if (!string.IsNullOrWhiteSpace(account) && !account.Contains(">>>"))
                    {
                        // Парсим аккаунт
                        string validAccount = Utility.TextUtil.AccountNormalizer(account);

                        if (!string.IsNullOrWhiteSpace(validAccount))
                        {
                            ip    = validAccount.Split(';')[0].Trim().Split(':')[0].Trim();
                            port  = validAccount.Split(';')[0].Trim().Split(':')[1].Trim();
                            login = validAccount.Split(';')[1].Trim();
                            try
                            {
                                password = Regex.Split(validAccount, "^[^;]+;[^;]+;(.+)$")[1].Trim();
                            }
                            catch { }

                            AccountList.Add(ip + ":" + port + ";" + login + ";" + password);
                        }
                    }
                    else if (account.Contains(">>>"))
                    {
                        // Парсим аккаунт
                        string validAccount = Utility.TextUtil.AccountNormalizer(account.Split(new string[] { ">>>" }, StringSplitOptions.None)[0].Trim());

                        if (!string.IsNullOrWhiteSpace(validAccount))
                        {
                            ip    = validAccount.Split(';')[0].Trim().Split(':')[0].Trim();
                            port  = validAccount.Split(';')[0].Trim().Split(':')[1].Trim();
                            login = validAccount.Split(';')[1].Trim();
                            try
                            {
                                password = Regex.Split(validAccount, "^[^;]+;[^;]+;(.+)$")[1].Trim();
                            }
                            catch { }

                            param = account.Split(new string[] { ">>>" }, StringSplitOptions.None)[1].Trim();

                            AccountList.Add(ip + ":" + port + ";" + login + ";" + password + ">>>" + param);
                        }
                    }
                }

                // Убираем дубли
                AccountList = AccountList
                              .Distinct()
                              .ToList();

                // Обновляем статистику
                label_Upload_Count_Accounts.Text = AccountList.Count.ToString();
            }

            // Проверяем выбранные методы
            if (!UseDRIVE && !UseCLIPBOARD && !UseHTTP_BA && !UseHTTP_PS && !UseFTP)
            {
                var mbox = new MessageBox("Not selected method!", "Notification");
                mbox.ShowDialog();
                button_Upload_Start.IsEnabled = true;

                return;
            }
            else if (UseHTTP_PS && PowerShellScriptText == null)
            {
                var mbox = new MessageBox("Not upload script power shell file", "Notification");
                mbox.ShowDialog();
                button_Upload_Start.IsEnabled = true;

                return;
            }
            else
            {
                // Проверка CLIPBOARD и DRIVE
                if (UseDRIVE || UseCLIPBOARD)
                {
                    // Проверяем файл
                    if (FileBytes == null || string.IsNullOrWhiteSpace(FileName))
                    {
                        var mbox = new MessageBox("File not loaded!", "Notification");
                        mbox.ShowDialog();
                        button_Upload_Start.IsEnabled = true;
                        return;
                    }
                }

                // Проверка HTTP
                if (UseHTTP_BA)
                {
                    if (string.IsNullOrWhiteSpace(URL))
                    {
                        var mbox = new MessageBox("URL is empty!", "Notification");
                        mbox.ShowDialog();
                        button_Upload_Start.IsEnabled = true;
                        return;
                    }
                }

                // Проверяем настройки FTP
                if (UseFTP)
                {
                    if (string.IsNullOrWhiteSpace(FTPHost) ||
                        string.IsNullOrWhiteSpace(FTPPort) ||
                        string.IsNullOrWhiteSpace(FTPLogin) ||
                        string.IsNullOrWhiteSpace(FTPPassword) ||
                        string.IsNullOrWhiteSpace(FTPPFilePath))
                    {
                        var mbox = new MessageBox("FTP is empty!", "Notification");
                        mbox.ShowDialog();
                        button_Upload_Start.IsEnabled = true;
                        return;
                    }
                }
            }

            // Получаем счетчик ip адресов для прогрессбара и статистики
            Upload_AllIPProgressCounter    = (uint)AccountList.Count;
            label_Upload_Count_LastIP.Text = Upload_AllIPProgressCounter.ToString();

            // Запускаем таймер для обновления прогрессбара
            var timer = new System.Timers.Timer();

            timer.AutoReset = true;
            timer.Enabled   = true;
            timer.Elapsed  += timer_Upload_Elapsed;
            timer.Interval  = 500;
            timer.Start();

            // Запускаем таймер для обновления времени выполнения
            var timerTime = new System.Timers.Timer();

            timerTime.AutoReset = true;
            timerTime.Enabled   = true;
            timerTime.Elapsed  += timerTime_Upload_Elapsed;
            timerTime.Interval  = 500;
            timerTime.Start();

            // Разбиваем подстроки на части
            int count       = AccountList.Count();
            var chunkLength = (int)Math.Ceiling(count / (double)ThreadCount);
            var parts       = Enumerable.Range(0, ThreadCount).Select(i => AccountList.Skip(i * chunkLength).Take(chunkLength).ToList()).ToList();

            // Создаем массив потоков
            var threads = new Thread[ThreadCount];

            await Task.Run(() =>
            {
                // Начинаем работу
                for (int i = 0; i < threads.Length; i++)
                {
                    if (parts[i] != null)
                    {
                        // Аккаунты
                        var Source = parts[i];

                        threads[i] = new Thread(() =>
                        {
                            // Проходимся по списку аккаунтов
                            foreach (var account in Source)
                            {
                                // Проверка на остановку
                                if (Upload_IsStop)
                                {
                                    break;
                                }


                                // Проверка на паузу
                                while (Upload_IsPause)
                                {
                                    Thread.Sleep(1000);
                                }

                                // Парсим аккаунт
                                string ip       = "";
                                int port        = 0;
                                string login    = "";
                                string password = "";
                                string param    = "";

                                if (!string.IsNullOrWhiteSpace(account))
                                {
                                    if (!account.Contains(">>>"))
                                    {
                                        ip    = account.Split(';')[0].Trim().Split(':')[0].Trim();
                                        port  = int.Parse(account.Split(';')[0].Trim().Split(':')[1].Trim());
                                        login = account.Split(';')[1].Trim();
                                        try
                                        {
                                            password = Regex.Split(account, "[^;]+;[^;]+;(.+)")[1].Trim();
                                        }
                                        catch { }
                                    }
                                    else
                                    {
                                        var tempAcc = account.Split(new string[] { ">>>" }, StringSplitOptions.None)[0];
                                        ip          = tempAcc.Split(';')[0].Trim().Split(':')[0].Trim();
                                        port        = int.Parse(tempAcc.Split(';')[0].Trim().Split(':')[1].Trim());
                                        login       = tempAcc.Split(';')[1].Trim();
                                        try
                                        {
                                            password = Regex.Split(tempAcc, "^[^;]+;[^;]+;(.+)$")[1].Trim();
                                        }
                                        catch { }

                                        param = account.Split(new string[] { ">>>" }, StringSplitOptions.None)[1].Trim();
                                    }
                                }
                                else
                                {
                                    continue;
                                }

                                if (PortScaner.IsOpenPort(ip, port, Timeout))
                                {
                                    // Результат проверки
                                    //var result = PortScaner.GetRdpVersion(ip, port, Timeout).Value;

                                    string powerShell = PowerShellScriptText.Replace("[rdphost]", ip);

                                    // Выполняем загрузку и запуск файла на RDP
                                    SelectMethod(ip, port, login, password, true,
                                                 URL, FTPHost, FTPPort, FTPLogin, FTPPassword, FTPPFilePath,
                                                 UseDRIVE, UseCLIPBOARD, UseHTTP_BA, UseHTTP_PS, UseFTP,
                                                 Timeout, LoadTimeout, ConnectTimeout, param, powerShell, Debug);

                                    UploadVistaCollection.Add(ip + ":" + port.ToString() + ";" + login + ";" + password);

                                    //if (result) { UploadVistaCollection.Add(ip + ":" + port.ToString() + ";" + login + ";" + password); }
                                    //else { UploadXpCollection.Add(ip + ":" + port.ToString() + ";" + login + ";" + password); }
                                }
                                else
                                {
                                    UploadErrorCollection.Add(ip + ":" + port.ToString() + ";" + login + ";" + password);
                                }

                                // Обновляем счетчик прогрессбара
                                lock (Upload_Sync_Stat)
                                    Upload_ProgressCounter++;
                            }
                        }, 4096);

                        threads[i].IsBackground = true;
                        threads[i].Start();
                    }
                }
            });

            // Ожидаем завершение потоков
            await Task.Run(() =>
            {
                foreach (var tread in threads)
                {
                    tread.Join();
                }
            });

            await Task.Delay(1000);

            // Останавливаем таймер
            timer.Stop();
            timerTime.Stop();

            // Обновляем прогрессбар
            Upload_ProgressBarText.Text = "100 %";
            Upload_ProgressBar.Value    = Upload_ProgressBar.Maximum;

            // Разблокируем кнопки
            button_Upload_Stop.IsEnabled  = true;
            button_Upload_Start.IsEnabled = true;
        }
Exemplo n.º 40
0
        protected override void OnStart(string[] args)
        {
            try
            {
                var timersend = System.Configuration.ConfigurationManager.AppSettings.Get("TimerSend");
                var logdata   = System.Configuration.ConfigurationManager.AppSettings.Get("LogData");
                _servername = System.Configuration.ConfigurationManager.AppSettings.Get("ServerName");

                var rabbitHost               = System.Configuration.ConfigurationManager.AppSettings.Get("RabbitHost");
                var rabbitPort               = System.Configuration.ConfigurationManager.AppSettings.Get("RabbitPort");
                var rabbitUserName           = System.Configuration.ConfigurationManager.AppSettings.Get("RabbitUserName");
                var rabbitPassword           = System.Configuration.ConfigurationManager.AppSettings.Get("RabbitPassword");
                var rabbitPerformanceDataKey = System.Configuration.ConfigurationManager.AppSettings.Get("RabbitPerformanceDataKey");
                var rabbitPerformanceHighKey = System.Configuration.ConfigurationManager.AppSettings.Get("RabbitPerformanceHighKey");

                var cpuHighPercent  = System.Configuration.ConfigurationManager.AppSettings.Get("CPUHighPercent");
                var ramHighPercent  = System.Configuration.ConfigurationManager.AppSettings.Get("RAMHighPercent");
                var hddHighPercent  = System.Configuration.ConfigurationManager.AppSettings.Get("HDDHighPercent");
                var sendHigh        = System.Configuration.ConfigurationManager.AppSettings.Get("SendHigh");
                var secondHighCheck = System.Configuration.ConfigurationManager.AppSettings.Get("SecondHighCheck");
                var secondCheck     = System.Configuration.ConfigurationManager.AppSettings.Get("SecondCheck");
                _batchFileInit  = System.Configuration.ConfigurationManager.AppSettings.Get("BatchInit");
                _batchFileCheck = System.Configuration.ConfigurationManager.AppSettings.Get("BatchCheck");
                _batchFileClear = System.Configuration.ConfigurationManager.AppSettings.Get("BatchClear");

                if (!string.IsNullOrEmpty(timersend) && !string.IsNullOrEmpty(logdata) && !string.IsNullOrEmpty(_servername) && !string.IsNullOrEmpty(sendHigh) && !string.IsNullOrEmpty(secondCheck))
                {
                    int i = Convert.ToInt32(timersend);
                    _secondCheck     = Convert.ToInt32(secondCheck);
                    _secondHighCheck = Convert.ToDouble(secondHighCheck);
                    if (i > 0 && _secondCheck > 5)
                    {
                        _lstDTO     = new List <InfoData>();
                        _islog      = logdata == "true";
                        _isSendHigh = sendHigh == "true";
                        if (!string.IsNullOrEmpty(rabbitPort))
                        {
                            _rabbitPort = Convert.ToInt32(rabbitPort);
                        }
                        _rabbitHost               = rabbitHost;
                        _rabbitUserName           = rabbitUserName;
                        _rabbitPassword           = rabbitPassword;
                        _rabbitPerformanceDataKey = rabbitPerformanceDataKey;
                        _rabbitPerformanceHighKey = rabbitPerformanceHighKey;

                        _batchClear    = false;
                        _batchRun      = false;
                        _batchComplete = false;

                        if (!string.IsNullOrEmpty(cpuHighPercent))
                        {
                            _cpuHighPercent = Convert.ToSingle(cpuHighPercent);
                        }
                        if (!string.IsNullOrEmpty(ramHighPercent))
                        {
                            _ramHighPercent = Convert.ToSingle(ramHighPercent);
                        }
                        if (!string.IsNullOrEmpty(hddHighPercent))
                        {
                            _hddHighPercent = Convert.ToSingle(hddHighPercent);
                        }
                        if (_cpuHighPercent < 1 || _ramHighPercent < 1 || _hddHighPercent < 1)
                        {
                            throw new Exception("HighPercent fail");
                        }

                        HelperProcess.Init();
                        Microsoft.VisualBasic.Devices.ComputerInfo ci = new Microsoft.VisualBasic.Devices.ComputerInfo();
                        _totalPhysicalMemory = (ci.TotalPhysicalMemory / 1024) * 0.001;
                        _cpuUsage            = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                        _dto = GetInfo();

                        LogInfo("Start service (" + _servername + ")");
                        _timerGet               = new System.Timers.Timer(1000);//1s
                        _timerGet.Elapsed      += TimerGet_Elapsed;
                        _timerGet.Enabled       = true;
                        _timerGetReset          = new System.Timers.Timer(600000);//10p reset
                        _timerGetReset.Enabled  = false;
                        _timerGetReset.Elapsed += TimerGetReset_Elapsed;

                        _timerSend               = new System.Timers.Timer(i);
                        _timerSend.Elapsed      += TimerSend_Elapsed;
                        _timerSend.Enabled       = true;
                        _timerSendReset          = new System.Timers.Timer(600000);//10p reset
                        _timerSendReset.Enabled  = false;
                        _timerSendReset.Elapsed += TimerSendReset_Elapsed;
                    }
                    else
                    {
                        throw new Exception("TimerSend fail");
                    }
                }
                else
                {
                    throw new Exception("Config fail");
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
        }
Exemplo n.º 41
0
        public void RelayMethod(object obj)
        {
            string command = obj.ToString();

            //  Do:应用
            if (command == "Init")
            {
                ClipBoardRegisterService.Instance.ClipBoardChanged += () =>
                {
                    if (!System.Windows.Clipboard.ContainsText())
                    {
                        return;
                    }

                    string text = string.Empty;

                    try
                    {
                        // HTodo  :复制的文件路径
                        text = System.Windows.Clipboard.GetText();
                    }
                    catch
                    {
                    }


                    if (string.IsNullOrEmpty(text))
                    {
                        return;
                    }

                    if (this.Collection.Count > 0)
                    {
                        NotePadItemNotifyClass last = this.Collection.First();

                        if (last.Content != text)
                        {
                            NotePadItemNotifyClass f = new NotePadItemNotifyClass();
                            f.Content = text;
                            f.Date    = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                            this.Collection.Insert(0, f);
                        }
                    }
                    else
                    {
                        NotePadItemNotifyClass f = new NotePadItemNotifyClass();
                        f.Content = text;
                        f.Date    = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        this.Collection.Insert(0, f);
                    }
                };

                this.Load();

                //  ToDo:定时保存
                System.Timers.Timer time = new System.Timers.Timer();

                time.Interval = 10000;

                time.Elapsed += (l, k) =>
                {
                    this.Save();
                };
                time.Start();
            }

            else if (command == "ButtonCommand_Save")
            {
                this.Save();
            }
        }
        private void LaunchTimer()
        {
            var repeatAfter      = databaseMethods.GetRepeatAfter();
            var now              = DateTime.UtcNow;
            var time             = repeatAfter.TimeOfDay;
            var date             = repeatAfter.Date.ToString().Split(' ')[0];//.Substring(0, 10);
            var repeat_after     = date + " " + time;
            var repeat_after_new = Convert.ToDateTime(repeat_after /*, CultureInfo.InvariantCulture*/);
            var res_time         = repeat_after_new - now;

            seconds = res_time.Seconds;
            minutes = res_time.Minutes;
            //hours = res_time.Hours;
            days  = res_time.Days;
            hours = days * 24 + res_time.Hours;

            timer          = new System.Timers.Timer();
            timer.Interval = 1000;

            timer.Elapsed += delegate
            {
                var diff  = DateTime.Compare(repeat_after_new, DateTime.UtcNow);
                var diff1 = DateTime.Compare(DateTime.UtcNow, repeat_after_new);
                if (diff1 == -1 || diff == 0)
                {
                    InvokeOnMainThread(() =>
                    {
                        //resendBn.Enabled = true;
                        //resendBn.SetTitleColor(UIColor.FromRGB(255, 99, 62), UIControlState.Normal);
                    });
                }
                seconds--;
                if (seconds == 0 && minutes >= 0)
                {
                    minutes--;
                    seconds = 60;
                }
                if (minutes == 60)
                {
                    InvokeOnMainThread(() => { timer_valueLabel.Text = $"{hours}:00:00"; });
                }
                //this construction used here to display timer value correctly
                if (seconds == 60)
                {
                    if (minutes < 10)
                    {
                        InvokeOnMainThread(() => { timer_valueLabel.Text = $"{hours}:0{minutes}:00"; });
                    }
                    else
                    {
                        InvokeOnMainThread(() => { timer_valueLabel.Text = $"{hours}:{minutes}:00"; });
                    }
                }
                else if (seconds < 10)
                {
                    if (minutes < 10)
                    {
                        InvokeOnMainThread(() => { timer_valueLabel.Text = $"{hours}:0{minutes}:0{seconds}"; });
                    }
                    else
                    {
                        InvokeOnMainThread(() => { timer_valueLabel.Text = $"{hours}:{minutes}:0{seconds}"; });
                    }
                }
                else
                {
                    if (minutes < 10)
                    {
                        InvokeOnMainThread(() => { timer_valueLabel.Text = $"{hours}:0{minutes}:{seconds}"; });
                    }
                    else
                    {
                        InvokeOnMainThread(() => { timer_valueLabel.Text = $"{hours}:{minutes}:{seconds}"; });
                    }
                }
                if (minutes == 0 && seconds == 1)
                {
                    hours--;
                    seconds = 60;
                    minutes = 60;
                    if (hours < 0)
                    {
                        timer.Stop();
                        InvokeOnMainThread(() =>
                        {
                            Thread.Sleep(1000);
                            timer_valueLabel.Text = "00:00";
                            resendBn.Enabled      = true;
                            resendBn.SetTitleColor(UIColor.FromRGB(255, 99, 62), UIControlState.Normal);
                        });
                    }
                }
            };
            InvokeInBackground(() => timer.Start());
        }
Exemplo n.º 43
0
        protected void Application_Start(Object sender, EventArgs e)
        {
            //记录application 开始时间 by simon
            SetLog4Net();
            LogHelper.WriteLog("系统开始运行");
            IAppConfigSetter setter = new AppConfigSetter();

            ApplicationConfiguration.SetAppConfiguration(setter);
            ClassBuilderManager.LoadClassBuilderDefine();

            ApplicationConfigSetup acs = new ApplicationConfigSetup();

            acs.LoadLogPath();
            acs.Dispose();


            BLL.WorkFlowSystemCode wfs = new RmsPM.BLL.WorkFlowSystemCode();
            Rms.WorkFlow.InterfaceManager.iSystemCode = wfs;

            BLL.WorkFlowDefine wfd = new RmsPM.BLL.WorkFlowDefine();
            Rms.WorkFlow.InterfaceManager.iDefinition = wfd;

            BLL.WorkFlowCaseIO wfci = new BLL.WorkFlowCaseIO();
            Rms.WorkFlow.InterfaceManager.iWorkCase = wfci;

            RmsPM.DAL.QueryStrategy.SystemClassDescription.LoadItem();

            string vPath = Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings["VirtualDirectory"]);

            Application["VirtualMapPath"] = vPath;

            AvailableFunction.LoadAvailableFunction();

            /********************** 在线用户统计 ***************************/
            Hashtable UserTable = new Hashtable();

            Application.Lock();
            Application["UserTable"] = UserTable;
            Application.UnLock();
            /***************************************************************/

            //单一用户登录
            Application["SingleUserLogin"] = BLL.ConvertRule.ToString(System.Configuration.ConfigurationManager.AppSettings["SingleUserLogin"]);

            //被弹出的用户列表
            Hashtable KilledUserTable = new Hashtable();

            Application.Lock();
            Application["KilledUserTable"] = KilledUserTable;
            Application.UnLock();

            //登录超时时间
            Application["LoginTimeOut"] = BLL.ConvertRule.ToDecimal(System.Configuration.ConfigurationSettings.AppSettings["LoginTimeOut"]);

            //是否使用新的合同结构(合同明细、合同计划分开)
            Application["IsContractNew"] = "1";            //System.Configuration.ConfigurationSettings.AppSettings["IsContractNew"];

            //营销系统接口
            Application["SalServiceUrl"] = BLL.ConvertRule.ToString(System.Configuration.ConfigurationSettings.AppSettings["SalServiceUrl"]);

            /********************** 定时器启动 ***************************/
            if (System.Configuration.ConfigurationSettings.AppSettings["SendMailTime"] != null)
            {
                //创建一个新的Timer实例
                if (sysTimer == null)
                {
                    sysTimer = new System.Timers.Timer();
                }
                //将sysTimer_Elapsed指定为计时器的 Elapsed 事件处理程序
                sysTimer.Elapsed  += new System.Timers.ElapsedEventHandler(sysTimer_Elapsed);
                sysTimer.Interval  = nInterMin * 60 * 1000;
                sysTimer.AutoReset = true;
                sysTimer.Enabled   = true;
                //ApplicationLog.WriteLog("SendMailTime", "定时器已经启动,邮件发送时间为" + System.Configuration.ConfigurationSettings.AppSettings["SendMailTime"].ToString());
            }
            /***************************************************************/
            Application["GridPageSize"] = 14;

            InitContractActorOperationList();
        }
Exemplo n.º 44
0
        private void OnTouch(object sender, View.TouchEventArgs args)
        {
            if (!isEnabled)
            {
                return;
            }

            //var x = args.Event.GetX();
            //var y = args.Event.GetY();
            //Console.Out.WriteLine($"x: {x}; y: {y} (action: {args.Event.Action.ToString()})");
            motion = args.Event;

            if (args.Event.Action == MotionEventActions.Down)
            {
                View.PlaySoundEffect(SoundEffects.Click);
                // DOWN
                if (EnableRipple)
                {
                    ForceStartRipple(args.Event.GetX(), args.Event.GetY());
                }
                else
                {
                    StartAnimation();
                }

                if (Touch.GetLongTap(Element) != null)
                {
                    if (timer == null)
                    {
                        timer          = new System.Timers.Timer();
                        timer.Elapsed += OnTimerEvent;
                    }
                    timer.Interval  = Touch.GetLongTapLatency(Element);
                    timer.AutoReset = false;
                    timer.Start();
                }
            }
            else
            if (args.Event.Action == MotionEventActions.Up ||
                args.Event.Action == MotionEventActions.Cancel ||
                args.Event.Action == MotionEventActions.Outside)
            {
                args.Handled = true;
                // UP
                if (IsDisposed)
                {
                    return;
                }

                if (EnableRipple)
                {
                    ForceEndRipple();
                }
                else
                {
                    TapAnimation(250, alpha, 0);
                }

                if (args.Event.Action == MotionEventActions.Up &&
                    IsViewInBounds((int)args.Event.RawX, (int)args.Event.RawY))
                {
                    if (Touch.GetLongTap(Element) != null)
                    {
                        if (timer == null)
                        {
                            timer          = new System.Timers.Timer();
                            timer.Elapsed += OnTimerEvent;
                        }

                        if (timer.Enabled)
                        {
                            SelectHandler();
                            ClickHandler();
                        }
                    }
                    else
                    {
                        SelectHandler();
                        ClickHandler();
                    }
                }

                timer?.Stop();
            }
        }
Exemplo n.º 45
0
 public void Dispose()
 {
     _timer?.Stop();
     _timer?.Dispose();
     _timer = null;
 }
Exemplo n.º 46
0
 public void Delete()
 {
     timer1.Stop();
     timer1 = null;
 }
Exemplo n.º 47
0
        private static void DebugStuff()
        {
            var i = 0;

            while (i < 50)
            {
                ChatWindowManager.Instance.AddTccMessage($"Test {i++}");
            }

            //var broken =
            //    "00000f00790a0100000000000000000000000000000000000000790a810a00000000810a890a00000000890a910a00000000910a990a00000000990aa10a00000000a10aa90a00000000a90ab10a00000000b10ab90a00000000b90ac10a00000000c10ac90a00000000c90ad10a00000000d10ad90a00000000d90ae10a00000000e10ae90a00000000e90a000000000000f10aba0c0200920b900b414501004a4f7b1000000000e92f0000000000006b0000000000000001000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffff4c5a0100000000000000000000000000920b260c0f00ae0b0000000000000000000000000000000000000000ae0bb60b00000000b60bbe0b00000000be0bc60b00000000c60bce0b00000000ce0bd60b00000000d60bde0b00000000de0be60b00000000e60bee0b00000000ee0bf60b00000000f60bfe0b00000000fe0b060c00000000060c0e0c000000000e0c160c00000000160c1e0c000000001e0c000000000000260c00000f00420c0100000000000000000000000000000000000000420c4a0c000000004a0c520c00000000520c5a0c000000005a0c620c00000000620c6a0c000000006a0c720c00000000720c7a0c000000007a0c820c00000000820c8a0c000000008a0c920c00000000920c9a0c000000009a0ca20c00000000a20caa0c00000000aa0cb20c00000000b20c000000000000ba0c830e02005b0d590d424501004b4f7b1000000000e92f0000000000006c0000000000000001000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffff4c5a01000000000000000000000000005b0def0d0f00770d0000000000000000000000000000000000000000770d7f0d000000007f0d870d00000000870d8f0d000000008f0d970d00000000970d9f0d000000009f0da70d00000000a70daf0d00000000af0db70d00000000b70dbf0d00000000bf0dc70d00000000c70dcf0d00000000cf0dd70d00000000d70ddf0d00000000df0de70d00000000e70d000000000000ef0d00000f000b0e01000000000000000000000000000000000000000b0e130e00000000130e1b0e000000001b0e230e00000000230e2b0e000000002b0e330e00000000330e3b0e000000003b0e430e00000000430e4b0e000000004b0e530e00000000530e5b0e000000005b0e630e00000000630e6b0e000000006b0e730e00000000730e7b0e000000007b0e000000000000830e4c100200240f220f5b4501004c4f7b1000000000e92f0000000000006d0000000000000001000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffff4c5a0100000000000000000000000000240fb80f0f00400f0000000000000000000000000000000000000000400f480f00000000480f500f00000000500f580f00000000580f600f00000000600f680f00000000680f700f00000000700f780f00000000780f800f00000000800f880f00000000880f900f00000000900f980f00000000980fa00f00000000a00fa80f00000000a80fb00f00000000b00f000000000000b80f00000f00d40f0100000000000000000000000000000000000000d40fdc0f00000000dc0fe40f00000000e40fec0f00000000ec0ff40f00000000f40ffc0f00000000fc0f04100000000004100c10000000000c1014100000000014101c10000000001c1024100000000024102c10000000002c1034100000000034103c10000000003c1044100000000044100000000000004c1015120200ed10eb10104501004d4f7b1000000000e92f0000000000006a0000000000000001000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffff4c5a0100000000000000000000000000ed1081110f0009110000000000000000000000000000000000000000091111110000000011111911000000001911211100000000211129110000000029113111000000003111391100000000391141110000000041114911000000004911511100000000511159110000000059116111000000006111691100000000691171110000000071117911000000007911000000000000811100000f009d1101000000000000000000000000000000000000009d11a51100000000a511ad1100000000ad11b51100000000b511bd1100000000bd11c51100000000c511cd1100000000cd11d51100000000d511dd1100000000dd11e51100000000e511ed1100000000ed11f51100000000f511fd1100000000fd1105120000000005120d12000000000d120000000000001512de130200b612b412920500004e4f7b1000000000e92f0000000000005e0000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffff00000000000000000000000000000000b6124a130f00d2120000000000000000000000000000000000000000d212da1200000000da12e21200000000e212ea1200000000ea12f21200000000f212fa1200000000fa1202130000000002130a13000000000a1312130000000012131a13000000001a1322130000000022132a13000000002a1332130000000032133a13000000003a1342130000000042130000000000004a1300000f006613010000000000000000000000000000000000000066136e13000000006e1376130000000076137e13000000007e1386130000000086138e13000000008e1396130000000096139e13000000009e13a61300000000a613ae1300000000ae13b61300000000b613be1300000000be13c61300000000c613ce1300000000ce13d61300000000d613000000000000de13a71502007f147d149cd902005d6a7f1000000000e92f0000000000003e0000000000000009000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffff000000000000000000000000000000007f1413150f009b1400000000000000000000000000000000000000009b14a31400000000a314ab1400000000ab14b31400000000b314bb140000000000";
            //var msg = new Message(DateTime.Now, MessageDirection.ServerToClient,
            //    new ArraySegment<byte>(StringUtils.StringToByteArray(broken)));
            //var fac = new MessageFactory();
            //var del = MessageFactory.Contructor<Func<TeraMessageReader, S_INVEN>>();
            //var reader = new TeraMessageReader(msg, null, fac, null);
            //del.DynamicInvoke(reader);



            //new DebugWindow().Show();
            //SessionManager.Logged = true;
            //SessionManager.LoadingScreen = false;
            //SessionManager.CurrentPlayer.Class = Class.Warrior;
            //ClassWindowViewModel.Instance.CurrentClass = SessionManager.CurrentPlayer.Class;

            //SessionManager.Combat = true;
            //SessionManager.Encounter = true;
            //(ClassWindowViewModel.Instance.CurrentManager as WarriorBarManager).DeadlyGamble.Cooldown.Start(2000);
            System.Timers.Timer _t = new System.Timers.Timer {
                Interval = 1000
            };
            var r = new Random();

            _t.Elapsed += (_, __) =>
            {
                ChatWindowManager.Instance.AddTccMessage("Random message #" + r.Next(200));
                //SessionManager.SetPlayerSt(10, SessionManager.CurrentPlayer.CurrentST + 100 > SessionManager.CurrentPlayer.MaxST ?
                //    0 : SessionManager.CurrentPlayer.CurrentST + 100);
            };
            //ClassWindowViewModel.Instance.CurrentClass = SessionManager.CurrentPlayer.Class;
            //CooldownWindowViewModel.Instance.LoadSkills(Utils.ClassEnumToString(SessionManager.CurrentPlayer.Class).ToLower() + "-skills.xml", SessionManager.CurrentPlayer.Class);
            ////SessionManager.SetSorcererElements(true, true, true);
            //SessionManager.SetPlayerMaxSt(10, 1000);
            //SessionManager.SetPlayerSt(10, 1000);

            _t.Start();
            //var i = 0;
            //while (i < 20000)
            //{
            //    ChatWindowManager.Instance.AddTccMessage($"Test {i++}");
            //}
            //GC.Collect();
            //GC.WaitForPendingFinalizers();
            //GroupWindowViewModel.Instance.AddOrUpdateMember(new User(BaseDispatcher)
            //{
            //    Alive = true,
            //    Awakened = true,
            //    CurrentHp = 1000,
            //    MaxHp = 1000,
            //    EntityId = 1,
            //    ServerId = 1,
            //    PlayerId = 1,
            //    UserClass = Class.Archer,
            //    Online = true
            //});
            //bool up = true;
            //bool inv = false;
            //ulong i = 0;
            //while (true)
            //{
            //    if (i > 1000)
            //    {
            //        up = false;
            //        if(!inv) Thread.Sleep(10000);
            //        inv = true;
            //    }

            //    if (up)
            //    {

            //        Console.WriteLine($"[{i}] Spawning NPCs");
            //        EntityManager.SpawnNPC(15, 1, i, Visibility.Visible);
            //        i++;
            //    }
            //    else
            //    {
            //        Console.WriteLine($"[{i}] Despawning NPCs");
            //        EntityManager.DespawnNPC(i, DespawnType.OutOfView);
            //        i--;
            //    }
            //    Thread.Sleep(2);
            //    if (i == 0) {break;}
            //}
            //EntityManager.SpawnNPC(920, 3000, 11, Visibility.Visible);
            //EntityManager.UpdateNPC(12, 1000, 1000);
            //AbnormalityManager.BeginOrRefreshPartyMemberAbnormality(1, 1, 1495, 200000, 1);
            //AbnormalityManager.BeginAbnormality(1495, 10, 200000, 1);
            //AbnormalityManager.BeginAbnormality(1495, 11, 200000, 1);
            //AbnormalityManager.BeginAbnormality(1495, 12, 200000, 1);

            //for (int i = 0; i < 2000; i++)
            //{
            //    ChatWindowManager.Instance.AddTccMessage($"Test {i}");
            //}

            /*
             *          EntityManager.SpawnNPC(210, 1108, 11, Visibility.Visible);
             *          var c = 0;
             *          while (c < 1000)
             *          {
             *              AbnormalityManager.BeginAbnormality(2, 10, 500, 1);
             *              AbnormalityManager.BeginAbnormality(2, 11, 500, 1);
             *              Console.WriteLine("Added " + c);
             *              Thread.Sleep(100);
             *              AbnormalityManager.EndAbnormality(2, 10);
             *              AbnormalityManager.EndAbnormality(2, 11);
             *              Console.WriteLine("Removed " + c);
             *              c++;
             *          }
             */
            //AbnormalityManager.BeginAbnormality(1495, 10, 10000, 5);
            //AbnormalityManager.BeginAbnormality(2066, 10, 100000, 10);
            //AbnormalityManager.BeginAbnormality(2074, 10, 10000000, 20);
            //var r = new Random();
            //for (int i = 0; i < 30; i++)
            //{
            //    WindowManager.CivilUnrestWindow.VM.AddGuild(new CityWarGuildInfo(1, (uint)i, 0, 0, (float)r.Next(0, 100) / 100));
            //    WindowManager.CivilUnrestWindow.VM.SetGuildName((uint)i, "Guild " + i);
            //    WindowManager.CivilUnrestWindow.VM.AddDestroyedGuildTower((uint)r.Next(0, 29));

            //}

            //ClassWindowViewModel.Instance.CurrentClass = Class.Priest;
            //EntityManager.SpawnNPC(920, 3000, 10, Visibility.Visible);
            //Task.Delay(2000).ContinueWith(t => BossGageWindowViewModel.Instance.AddOrUpdateBoss(10,5250000000,3240000000,true, HpChangeSource.BossGage));
            //Task.Delay(4000).ContinueWith(t => BossGageWindowViewModel.Instance.AddOrUpdateBoss(10,5250000000,2240000000,true, HpChangeSource.BossGage));
            //EntityManager.SpawnNPC(950,3000,10,Visibility.Visible);
            //EntityManager.SpawnNPC(970,1000,11,Visibility.Visible);
            //EntityManager.SpawnNPC(970,2000,12,Visibility.Visible);
            //EntityManager.SpawnNPC(970,3000,13,Visibility.Visible);
            //EntityManager.SetNPCStatus(10, true);

            //Task.Delay(1000).ContinueWith(t => (ClassWindowViewModel.Instance.CurrentManager as WarriorBarManager).DeadlyGamble.Buff.Start(10000));
            //WindowManager.LfgListWindow.ShowWindow();
            // var l = new Listing();
            // l.LeaderId = 10;
            // l.Message = "SJG exp only";
            // l.LeaderName = "Foglio";
            // l.Players.Add(new User(WindowManager.LfgListWindow.Dispatcher){PlayerId = 10, IsLeader = true, Online = true});
            // l.Applicants.Add(new User(WindowManager.LfgListWindow.Dispatcher){PlayerId = 1, Name = "Applicant", Online = true, UserClass = Class.Priest});
            // WindowManager.LfgListWindow.VM.Listings.Add(l);

            //var l = new List<User>();
            //var r = new Random();
            //for (uint i = 0; i <= 10; i++)
            //{
            //    var u = new User(GroupWindowViewModel.Instance.GetDispatcher())
            //    {
            //        Name = i.ToString(),
            //        PlayerId = i,
            //        ServerId = i,
            //        EntityId = i,
            //        Online = true,
            //        Laurel = (Laurel)(r.Next(0, 6)),
            //        HasAggro = i == 1,
            //        Alive = true, //i != 0,
            //        UserClass = (Class)r.Next(0, 12),
            //        Awakened = i < 5,
            //    };
            //    GroupWindowViewModel.Instance.AddOrUpdateMember(u);
            //}

            ////GroupWindowViewModel.Instance.SetRaid(true);
            //GroupWindowViewModel.Instance.SetNewLeader(1, "1");
        }
Exemplo n.º 48
0
        //outputs in this context means the outcome of the instance
        //attribute is the thing leading to the outcoome

        //double[][] oddsAttributesGivenOutputs = new double[numberOfOutputs][numberOfAttribute];

        static public void getOddsOfAttributeGivenGenre(List <Data.BookData> bookList, Dictionary <string, WordOddsBayes> odds, bool usingVariance)
        {
            int tenthsOfASecond = 0;

            System.Timers.Timer t = new System.Timers.Timer(100);
            t.Elapsed += (arg1, arg2) => { tenthsOfASecond++; };
            t.Start();
            var booksByGenre      = new Dictionary <string, List <Data.BookData> >();
            var wordCountsByGenre = new Dictionary <string, Dictionary <string, int> >();

            foreach (var book in bookList)
            {
                if (!booksByGenre.ContainsKey(book.Genre))
                {
                    booksByGenre.Add(book.Genre, new List <Data.BookData>());
                    wordCountsByGenre.Add(book.Genre, new Dictionary <string, int>());
                }

                booksByGenre[book.Genre].Add(book);

                var wordCountTotals = wordCountsByGenre[book.Genre];
                foreach (var wordCount in book.WordCounts)
                {
                    odds[book.Genre].addToMean(wordCount.Key, wordCount.Value);
                    if (!wordCountTotals.ContainsKey(wordCount.Key))
                    {
                        wordCountTotals.Add(wordCount.Key, 0);
                    }
                    wordCountTotals[wordCount.Key] += wordCount.Value;
                }
            }



            foreach (var Genre in wordCountsByGenre)
            {
                foreach (var word in Genre.Value)
                {
                    foreach (var book in booksByGenre[Genre.Key])
                    {
                        if (book.WordCounts.ContainsKey(word.Key))
                        {
                            //add the word counts for that word in that book
                            odds[book.Genre].addToVariance(word.Key, book.WordCounts[word.Key]);
                        }
                        else
                        {
                            //if it's not found there's a book with zero instances of that word
                            odds[book.Genre].addToVariance(word.Key, 0);
                        }
                    }
                    //incidentally ths will also set standard deviation at this point we can simply use the z score function in the wordOddsBayes to find the odds of a specific incident being in  genre
                    odds[Genre.Key].getFinalVariance(word.Key);
                }
            }



            /*
             * int counter = 0;
             * System.Collections.IList books = bookList;
             * foreach (Data.BookData book in books)
             * {
             *  foreach (KeyValuePair<string, int> instance in book.WordCounts)
             *  {
             *      //we now have the word to run the rest by
             *      string word = instance.Key;
             *      //if we've already run the odds on this particular word we can ignore it
             *      bool seenThisBefore = false;
             *      //we're going to go through each genre and see if the odds have been set if not we run it
             *      foreach (KeyValuePair<string, WordOddsBayes> genre in odds)
             *      {
             *
             *          if (genre.Value.containsKey(word))
             *          {
             *              seenThisBefore = true;
             *          }
             *      }
             *
             *      //if we haven't seen this before
             *      if (!seenThisBefore)
             *      {
             *
             *
             *          if (usingVariance == true)
             *          {
             *              //this second one gets the variance
             *              foreach (Data.BookData bookSecondLevel in books)
             *              {
             *                  if (bookSecondLevel.WordCounts.ContainsKey(word))
             *                  {
             *                      bool getByPercent = false;
             *                      int TotalWordCount = 1;
             *                      //a simple fix ensures we can get the percent or absolute value easily
             *                      if (getByPercent)
             *                      {
             *                          TotalWordCount = book.TotalWordCount;
             *                      }
             *                      //add the word counts for that word in that book
             *                      odds[bookSecondLevel.Genre].addToVariance(word, bookSecondLevel.WordCounts[word] / TotalWordCount);
             *                  }
             *                  else
             *                  {
             *                      //if it's not found there's a book with zero instances of that word
             *                      odds[bookSecondLevel.Genre].addToVariance(word, 0);
             *                  }
             *
             *              }
             *              foreach (KeyValuePair<string, WordOddsBayes> odd in odds)
             *              {
             *                  //incidentally ths will also set standard deviation at this point we can simply use the z score function in the wordOddsBayes to find the odds of a specific incident being in  genre
             *                  odd.Value.getFinalVariance(word);
             *              }
             *          }
             *
             *      }
             *
             *  }
             *
             *  Console.WriteLine("book no." + counter);
             *  counter++;
             * }
             */
            t.Stop();
            Console.WriteLine("Number of seconds: " + tenthsOfASecond / 10);
        }
Exemplo n.º 49
0
        /// <summary>
        /// RenderableObject abstract member (needed)
        /// OBS: Worker thread (don't update UI directly from this thread)
        /// </summary>
        public override void Initialize(DrawArgs drawArgs)
        {
            if (!IsVisible(drawArgs.WorldCamera))
            {
                return;
            }
            if (meshFileName.StartsWith("http"))
            {
                Uri    meshuri   = new Uri(meshFileName);
                string meshpath  = meshuri.AbsolutePath;
                string extension = Path.GetExtension(meshpath);
                //download online mesh files to cache and
                //update meshfilename to new name
                if (meshuri.Scheme == Uri.UriSchemeHttp ||
                    meshuri.Scheme == Uri.UriSchemeHttps)
                {
                    try
                    {
                        // Offline check
                        if (World.Settings.WorkOffline)
                        {
                            throw new Exception("Offline mode active.");
                        }

                        WebDownload request = new WebDownload(meshFileName);

                        string cachefilename = request.GetHashCode() + extension;
                        //HACK: Hard Coded Path
                        cachefilename =
                            Directory.GetParent(System.Windows.Forms.Application.ExecutablePath) +
                            "//Cache//Models//" + cachefilename;
                        if (!File.Exists(cachefilename))
                        {
                            request.DownloadFile(cachefilename);
                        }
                        meshFileName = cachefilename;
                    }
                    catch (Exception caught)
                    {
                        Utility.Log.Write(caught);
                        errorMsg = "Failed to download mesh from " + meshFileName;
                    }
                }
            }
            string ext = Path.GetExtension(meshFileName);

            try
            {
                lock (m_thisLock)
                {
                    if (m_meshTable.ContainsKey(meshFileName))
                    {
                        m_meshTableElem = m_meshTable[meshFileName];
                        m_meshTableElem.referenceCount++;
                        m_meshElems = m_meshTableElem.meshElems;
                    }
                    else
                    {
                        if (ext.Equals(".x"))
                        {
                            LoadDirectXMesh(drawArgs);
                        }
                        else if (ext.Equals(".dae") || ext.Equals(".xml"))
                        {
                            LoadColladaMesh(drawArgs);
                        }

                        // if mesh loaded then add to the mesh table
                        if (m_meshElems != null)
                        {
                            m_meshTableElem = new MeshTableElem();
                            m_meshTableElem.meshFilePath   = meshFileName;
                            m_meshTableElem.meshElems      = m_meshElems;
                            m_meshTableElem.referenceCount = 1;

                            m_meshTable.Add(meshFileName, m_meshTableElem);
                        }
                    }
                }

                if (m_meshElems == null)
                {
                    throw new InvalidMeshException();
                }

                //vertExaggeration = World.Settings.VerticalExaggeration;
                //if (m_isElevationRelativeToGround == true)
                //    currentElevation = World.TerrainAccessor.GetElevationAt(Latitude, Longitude);

                if (refreshTimer == null && m_refreshurl != null)
                {
                    refreshTimer          = new System.Timers.Timer(60000);
                    refreshTimer.Elapsed += new System.Timers.ElapsedEventHandler(refreshTimer_Elapsed);
                    refreshTimer.Start();
                }

                isInitialized = true;
            }
            catch (Exception caught)
            {
                Utility.Log.Write(caught);
                errorMsg = "Failed to read mesh from " + meshFileName;
            }
        }
        /// <summary>
        ///     Start checking for new version of application and display a dialog to the user if update is available.
        /// </summary>
        /// <param name="appCast">URL of the xml file that contains information about latest version of the application.</param>
        /// <param name="myAssembly">Assembly to use for version checking.</param>
        public static void Start(string appCast, Assembly myAssembly = null)
        {
            try
            {
                ServicePointManager.SecurityProtocol |= (SecurityProtocolType)192 |
                                                        (SecurityProtocolType)768 | (SecurityProtocolType)3072;
            }
            catch (NotSupportedException)
            {
            }

            if (Mandatory && _remindLaterTimer != null)
            {
                _remindLaterTimer.Stop();
                _remindLaterTimer.Close();
                _remindLaterTimer = null;
            }

            if (!Running && _remindLaterTimer == null)
            {
                Running = true;

                AppCastURL = appCast;

                IsWinFormsApplication = Application.MessageLoop;

                if (!IsWinFormsApplication)
                {
                    Application.EnableVisualStyles();
                }

                Assembly assembly = myAssembly ?? Assembly.GetEntryAssembly();

                if (Synchronous)
                {
                    try
                    {
                        var result = CheckUpdate(assembly);

                        Running = StartUpdate(result);
                    }
                    catch (Exception exception)
                    {
                        ShowError(exception);
                    }
                }
                else
                {
                    using (var backgroundWorker = new BackgroundWorker())
                    {
                        backgroundWorker.DoWork += (sender, args) =>
                        {
                            Assembly mainAssembly = args.Argument as Assembly;

                            args.Result = CheckUpdate(mainAssembly);
                        };

                        backgroundWorker.RunWorkerCompleted += (sender, args) =>
                        {
                            if (args.Error != null)
                            {
                                ShowError(args.Error);
                            }
                            else
                            {
                                if (!args.Cancelled)
                                {
                                    if (StartUpdate(args.Result))
                                    {
                                        return;
                                    }
                                }
                            }

                            Running = false;
                        };

                        backgroundWorker.RunWorkerAsync(assembly);
                    }
                }
            }
        }
        public void DataPartnerPayloadFromAnalysisCenter()
        {
            //the analysis center provides multiple documents that are distributed to each data partner, the files are extracted into the "inputfiles" folder of the data partner
            //the SAS app will drop an output files manifest and documents into the "msoc" folder, the files listed in the manifest file will be uploaded when the trigger file exists

            _adapter.Initialize(CreateSettings(MonitorFolderDataPartner));

            string outputFolder = Path.Combine(MonitorFolderDataPartner, "msoc");
            var    timer        = new System.Timers.Timer(TimeSpan.FromSeconds(5).TotalMilliseconds);

            timer.AutoReset = true;
            timer.Elapsed  += (object sender, System.Timers.ElapsedEventArgs e) =>
            {
                if (Directory.Exists(outputFolder))
                {
                    timer.Stop();

                    //create some output documents
                    string fname;
                    for (int i = 1; i <= 5; i++)
                    {
                        fname = Path.Combine(outputFolder, "output_file_" + i + ".txt");
                        using (var fs = File.CreateText(fname))
                        {
                            fs.WriteLine("Data partner document " + i + ".");
                            fs.Close();
                        }
                    }

                    //create a manifest csv listing the documents to upload
                    using (var fs = File.CreateText(Path.Combine(outputFolder, ManifestFilename)))
                    {
                        fs.WriteLine("file_nm,transfer_to_site_in");
                        fs.WriteLine("output_file_1.txt,1");
                        fs.WriteLine("output_file_2.txt,0");
                        fs.WriteLine("output_file_3.txt,1");
                        fs.WriteLine("output_file_4.txt,0");
                        fs.WriteLine("output_file_5.txt,1");
                        fs.Close();
                    }

                    //create the execution complete trigger file
                    using (var fs = File.Create(Path.Combine(outputFolder, ExecutionCompleteFilename)))
                    {
                        fs.Close();
                    }
                }
            };

            List <DocumentWithStream> datapartnerDocuments = new List <DocumentWithStream>();

            for (int i = 1; i <= 5; i++)
            {
                Guid documentID = Guid.NewGuid();
                datapartnerDocuments.Add(new DocumentWithStream(documentID, new Document(documentID.ToString("D"), "text/plain", "payload_document_" + i + ".txt"), new MemoryStream(System.Text.Encoding.UTF8.GetBytes("Hello!"))));
            }

            timer.Start();
            var responseDocuments = _adapter.StartRequest(datapartnerDocuments.ToArray());

            Console.WriteLine("done");

            //assert that only the documents listed in the file manifest got uploaded
        }
Exemplo n.º 52
0
        private void performEAll4Input()
        {
            firstActive = DateTime.UtcNow;
            System.Timers.Timer readTimeout = new System.Timers.Timer(); // Await 30 seconds for the initial packet, then 3 seconds thereafter.
            readTimeout.Elapsed += delegate { HidDevice.CancelIO(); };
            List <long> Latency = new List <long>();
            long        oldtime = 0;
            Stopwatch   sw      = new Stopwatch();

            sw.Start();
            while (true)
            {
                string currerror = string.Empty;
                Latency.Add(sw.ElapsedMilliseconds - oldtime);
                oldtime = sw.ElapsedMilliseconds;

                if (Latency.Count > 100)
                {
                    Latency.RemoveAt(0);
                }

                this.Latency = Latency.Average();

                if (this.Latency > 10 && !warn && sw.ElapsedMilliseconds > 4000)
                {
                    warn = true;
                    //System.Diagnostics.Trace.WriteLine(System.DateTime.UtcNow.ToString("o") + "> " + "Controller " + /*this.DeviceNum*/ + 1 + " (" + this.MacAddress + ") is experiencing latency issues. Currently at " + Math.Round(this.Latency, 2).ToString() + "ms of recomended maximum 10ms");
                }
                else if (this.Latency <= 10 && warn)
                {
                    warn = false;
                }

                if (readTimeout.Interval != 3000.0)
                {
                    if (readTimeout.Interval != 30000.0)
                    {
                        readTimeout.Interval = 30000.0;
                    }
                    else
                    {
                        readTimeout.Interval = 3000.0;
                    }
                }
                readTimeout.Enabled = true;
                if (conType != ConnectionType.USB)
                {
                    HidDevice.ReadStatus res = hDevice.ReadFile(btInputReport);
                    readTimeout.Enabled = false;
                    if (res == HidDevice.ReadStatus.Success)
                    {
                        _isAvaliable = true;
                        Array.Copy(btInputReport, 0, inputReport, 0, inputReport.Length);
                    }
                    else
                    {
                        _isAvaliable = false;
                        Console.WriteLine(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") + "> disconnect due to read failure: " + Marshal.GetLastWin32Error());
                        Log.LogToTray(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") +
                                      "> disconnect due to read failure(notUsb): " + Marshal.GetLastWin32Error());
                        Nlog.Debug(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") +
                                   "> disconnect due to read failure(notUsb): " + Marshal.GetLastWin32Error());
                        IsDisconnecting = true;
                        if (Removal != null)
                        {
                            Removal(this, EventArgs.Empty);
                        }

                        break;
                        return;
                    }



                    //else
                    //{
                    //    Console.WriteLine(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") + "> disconnect due to read failure: " + Marshal.GetLastWin32Error());
                    //    sendOutputReport(true); // Kick Windows into noticing the disconnection.
                    //    StopOutputUpdate();
                    //    IsDisconnecting = true;
                    //    if (Removal != null)
                    //        Removal(this, EventArgs.Empty);
                    //    return;

                    //}
                }
                else
                {
                    HidDevice.ReadStatus res = hDevice.ReadFile(inputReport);
                    readTimeout.Enabled = false;
                    if (res != HidDevice.ReadStatus.Success)
                    {
                        Console.WriteLine(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") + "> disconnect due to read failure: " + Marshal.GetLastWin32Error());
                        Log.LogToTray(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") +
                                      "> disconnect due to read failure(USB): " + Marshal.GetLastWin32Error());

                        Nlog.Debug(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") +
                                   "> disconnect due to read failure(USB): " + Marshal.GetLastWin32Error());
                        StopOutputUpdate();
                        IsDisconnecting = true;
                        if (Removal != null)
                        {
                            Removal(this, EventArgs.Empty);
                        }
                        return;
                    }
                }
                //if (ConnectionType == ConnectionType.BT && btInputReport[0] != 0x11)
                //{
                //    //Received incorrect report, skip it
                //    continue;
                //}
                DateTime utcNow = System.DateTime.UtcNow; // timestamp with UTC in case system time zone changes
                //resetHapticState();
                cState.ReportTimeStamp = utcNow;
                cState.LX = inputReport[4]; // left joystick x-axis//左摇杆x轴
                cState.LY = inputReport[5]; // left joystick y-axis//左摇杆Y轴
                cState.RX = inputReport[6]; // right joystick x-axis//右摇杆x轴
                cState.RY = inputReport[7]; //right joystick y-axis//右摇杆y轴


                cState.LT = inputReport[8];
                cState.RT = inputReport[9];
                cState.LB = ((byte)inputReport[1] & Convert.ToByte(64)) != 0;
                cState.RB = ((byte)inputReport[1] & Convert.ToByte(128)) != 0;

                cState.A = ((byte)inputReport[1] & Convert.ToByte(1)) != 0;  // ok
                cState.B = ((byte)inputReport[1] & Convert.ToByte(2)) != 0;  //ok
                cState.X = ((byte)inputReport[1] & Convert.ToByte(8)) != 0;  //ok
                cState.Y = ((byte)inputReport[1] & Convert.ToByte(16)) != 0; //ok
                switch (inputReport[3])
                {
                case 0: cState.DpadUp = true; cState.DpadDown = false; cState.DpadLeft = false; cState.DpadRight = false; break;   //up

                case 1: cState.DpadUp = true; cState.DpadDown = false; cState.DpadLeft = false; cState.DpadRight = true; break;    //up right//fixed on 2016-12-28

                case 2: cState.DpadUp = false; cState.DpadDown = false; cState.DpadLeft = false; cState.DpadRight = true; break;   //right

                case 3: cState.DpadUp = false; cState.DpadDown = true; cState.DpadLeft = false; cState.DpadRight = true; break;    //down right

                case 4: cState.DpadUp = false; cState.DpadDown = true; cState.DpadLeft = false; cState.DpadRight = false; break;   //down

                case 5: cState.DpadUp = false; cState.DpadDown = true; cState.DpadLeft = true; cState.DpadRight = false; break;    //down left

                case 6: cState.DpadUp = false; cState.DpadDown = false; cState.DpadLeft = true; cState.DpadRight = false; break;   // left

                case 7: cState.DpadUp = true; cState.DpadDown = false; cState.DpadLeft = true; cState.DpadRight = false; break;    //up left

                default: cState.DpadUp = false; cState.DpadDown = false; cState.DpadLeft = false; cState.DpadRight = false; break;
                }

                cState.RS = ((byte)inputReport[2] & Convert.ToByte(64)) != 0;
                var leftStick = ((byte)inputReport[2] & Convert.ToByte(32)) != 0;
                cState.LS = leftStick;
                var menu = ((byte)inputReport[2] & Convert.ToByte(8)) != 0;
                var back = ((byte)inputReport[2] & Convert.ToByte(4)) != 0;
                cState.Start = menu;
                cState.Back  = back;


                cState.Guide = menu && leftStick;
                // XXX fix initialization ordering so the null checks all go away

                //battery level, the be-top protocal look like not contain battery data.. can not display battery level for now.
                //var batteryLevel = Convert.ToInt32(inputReport[18]) / 255;
                //battery = batteryLevel;

                //cState.Battery = 60;

                if (Report != null)
                {
                    Report(this, EventArgs.Empty);
                }
                //sendOutputReport(false);

                // the be-top bluetooth report protocal unknow fo now , the rumble function can not supported.
                //sendOutputReport(false);


                if (!string.IsNullOrEmpty(error))
                {
                    error = string.Empty;
                }
                if (!string.IsNullOrEmpty(currerror))
                {
                    error = currerror;
                }
                cState.CopyTo(pState);
            }
        }
Exemplo n.º 53
0
        public static void doOnlineCommands(int playerPluginId, string playerName, string playerId)
        {
            Tebex.logWarning("Running online commands for " + playerName + " (" + playerId + ")");

            TebexApiClient wc = new TebexApiClient();

            wc.setPlugin(Tebex.Instance);
            wc.Headers.Add("X-Buycraft-Secret", Tebex.Instance.Config.Secret);
            String url = Tebex.Instance.Config.BaseUrl + "queue/online-commands/" +
                         playerPluginId.ToString();

            Tebex.logWarning("GET " + url);

            wc.DownloadStringCompleted += (sender, e) =>
            {
                JObject json     = JObject.Parse(e.Result);
                JArray  commands = (JArray)json["commands"];

                int        exCount          = 0;
                List <int> executedCommands = new List <int>();

                foreach (var command in commands.Children())
                {
                    String commandToRun = buildCommand((string)command["command"], playerName, playerId);

                    Tebex.logWarning("Run command " + commandToRun);
                    if ((int)command["conditions"]["delay"] > 0)
                    {
                        // Create a timer with a two second interval.
                        var aTimer = new System.Timers.Timer((int)command["conditions"]["delay"] * 1000);
                        aTimer.Elapsed += (Object source, System.Timers.ElapsedEventArgs ev) =>
                        {
                            RunCommand(commandToRun);
                            ((Timer)source).Dispose();
                        };
                        aTimer.AutoReset = false;
                        aTimer.Enabled   = true;
                    }
                    else
                    {
                        RunCommand(commandToRun);
                    }
                    executedCommands.Add((int)command["id"]);

                    exCount++;

                    if (exCount % deleteAfter == 0)
                    {
                        try
                        {
                            deleteCommands(executedCommands);
                            executedCommands.Clear();
                        }
                        catch (Exception ex)
                        {
                            Tebex.logError(ex.ToString());
                        }
                    }
                }

                Tebex.logWarning(exCount.ToString() + " online commands executed for " + playerName);
                if (exCount % deleteAfter != 0)
                {
                    try
                    {
                        deleteCommands(executedCommands);
                        executedCommands.Clear();
                    }
                    catch (Exception ex)
                    {
                        Tebex.logError(ex.ToString());
                    }
                }

                wc.Dispose();
            };

            wc.DownloadStringAsync(new Uri(url));
        }
        public void AnalysisCenterWithNewPayloadFromDataPartners()
        {
            _adapter.Initialize(CreateSettings(MonitorFolderAnalysisCenter));


            //remove all the directories
            var directories = Directory.GetDirectories(MonitorFolderAnalysisCenter);

            foreach (var dir in directories)
            {
                Directory.Delete(dir, true);
            }

            //create the inputfiles folder
            string inputfilesFolderPath = Path.Combine(MonitorFolderAnalysisCenter, "inputfiles");

            if (!Directory.Exists(inputfilesFolderPath))
            {
                Directory.CreateDirectory(inputfilesFolderPath);
            }

            //payload will consist of input files from each data partner, need to be extracted to partner specific folders and then monitor the inputfiles folder

            List <DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem> manifestItems = new List <DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem>();
            List <DocumentWithStream> datapartnerDocuments = new List <DocumentWithStream>();

            for (int i = 1; i <= 5; i++)
            {
                Guid documentID = Guid.NewGuid();
                datapartnerDocuments.Add(new DocumentWithStream(documentID, new Document(documentID.ToString("D"), "text/plain", "payload_document.txt"), new MemoryStream(System.Text.Encoding.UTF8.GetBytes("Hello!"))));

                manifestItems.Add(new DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem {
                    DataMart              = "Data Partner " + i,
                    DataMartID            = Guid.NewGuid(),
                    DataPartnerIdentifier = "msoc" + i,
                    DocumentID            = documentID,
                    RequestDataMartID     = Guid.NewGuid(),
                    ResponseID            = Guid.NewGuid(),
                    RevisionSetID         = documentID
                });
            }

            //create the analysis center manifest
            MemoryStream manifestStream;

            using (var ms = new MemoryStream())
                using (var sr = new StreamWriter(ms))
                    using (var jr = new Newtonsoft.Json.JsonTextWriter(sr))
                    {
                        var serializer = new Newtonsoft.Json.JsonSerializer();
                        serializer.Serialize(jr, manifestItems);
                        jr.Flush();

                        manifestStream = new MemoryStream(ms.ToArray());
                    }


            Guid manifestID = Guid.NewGuid();

            datapartnerDocuments.Add(new DocumentWithStream(manifestID, new Document(manifestID, "application/json", "manifest.json", false, Convert.ToInt32(manifestStream.Length), Lpp.Dns.DTO.Enums.DocumentKind.SystemGeneratedNoLog), manifestStream));

            var timer = new System.Timers.Timer(TimeSpan.FromSeconds(1).TotalMilliseconds);

            timer.AutoReset = true;
            timer.Elapsed  += (object sender, System.Timers.ElapsedEventArgs e) =>
            {
                if (Directory.Exists(Path.Combine(MonitorFolderAnalysisCenter, "inputfiles")))
                {
                    timer.Stop();

                    using (var fs = File.Create(Path.Combine(MonitorFolderAnalysisCenter, "inputfiles", ExecutionCompleteFilename)))
                    {
                        fs.Close();
                    }
                }
            };
            timer.Start();

            var responseDocuments = _adapter.StartRequest(datapartnerDocuments.ToArray());

            for (int i = 1; i <= 5; i++)
            {
                Assert.IsTrue(Directory.Exists(Path.Combine(MonitorFolderAnalysisCenter, "msoc" + i)));
            }
        }
Exemplo n.º 55
0
        /// <summary>
        /// Collects a diagnostic trace from a currently running process.
        /// </summary>
        /// <param name="ct">The cancellation token</param>
        /// <param name="console"></param>
        /// <param name="processId">The process to collect the trace from.</param>
        /// <param name="name">The name of process to collect the trace from.</param>
        /// <param name="output">The output path for the collected trace data.</param>
        /// <param name="buffersize">Sets the size of the in-memory circular buffer in megabytes.</param>
        /// <param name="providers">A list of EventPipe providers to be enabled. This is in the form 'Provider[,Provider]', where Provider is in the form: 'KnownProviderName[:Flags[:Level][:KeyValueArgs]]', and KeyValueArgs is in the form: '[key1=value1][;key2=value2]'</param>
        /// <param name="profile">A named pre-defined set of provider configurations that allows common tracing scenarios to be specified succinctly.</param>
        /// <param name="format">The desired format of the created trace file.</param>
        /// <param name="duration">The duration of trace to be taken. </param>
        /// <param name="clrevents">A list of CLR events to be emitted.</param>
        /// <param name="clreventlevel">The verbosity level of CLR events</param>
        /// <returns></returns>
        private static async Task <int> Collect(CancellationToken ct, IConsole console, int processId, FileInfo output, uint buffersize, string providers, string profile, TraceFileFormat format, TimeSpan duration, string clrevents, string clreventlevel, string name)
        {
            try
            {
                Debug.Assert(output != null);
                Debug.Assert(profile != null);

                // Either processName or processId has to be specified.
                if (name != null)
                {
                    if (processId != 0)
                    {
                        Console.WriteLine("Can only specify either --name or --process-id option.");
                        return(ErrorCodes.ArgumentError);
                    }
                    processId = CommandUtils.FindProcessIdWithName(name);
                    if (processId < 0)
                    {
                        return(ErrorCodes.ArgumentError);
                    }
                }

                if (processId < 0)
                {
                    Console.Error.WriteLine("Process ID should not be negative.");
                    return(ErrorCodes.ArgumentError);
                }
                else if (processId == 0)
                {
                    Console.Error.WriteLine("--process-id is required");
                    return(ErrorCodes.ArgumentError);
                }

                bool hasConsole = console.GetTerminal() != null;

                if (hasConsole)
                {
                    Console.Clear();
                }

                if (profile.Length == 0 && providers.Length == 0 && clrevents.Length == 0)
                {
                    Console.Out.WriteLine("No profile or providers specified, defaulting to trace profile 'cpu-sampling'");
                    profile = "cpu-sampling";
                }

                Dictionary <string, string> enabledBy = new Dictionary <string, string>();

                var providerCollection = Extensions.ToProviders(providers);
                foreach (EventPipeProvider providerCollectionProvider in providerCollection)
                {
                    enabledBy[providerCollectionProvider.Name] = "--providers ";
                }

                if (profile.Length != 0)
                {
                    var selectedProfile = ListProfilesCommandHandler.DotNETRuntimeProfiles
                                          .FirstOrDefault(p => p.Name.Equals(profile, StringComparison.OrdinalIgnoreCase));
                    if (selectedProfile == null)
                    {
                        Console.Error.WriteLine($"Invalid profile name: {profile}");
                        return(ErrorCodes.ArgumentError);
                    }

                    Profile.MergeProfileAndProviders(selectedProfile, providerCollection, enabledBy);
                }

                // Parse --clrevents parameter
                if (clrevents.Length != 0)
                {
                    // Ignore --clrevents if CLR event provider was already specified via --profile or --providers command.
                    if (enabledBy.ContainsKey(Extensions.CLREventProviderName))
                    {
                        Console.WriteLine($"The argument --clrevents {clrevents} will be ignored because the CLR provider was configured via either --profile or --providers command.");
                    }
                    else
                    {
                        var clrProvider = Extensions.ToCLREventPipeProvider(clrevents, clreventlevel);
                        providerCollection.Add(clrProvider);
                        enabledBy[Extensions.CLREventProviderName] = "--clrevents";
                    }
                }


                if (providerCollection.Count <= 0)
                {
                    Console.Error.WriteLine("No providers were specified to start a trace.");
                    return(ErrorCodes.ArgumentError);
                }

                PrintProviders(providerCollection, enabledBy);

                var process    = Process.GetProcessById(processId);
                var shouldExit = new ManualResetEvent(false);
                var shouldStopAfterDuration = duration != default(TimeSpan);
                var failed           = false;
                var terminated       = false;
                var rundownRequested = false;
                System.Timers.Timer durationTimer = null;

                ct.Register(() => shouldExit.Set());

                var diagnosticsClient = new DiagnosticsClient(processId);
                using (VirtualTerminalMode vTermMode = VirtualTerminalMode.TryEnable())
                {
                    EventPipeSession session = null;
                    try
                    {
                        session = diagnosticsClient.StartEventPipeSession(providerCollection, true, (int)buffersize);
                    }
                    catch (DiagnosticsClientException e)
                    {
                        Console.Error.WriteLine($"Unable to start a tracing session: {e.ToString()}");
                    }

                    if (session == null)
                    {
                        Console.Error.WriteLine("Unable to create session.");
                        return(ErrorCodes.SessionCreationError);
                    }

                    if (shouldStopAfterDuration)
                    {
                        durationTimer           = new System.Timers.Timer(duration.TotalMilliseconds);
                        durationTimer.Elapsed  += (s, e) => shouldExit.Set();
                        durationTimer.AutoReset = false;
                    }

                    var collectingTask = new Task(() =>
                    {
                        try
                        {
                            var stopwatch = new Stopwatch();
                            durationTimer?.Start();
                            stopwatch.Start();

                            using (var fs = new FileStream(output.FullName, FileMode.Create, FileAccess.Write))
                            {
                                Console.Out.WriteLine($"Process        : {process.MainModule.FileName}");
                                Console.Out.WriteLine($"Output File    : {fs.Name}");
                                if (shouldStopAfterDuration)
                                {
                                    Console.Out.WriteLine($"Trace Duration : {duration.ToString(@"dd\:hh\:mm\:ss")}");
                                }

                                Console.Out.WriteLine("\n\n");
                                var buffer = new byte[16 * 1024];

                                while (true)
                                {
                                    int nBytesRead = session.EventStream.Read(buffer, 0, buffer.Length);
                                    if (nBytesRead <= 0)
                                    {
                                        break;
                                    }
                                    fs.Write(buffer, 0, nBytesRead);

                                    if (!rundownRequested)
                                    {
                                        if (hasConsole)
                                        {
                                            lineToClear = Console.CursorTop - 1;
                                            ResetCurrentConsoleLine(vTermMode.IsEnabled);
                                        }

                                        Console.Out.WriteLine($"[{stopwatch.Elapsed.ToString(@"dd\:hh\:mm\:ss")}]\tRecording trace {GetSize(fs.Length)}");
                                        Console.Out.WriteLine("Press <Enter> or <Ctrl+C> to exit...");
                                        Debug.WriteLine($"PACKET: {Convert.ToBase64String(buffer, 0, nBytesRead)} (bytes {nBytesRead})");
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            failed = true;
                            Console.Error.WriteLine($"[ERROR] {ex.ToString()}");
                        }
                        finally
                        {
                            terminated = true;
                            shouldExit.Set();
                        }
                    });
                    collectingTask.Start();

                    do
                    {
                        while (!Console.KeyAvailable && !shouldExit.WaitOne(250))
                        {
                        }
                    } while (!shouldExit.WaitOne(0) && Console.ReadKey(true).Key != ConsoleKey.Enter);

                    if (!terminated)
                    {
                        durationTimer?.Stop();
                        if (hasConsole)
                        {
                            lineToClear = Console.CursorTop;
                            ResetCurrentConsoleLine(vTermMode.IsEnabled);
                        }
                        Console.Out.WriteLine("Stopping the trace. This may take up to minutes depending on the application being traced.");
                        rundownRequested = true;
                        session.Stop();
                    }
                    await collectingTask;
                }

                Console.Out.WriteLine();
                Console.Out.WriteLine("Trace completed.");

                if (format != TraceFileFormat.NetTrace)
                {
                    TraceFileFormatConverter.ConvertToFormat(format, output.FullName);
                }

                return(failed ? ErrorCodes.TracingError : 0);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"[ERROR] {ex.ToString()}");
                return(ErrorCodes.UnknownError);
            }
        }
Exemplo n.º 56
0
 public Timer()
 {
     _timer = new System.Timers.Timer();
 }
Exemplo n.º 57
0
        private void init()
        {
            try
            {
                logger = LogService.Instance();

                workerSynch = new object();

                workerIsBusy = false;

                tiWorker          = new System.Timers.Timer();
                tiWorker.Interval = 10000;
                tiWorker.Elapsed += TiWorker_Elapsed;


                if (!File.Exists(configFolder))
                {
                    initOK = false;
                    logEntry(System.Diagnostics.EventLogEntryType.Error, "DataClient.init failed: " + configFolder + " does not exist");

                    return;
                }

                IniFile ini = new IniFile(configFolder);
                LogService.LogPath = ini.Read("LogPath", "PATH");

                Location       = ini.Read("Location", "GENERAL");
                workerInterval = Int32.Parse(ini.Read("ScanIntervalMinutes", "GENERAL")) * 1000 * 60;
                aliveInterval  = Int32.Parse(ini.Read("AliveIntervalMinutes", "GENERAL")) * 1000 * 60;

                scanFolder    = ini.Read("ScanFolder", "PATH");
                workingFolder = ini.Read("WorkingFolder", "PATH");
                queueFolder   = ini.Read("QueueFolder", "PATH");
                suspectFolder = ini.Read("SuspectFolder", "PATH");


                DataManager.Network.TCPClient.ServerAddress = ini.Read("ServiceAddress", "CONNECTION");
                DataManager.Network.TCPClient.ServerPort    = Int32.Parse(ini.Read("ServicePort", "CONNECTION"));

                DataFile.FileNameRegEx          = ini.Read("FileNameRegEx", "FORMAT");
                DataFile.FileContentHeaderRegEx = ini.Read("ContentHeaderRegEx", "FORMAT");
                DataFile.DateTimeFormat         = ini.Read("ContentDateTimeFormat", "FORMAT");

                aliveAgent = new AliveAgent(aliveInterval, Location);

                String daysToZipLog    = ini.Read("DaysToZip", "HOUSEKEEPING");
                String daysToDeleteLog = ini.Read("DaysToDelete", "HOUSEKEEPING");

                houseKeepingAgent = new FileZipAgent(LogService.LogPath, daysToZipLog, daysToDeleteLog);

                if (!houseKeepingAgent.init())
                {
                    logEntry(System.Diagnostics.EventLogEntryType.Error, "DataClient.init failed: Check housekeeping parameter");
                    initOK = false;

                    return;
                }

                initOK = true;
                logEntry(System.Diagnostics.EventLogEntryType.Information, "DataClient.init ok");
            }
            catch (Exception ex)
            {
                initOK = false;
                logEntry(System.Diagnostics.EventLogEntryType.Error, "DataClient.init failed: " + ex.Message);
            }
        }
Exemplo n.º 58
-32
 public MqttDataLayer(string clientId, string broker)
 {
     ClientId = clientId;
     Broker = broker;
     FakeDataTimer = new System.Timers.Timer(1500) {Enabled = false};
     FakeDataTimer.Elapsed += FakeDataTimer_Elapsed;
 }
Exemplo n.º 59
-44
        /// <summary>
        /// 
        /// </summary>
        public TestClient(ClientManager manager)
        {
            ClientManager = manager;

            updateTimer = new System.Timers.Timer(500);
            updateTimer.Elapsed += new System.Timers.ElapsedEventHandler(updateTimer_Elapsed);

            RegisterAllCommands(Assembly.GetExecutingAssembly());

            Settings.LOG_LEVEL = Helpers.LogLevel.Debug;
            Settings.LOG_RESENDS = false;
            Settings.STORE_LAND_PATCHES = true;
            Settings.ALWAYS_DECODE_OBJECTS = true;
            Settings.ALWAYS_REQUEST_OBJECTS = true;
            Settings.SEND_AGENT_UPDATES = true;
            Settings.USE_ASSET_CACHE = true;

            Network.RegisterCallback(PacketType.AgentDataUpdate, new NetworkManager.PacketCallback(AgentDataUpdateHandler));
            Network.OnLogin += new NetworkManager.LoginCallback(LoginHandler);
            Self.IM += Self_IM;
            Groups.GroupMembersReply += GroupMembersHandler;
            Inventory.OnObjectOffered += new InventoryManager.ObjectOfferedCallback(Inventory_OnInventoryObjectReceived);

            Network.RegisterCallback(PacketType.AvatarAppearance, new NetworkManager.PacketCallback(AvatarAppearanceHandler));
            Network.RegisterCallback(PacketType.AlertMessage, new NetworkManager.PacketCallback(AlertMessageHandler));

            VoiceManager = new VoiceManager(this);

            updateTimer.Start();
        }
Exemplo n.º 60
-56
        internal void Process()
        {
            dbHelper helper = new dbHelper();
            helper.UpdateMissedData();
            FillSettings();
            if (settings != null)
            {
                double timerInterval = 10;
                double.TryParse(settings["EmailSendInterval"], out timerInterval);
                int.TryParse(settings["ThreadCount"], out thread_count);

                if (timerInterval == 0)
                    timerInterval = 0.1;
                collection = new List<mailDetails>();

                emailerTimer = new System.Timers.Timer();
                emailerTimer.Elapsed += new System.Timers.ElapsedEventHandler(GetMail);

                emailerTimer.Interval = 60000 * timerInterval;
                emailerTimer.Enabled = true;
                emailerTimer.AutoReset = true;
                emailerTimer.Start();

            }
        }