Exemplo n.º 1
0
 protected void UnscheduleObsoleteJobs(IEnumerable <DBJobs> jobs2Check)
 {
     try
     {
         var jobs = jobs2Check.Select(d => getJobKeyForJobDescription(d))
                    .Where(d => !d.Equals(thisJobDetail.Key));
         if (jobs != null)
         {
             MainService.thisGlobal.UnsheduleJobs(jobs);
         }
     }
     catch (SchedulerException e)
     {
         log.Error("method: UnscheduleObsoleteJobs: unable to remove the jobs.", e);
     }
 }
Exemplo n.º 2
0
        //End

        //无法找到资源事件(404)
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception objExp = HttpContext.Current.Server.GetLastError();

            WebLog.Error(Request.UserHostAddress, Request.Url.ToString(), objExp.Message.ToString(), objExp, 0, "");
            Response.Redirect("/home/error?msg=" + objExp.Message.ToString());
        }
Exemplo n.º 3
0
        /// <summary>
        /// 记录完整错误信息
        /// by:willian date:2016-9-28
        /// </summary>
        /// <param name="t"></param>
        /// <param name="ex"></param>
        /// <param name="loginId"></param>
        /// <param name="loginUserName"></param>
        public static void WriteLog(Type t, Exception ex, int loginId = 0, string loginUserName = "")
        {
            string  Ip         = Tools.Utility.CheckClient.GetIP();
            string  RequestUrl = Tools.Utility.CheckClient.GetNowPage();
            IWebLog WebLog     = WebLogHelper.GetLogger(t);

            WebLog.Error(Ip, RequestUrl, ex.Message.ToString(), ex, loginId, loginUserName);
        }
Exemplo n.º 4
0
        public virtual bool Initialize()
        {
            log.Info("------- Initializing Scheduler -------------------");
            try
            {
                XTradeConfig config     = MainService.thisGlobal.Container.Resolve <XTradeConfig>();
                var          properties = config.Quartz();

                // First we must get a reference to a scheduler
                sf    = new StdSchedulerFactory(properties);
                sched = sf.GetScheduler().Result;
                // All of the jobs have been added to the scheduler, but none of the jobs
                // will run until the scheduler has been started
                sched.Start();

                while (!sched.IsStarted)
                {
                    log.Info("Waiting for scheduler to start.");
                    Thread.Sleep(1000);
                }

                log.Info("IsStarted=" + sched.IsStarted);
                log.Info("InstanceId=" + sched.SchedulerInstanceId);
                log.Info("SchedulerName=" + sched.SchedulerName);
                SchedulerMetaData metadata = sched.GetMetaData().Result;
                log.Info("IS REMOTE (CLUSTERED )=" + metadata.SchedulerRemote);
                isClustered = metadata.SchedulerRemote;

                RunJobSupervisor();
            }
            catch (Exception ex)
            {
                log.Error("Error Initializing Scheduler: " + ex.Message);
                bInitialized = false;
                return(bInitialized);
            }

            bInitialized = true;
            return(bInitialized);
        }
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                thisJobDetail = context.JobDetail;
                sched         = context.Scheduler;
                if (MainService.thisGlobal.IsDebug())
                {
                    log.Info("TerminalMonitoringJob: ------- Monitor Terminals -------");
                }

                DataService dataService = MainService.thisGlobal.Container.Resolve <DataService>();

                IEnumerable <Terminal> results = (IEnumerable <Terminal>)dataService.GetObjects(EntitiesEnum.Terminal);

                results = results.Where(x => (x.Retired == false) &&
                                        (x.Stopped == false));
                foreach (var resRow in results)
                {
                    var oPath = resRow.FullPath;
                    if (oPath != null)
                    {
                        strPath = oPath;
                        string    appName     = Path.GetFileNameWithoutExtension(strPath);
                        Process[] processlist = Process.GetProcessesByName(appName);
                        if (processlist == null || processlist.Length == 0)
                        {
                            procUtil.ExecuteAppAsLoggedOnUser(strPath, "");
                        }
                        else
                        {
                            var procL = processlist.Where(d =>
                                                          d.MainModule.FileName.Equals(strPath, StringComparison.InvariantCultureIgnoreCase));
                            if (procL == null || procL.Count() == 0)
                            {
                                procUtil.ExecuteAppAsLoggedOnUser(strPath, "");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error($"TerminalMonitoringJob Failed: {ex}");
            }

            await Task.CompletedTask;
        }
Exemplo n.º 6
0
        public void StartProcessInNewThread(string fileName, string logFile, string appname)
        {
            log.Info($"Starting deploy script {fileName}");
            var    runTime   = SystemTime.UtcNow();
            Thread newThread = new Thread(Func =>
            {
                try
                {
                    //CloseTerminal(appname);
                    string CmdLineArgs = $" > {logFile}";

                    var p = ExecuteAppAsLoggedOnUser(fileName, "");
                    if (p != null)
                    {
                        p.WaitForExit();
                        DateTimeOffset now = SystemTime.UtcNow();
                        TimeSpan duration  = now - runTime;
                        log.Info($"Deploying finished for script {fileName} for {duration.Seconds} seconds.");
                    }

                    /*
                     *  ProcessStartInfo process = new ProcessStartInfo();
                     *  process.FileName = fileName;
                     *  process.Arguments = $" > {logFile}";
                     *  process.CreateNoWindow = true;
                     *  process.ErrorDialog = false;
                     *  process.RedirectStandardError = true;
                     *  process.RedirectStandardInput = true;
                     *  process.RedirectStandardOutput = true;
                     *  process.UseShellExecute = false;
                     *  process.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                     *  Process p = Process.Start(process);
                     *  p.WaitForExit();
                     */
                }
                catch (Exception e)
                {
                    log.Error("Thread run Process Error: " + e.ToString());
                }
            });

            newThread.Start();
        }
Exemplo n.º 7
0
        public List <CurrencyInfo> GetCurrencies()
        {
            List <CurrencyInfo> result = new List <CurrencyInfo>();

            try
            {
                currencies.GetAll().ForEach(currency =>
                {
                    var curr     = new CurrencyInfo();
                    curr.Id      = (short)currency.Id;
                    curr.Name    = currency.Name;
                    curr.Retired = currency.Enabled.Value > 0 ? false : true;
                    result.Add(curr);
                });
            }
            catch (Exception e)
            {
                log.Error("Error: GetCurrencies: " + e);
            }

            return(result);
        }
Exemplo n.º 8
0
        public List <string> ProcessStringData(Dictionary <string, string> paramsList, List <string> inputData)
        {
            var list = new List <string>();

            if (!paramsList.ContainsKey("func"))
            {
                log.Error("ProcessStringData: Params error");
                return(list);
            }

            string func = paramsList["func"];

            try
            {
                switch (func)
                {
                case "NextNewsEvent":
                {
                    DateTime date;
                    DateTime.TryParseExact(paramsList["time"], xtradeConstants.MTDATETIMEFORMAT,
                                           CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out date);

                    string symbolStr = paramsList["symbol"];
                    // int BeforeMin = Int32.Parse(paramsList["before"]);
                    byte          minImportance = byte.Parse(paramsList["importance"]);
                    NewsEventInfo info          = null;
                    if (xtrade.GetNextNewsEvent(date, symbolStr, minImportance, ref info))
                    {
                        //log.Info( info.RaiseDateTime.ToString(MainService.MTDATETIMEFORMAT) + " Got news: (" + info.Name + ") Importance:  " + info.Importance.ToString());
                        list.Add(info.Currency);
                        list.Add(info.Importance.ToString());
                        list.Add(info.RaiseDateTime);
                        list.Add(info.Name);
                    }
                }
                break;

                case "GetTodayNews":
                {
                    DateTime date;
                    DateTime.TryParseExact(paramsList["time"], xtradeConstants.MTDATETIMEFORMAT,
                                           CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out date);
                    string symbolStr     = paramsList["symbol"];
                    byte   minImportance = byte.Parse(paramsList["importance"]);
                    int    i             = 0;
                    var    news          = xtrade.GetTodayNews(date, symbolStr, minImportance);
                    foreach (var info in news)
                    {
                        list.Add(info.Currency);
                        list.Add(info.Importance.ToString());
                        list.Add(info.RaiseDateTime);

                        if (i == news.Count - 1)
                        {
                            list.Add(info.Name);
                        }
                        else
                        {
                            list.Add(info.Name + "~");     // Delimiter
                        }
                        i++;
                    }
                }
                break;

                case "Somefunc":
                {
                }
                break;
                }
            }
            catch (Exception e)
            {
                log.Error("ProcessStringData Error:" + e);
            }

            return(list);
        }
Exemplo n.º 9
0
        public bool Connect(Terminal toTerminal)
        {
            try
            {
                if (Trader == null)
                {
                    // создаем подключение
                    Trader = new QuikTrader {
                        IsDde = false, Path = toTerminal.FullPath
                    };

                    /*
                     * {
                     *  LuaFixServerAddress = Address.Text.To<EndPoint>(),
                     *  LuaLogin = Login.Text,
                     *  LuaPassword = Password.Password.To<SecureString>()
                     * };
                     */

                    Trader.LogLevel = LogLevels.Info;

                    _logManager.Sources.Add(Trader);
                    _logManager.Listeners.Add(new FileLogListener("XTrade.Quik.log"));

                    // отключение автоматического запроса всех инструментов.
                    Trader.RequestAllSecurities = false;

                    // возводим флаг, что соединение установлено
                    _isConnected = true;

                    // переподключение будет работать только во время работы биржи РТС
                    // (чтобы отключить переподключение когда торгов нет штатно, например, ночью)
                    Trader.ReConnectionSettings.WorkingTime = ExchangeBoard.Forts.WorkingTime;

                    // подписываемся на событие об успешном восстановлении соединения
                    Trader.Restored += () =>
                    {
                        Log("Connection restored");
                    }; // MessageBox.Show(this, LocalizedStrings.Str2958));

                    // подписываемся на событие разрыва соединения
                    Trader.ConnectionError += error =>
                    {
                        Log(error.ToString());
                    }; //this.GuiAsync(() => MessageBox.Show(this, error.ToString()));

                    // подписываемся на ошибку обработки данных (транзакций и маркет)
                    Trader.Error += error => { Log(error.ToString()); };
                    //	this.GuiAsync(() => MessageBox.Show(this, error.ToString(), "Ошибка обработки данных"));

                    // подписываемся на ошибку подписки маркет-данных
                    Trader.MarketDataSubscriptionFailed += (security, msg, error) => { Log(error.ToString()); };
                    // this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));

                    Trader.NewSecurity += Securities.Add;
                    //Trader.NewMyTrade += _myTradesWindow.TradeGrid.Trades.Add;
                    //Trader.NewTrade += _tradesWindow.TradeGrid.Trades.Add;
                    Trader.NewOrder     += Orders.Add;
                    Trader.NewStopOrder += Orders.Add;
                    //Trader.OrderRegisterFailed += _ordersWindow.OrderGrid.AddRegistrationFail;
                    //Trader.StopOrderRegisterFailed += _stopOrdersWindow.OrderGrid.AddRegistrationFail;
                    Trader.OrderCancelFailed += fail => { Log(fail.Error.Message); };
                    // this.GuiAsync(() => MessageBox.Show(this, fail.Error.Message, LocalizedStrings.Str2981));
                    Trader.StopOrderCancelFailed += fail => { Log(fail.Error.Message); };
                    //this.GuiAsync(() => MessageBox.Show(this, fail.Error.Message, LocalizedStrings.Str2981));
                    Trader.NewPortfolio += Portfolios.Add;
                    Trader.NewPosition  += Positions.Add;

                    Trader.MassOrderCancelFailed += (transId, error) => { Log(error.ToString()); };
                    //this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716));

                    // устанавливаем поставщик маркет-данных
                    // _securitiesWindow.SecurityPicker.MarketDataProvider = Trader;

                    //ShowSecurities.IsEnabled = ShowTrades.IsEnabled =
                    //    ShowMyTrades.IsEnabled = ShowOrders.IsEnabled =
                    //        ShowPortfolios.IsEnabled = ShowStopOrders.IsEnabled = true;

                    Trader.Connect();

                    _isConnected = true;

                    bStopJobs = false;

                    terminal = toTerminal;
                    //var advs = MainService.thisGlobal.GetAdvisersByTerminal(terminal.Id);
                    Portfolio portfolio = null;
                    try
                    {
                        var res = service.GetAdvisers().Where(x => x.TerminalId == toTerminal.Id);
                        foreach (var adv in res)
                        {
                            if (!adv.Disabled)
                            {
                                QUIKExpert quikE = new QUIKExpert(adv);
                                advisers.Add(adv.Id, quikE);
                                service.SubscribeToSignals(adv.Id);
                                if (string.IsNullOrEmpty(adv.State))
                                {
                                    adv.State = quikE.Serialize();
                                    service.UpdateAdviser(adv);
                                }

                                if (portfolio == null)
                                {
                                    portfolio = Portfolios.Where(x => x.Name == quikE.PortfolioName).FirstOrDefault();
                                }
                            }
                        }

                        Log("Successfully connected to <QUIK>");
                    }
                    catch (Exception e)
                    {
                        log.Error(e);
                    }

                    return(true);
                }

                Trader.Disconnect();

                _isConnected = false;
                return(false);
            }
            catch (Exception e)
            {
                Log(e.ToString());
            }

            return(false);
        }
Exemplo n.º 10
0
        public List <Wallet> GetWalletsState(DateTime date)
        {
            var result = new List <Wallet>();

            try
            {
                result = data.GetWalletsState(date);
            }
            catch (Exception e)
            {
                log.Error("Error: GetWalletsState: " + e);
            }

            return(result);
        }